Data Structures & AlgorithmsVery hard
To count subarrays with equal numbers of even and odd values, which transformation makes the problem a zero-sum subarray problem?
- A. Map each even value to +1 and each odd value to −1, so balance equals zero exactly when the counts match.
- B. Map each value to its square root.
- C. Sort the array and compare the two halves.
- D. Keep only the even values.
Correct answer: A. Map each even value to +1 and each odd value to −1, so balance equals zero exactly when the counts match.
With +1 for evens and −1 for odds, equal counts give a sum of zero, which the prefix-sum hash counts in linear time. The other transformations lose the balance information.
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
- The function below computes the length of a longest increasing subsequence. python import bisect a = [4, 4, 1, 5, 5, 6, 2, 7] t = [] for x…
- A maximum subarray sum routine is written as follows. python def bestsub(a): cur = best = a[0] for x in a[1:]: cur = max(x, cur + x) best…
- A knapsack routine is written as follows (items are (weight, value)). python items = [(2, 3), (3, 4), (4, 5)] W = 6 dp = [0] (W + 1) for…
- Two DP loops count ways to pay 5 using coins 1 and 2 (the order of coins in the sum is ignored in the first version). python coins = [1…
- A monotonic deque computes the minimum of each window of size 3. python from collections import deque a = [4, 2, 12, 11, -5, 7] k = 3 dq =…
- A DP counts the minimum number of coins to pay exactly 11 with coins [2, 5], returning −1 if impossible. python INF = float('inf') coins =…