Remainder-Sum Windows and Bracket Cleanup
Arrays & HashingAuto-graded · 23 test casesLast updated
Count contiguous subarrays whose sum has a given remainder using prefix-sum remainders, and delete the fewest parentheses to balance a string in a fixed, deterministic way.
Implement one function that solves two independent subtasks and returns both answers together.
Part A: Subarrays with a given remainder
You get a list of integers values, a modulus modulus, and a target remainder target. Count the contiguous, non-empty subarrays whose sum, taken modulo modulus, equals target.
- Subarrays are distinguished by their position, so two equal subarrays at different positions are counted separately.
- The remainder is always in the range
0tomodulus - 1, even for negative sums. For example, withmodulus = 3, a sum of-1has remainder2.
Part B: Minimal bracket cleanup
You get a string text made of lowercase letters, ( and ). Delete as few parentheses as possible so that the remaining parentheses are balanced, without reordering any characters. Letters are never deleted.
A string is balanced when, in every prefix, the number of ( is at least the number of ), and the totals over the whole string are equal.
Several minimal answers can exist, so to make the output unique, build it exactly like this:
- Scan left to right while tracking the number of currently open
(. Drop every)that appears when that number is0. Keep everything else. - If some
(remain unmatched after this scan, sayeof them, remove the lasteoccurrences of(in the string produced by step 1.
Return the resulting string.
Return value
Return a list of two items: [count, cleaned_text], where count is the integer from Part A and cleaned_text is the string from Part B.
Constraints
0 <= len(values) <= 10^5- Each value is an integer that fits in a normal 64-bit signed integer; it may be negative or zero.
1 <= modulus <= 10^40 <= target < modulustextcontains only lowercase letters,(and). It may be empty.- Aim for
O(n + modulus)time for Part A and linear time for Part B.
Examples
Example 1
Input: count_remainder_windows_and_fix_brackets([1, 1, 1], 3, 0, 'lee(t(c)o)de')
Output: [1, 'lee(t(c)o)de']
Example 2
Input: count_remainder_windows_and_fix_brackets([2, -1, 2], 3, 1, 'a)b(c)d')
Output: [2, 'ab(c)d']
Example 3
Input: count_remainder_windows_and_fix_brackets([], 1, 0, ')((')
Output: [0, '']
Hints
Hint 1
Write each subarray sum as a difference of two prefix sums. The condition on the remainder then becomes a condition on the remainders of two prefix sums.
Hint 2
While scanning, keep a count array indexed by prefix remainder. The prefix remainder you look up for the current prefix is (current - target) mod modulus. Don't forget the empty prefix, whose remainder is 0.
Hint 3
For the parentheses, first drop every `)` that has no open `(` before it. Any `(` still unmatched are then removed from the right end, which keeps all earlier prefixes valid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: prefix-sum remainders
Let P[0] = 0 and P[k] be the sum of the first k values. The subarray from index i to j has sum P[j+1] - P[i]. It qualifies when
(P[j+1] - P[i]) mod m == target, which is equivalent to P[i] mod m == (P[j+1] - target) mod m.
Scan the array once while maintaining the current prefix remainder and an array seen where seen[r] is the number of earlier prefixes with remainder r. At each new prefix, add seen[(cur - target) mod m] to the answer, then record the current remainder. Start with seen[0] = 1 for the empty prefix, so subarrays starting at index 0 are counted.
Every subarray corresponds to exactly one pair of prefixes (earlier, later). When the later prefix is processed, seen contains exactly the earlier prefixes, and the congruence is an exact equivalence. So each qualifying subarray is counted once and nothing else is counted. Python's % returns a non-negative result for a positive modulus, so negative sums are handled automatically.
Part B: greedy balance
A string is balanced exactly when no prefix has more ) than ( and the totals match.
- Scanning left to right, a
)seen when no(is open can never be matched by anything, so it must be deleted. Deleting these)is therefore forced. - After that scan, no prefix is in deficit.
eunmatched(remain, and they must be deleted too, soefurther deletions are required. - Deleting the last
eoccurrences of(is safe. Any prefix that includes only some of the removed(still has enough surplus(before it, because those removed brackets were the ones left over at the end of the scan. So the result stays balanced.
The total number of deletions equals the forced ) deletions plus e, which matches the lower bound, so the result is minimal. The fixed rule (last e openings) makes the answer unique.
Complexity
- Part A: time
O(n + m), spaceO(m). - Part B: time
O(len(text)), spaceO(len(text))for the output.
Reference solution
from typing import List
def count_remainder_windows_and_fix_brackets(values: List[int], modulus: int, target: int, text: str) -> List[object]:
# Part A: prefix-sum remainders.
seen = [0] * modulus
seen[0] = 1 # empty prefix
prefix = 0
total = 0
for v in values:
prefix = (prefix + v) % modulus
total += seen[(prefix - target) % modulus]
seen[prefix] += 1
# Part B: drop unmatched ')' while scanning.
kept = []
open_count = 0
for ch in text:
if ch == '(':
kept.append(ch)
open_count += 1
elif ch == ')':
if open_count > 0:
kept.append(ch)
open_count -= 1
else:
kept.append(ch)
# Remove the last `open_count` occurrences of '('.
if open_count > 0:
rebuilt = []
for ch in reversed(kept):
if ch == '(' and open_count > 0:
open_count -= 1
else:
rebuilt.append(ch)
kept = rebuilt[::-1]
return [total, ''.join(kept)]