Question Bank
JavaScript X and O Balance: Two Approaches Quiz
Difficulty: Medium
Check whether a string contains an equal count of `x` and `o` (case-insensitive), two ways (regex match-array length and filter + length), plus companions on counting any pair of characters and treating empty input.
JavaScript X and O Balance: Two Approaches Quiz
Check whether a string contains an equal count of `x` and `o` (case-insensitive), two ways (regex match-array length and filter + length), plus companions on counting any pair of characters and treating empty input.
636 views
15
Implement hasEqualXO(str) using String.prototype.match with the /g and /i flags. Compare the lengths of the match arrays for x and o. Treat "no x and no o" as balanced (return true).
Examples
Example 1:
Input: 'xoxo'
Output: true
Explanation: 2 x's and 2 o's.Example 2:
Input: 'loovex'
Output: false
Explanation: 2 o's but only 1 x.Example 3:
Input: 'abc'
Output: true
Explanation: zero of each is still equal.Implement hasEqualXO(str) again by splitting the string into characters and using Array.prototype.filter with a per-letter regex on each character. Compare the two filtered lengths. Explain why this is more readable but produces more intermediate allocations than the match-array form.
Examples
Example 1:
Input: 'abcx12o3Xdefo'
Output: true
Explanation: 2 x's (x and X) and 2 o's.Generalise to hasEqualCounts(str, a, b) that returns true when the case-insensitive counts of single characters a and b match. Treat any non-letter input character normally (no special handling). Use a single linear pass.
Examples
Example 1:
Input: ('aabb', 'a', 'b')
Output: true
Explanation: 2 of each.Example 2:
Input: ('aAbB!@', 'a', 'b')
Output: true
Explanation: case-insensitive matches: 2 a's, 2 b's.Example 3:
Input: ('aab', 'a', 'b')
Output: false
Explanation: 2 a's vs 1 b.Implement letterHistogram(str) returning an object mapping each lowercase letter present in the string to its occurrence count. Use Array.prototype.reduce. Ignore non-letter characters.
Examples
Example 1:
Input: 'Hello, World!'
Output: { h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1 }
Explanation: case-insensitive count; punctuation and spaces are skipped.