Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA
Problem: How many subarrays of [1, 2, 2, 3] have max minus min at most 1? Run the code.
Problem: How many subarrays of [1, 2, 2, 3] have max minus min at most 1? Run the code.
a = [1, 2, 2, 3] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a) + 1) if max(a[i:j]) - min(a[i:j]) <= 1))What is printed?
- A. 9
- B. 5
- C. 10
- D. 4
Correct answer: A. 9
The 4 singletons, the pairs [1,2], [2,2], [2,3] and the triples [1,2,2], [2,2,3] qualify; the full array has spread 2, so 9. Using < 1 keeps only equal-valued windows (5), counting all 10 subarrays ignores the condition, and requiring a spread of exactly 1 gives 4.
More Coding Interview Problems questions
- Problem: How many peaks (elements strictly greater than both neighbours, excluding the two ends) does [1, 3, 2, 4, 1, 5] have? Run the…
- Problem: What does this run-length encoder print for 'aaabccdd'? python s = 'aaabccdd' out = [] i = 0 while i < len(s): j = i while j <…
- Problem: Check bracket balance for '([]{})' and '([)]' with a stack. What is printed? python def ok(s): pairs = {')': '(', ']': '[', '}'…
- Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes…
- Problem: Using at most one flip of a 0 to 1, what is the longest run of consecutive 1s in [1, 0, 1, 1, 0, 1]? Run the sliding-window code…
- Problem: How many unordered pairs of words in ['abc', 'bca', 'xyz', 'cab'] are anagrams of each other? Run the code. python from itertools…