Data Structures & AlgorithmsVery hardCodeforces Div2 B-D · ICPC regional
A binary array of length 10^6 needs its longest contiguous subarray with equally many 0s and 1s. Which approach is correct and linear?
- A. Map 0 to -1, keep prefix sums, and store the first index of each prefix value in a hashmap; the longest gap between equal prefixes is the answer
- B. Two pointers that always expand the window, because the balance is monotone
- C. Sorting the array, then taking the longest run of equal values
- D. Binary search on the window length with a fixed-size check of counts only at the endpoints
Correct answer: A. Map 0 to -1, keep prefix sums, and store the first index of each prefix value in a hashmap; the longest gap between equal prefixes is the answer
Rewriting 0 as -1 turns the balance condition into a zero-sum subarray, which prefix sums with first occurrences solve in one pass. The balance is not monotone, so two pointers fail.
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
- For an array of 10^5 integers you must count index pairs with a[i] XOR a[j] equal to a fixed K. Which method is the best fit?
- How many contiguous subarrays of [2, 4, 6, 8] have every element divisible by 4?
- What is the length of the longest contiguous subarray of [3, 1, 4, 1, 5, 9, 2, 6] whose sum is divisible by 3?
- How many index pairs i < j of [2, 8, 3, 12, 6, 18] have a product that is a perfect square?
- Meetings are [0,30), [5,10), [15,20), [35,45), [40,50). A meeting ending at time t and another starting at t can share a room. What is the…
- What is the sum of the minimum over every window of size 2 in [5, 2, 8, 1, 9]?