Data Structures & AlgorithmsVery hard
In the 'longest window with equal numbers of high and low values' problem, what turns the condition into a standard prefix-sum problem?
- A. Sort the values and compare the halves.
- B. Count the high values and divide by two.
- C. Assign +1 to one class and −1 to the other, so equal counts become a zero-sum subarray.
- D. Remove the middle value.
Correct answer: C. Assign +1 to one class and −1 to the other, so equal counts become a zero-sum subarray.
The balance trick reduces 'equal counts' to 'sum zero', and then first-occurrence prefix hashing finds the longest such block in linear time.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- When two consecutive windows of length 3 are compared, why does equal sums reduce to a single element comparison?
- Why does a pair (i<j) with A[i] AND A[j] = 0 require disjoint sets of set bits?
- Among pairs with A[i] ≠ A[j] and A[i] XOR A[j] = 0, how many exist?
- Why can the number of distinct OR values over all subarrays of an array be small even for long arrays?
- In the array [2, 5, 5, 3, 5, 2] the maximum of a subarray is taken. How many contiguous subarrays have their maximum value occurring…
- What is the sum of the minimum over all contiguous subarrays of [3, 1, 2, 4] that have length at least 2?