Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT work here, while prefix sums + hash map do?
- A. Sliding windows only work on sorted arrays
- B. With negative values, extending the window can decrease the sum, so shrinking/expanding decisions are not monotonic
- C. A hash map is needed because k can exceed 10⁴
- D. Sliding windows need O(n²) time for counting problems
Correct answer: B. With negative values, extending the window can decrease the sum, so shrinking/expanding decisions are not monotonic
A window works when adding an element always increases (or never decreases) the sum, so a too-large window can only be fixed by shrinking. Negatives break that monotonicity. Prefix sums with a count map handle any sign in O(n). Sorting is irrelevant (it destroys contiguity).
More Coding Interview Problems questions
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…