Subarray Remainder Counting and Minimal Parenthesis Removal
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement solve_array_and_parentheses(nums, K, R, s) to solve two independent tasks in a single call and return [subarray_count, balanced_text]:
-
Task 1 — Count subarrays with a target modulo remainder: Given an integer list
nums(which may include negative values, zeros, and positive values), a positive divisorK, and a target remainderR(0 <= R < K), computesubarray_count: how many non-empty contiguous subarraysnums[i..j](0 <= i <= j < len(nums)) satisfy:text sum(nums[i..j]) mod K == RHeremod Kdenotes the standard non-negative mathematical remainder in0 .. K - 1(for instance,-5 mod 4 == 3and-1 mod 4 == 3). Your solution for Task 1 must run inO(len(nums))time andO(K)auxiliary space. -
Task 2 — Remove the fewest parentheses to balance a string: Given a string
sconsisting of lowercase English letters ('a'–'z'),'(', and')', returnbalanced_text: any valid string formed by deleting the minimum possible number of'('and')'characters so that the remaining parentheses are properly balanced while preserving every letter and keeping all surviving characters in their original relative order. Your solution for Task 2 must run inO(len(s))time and useO(1)auxiliary space beyond the returned output string itself.
Examples
Example 1
Input:
nums = [4, 1, 2, 3], K = 5, R = 0, s = "co(d(e)r)s"
Output:
[3, "co(d(e)r)s"]
Explanation:
- Task 1: Among the 10 non-empty contiguous subarrays of [4, 1, 2, 3], three have sums divisible by 5 (R = 0): [4, 1] (sum 5), [4, 1, 2, 3] (sum 10), and [2, 3] (sum 5).
- Task 2: "co(d(e)r)s" already has balanced parentheses, so 0 deletions are needed.
Example 2
Input:
nums = [3, -5, 4], K = 4, R = 3, s = "x)y(z)w("
Output:
[3, "xy(z)w"]
Explanation:
- Task 1: Three contiguous subarrays leave remainder 3 modulo 4: [3] (3 mod 4 == 3), [-5] (-5 = -2 * 4 + 3, so -5 mod 4 == 3), and [-5, 4] (-1 mod 4 == 3).
- Task 2: The ')' after 'x' has no preceding '(', and the trailing '(' after 'w' has no following ')'. Deleting those two characters leaves "xy(z)w".
Example 3
Input:
nums = [], K = 2, R = 1, s = "))m(("
Output:
[0, "m"]
Explanation:
- Task 1: An empty list has 0 non-empty subarrays.
- Task 2: Neither of the leading ')' characters nor either of the trailing '(' characters can form a matched pair, so all four parentheses are removed and "m" remains.
Constraints
0 <= len(nums) <= 100,000-10^9 <= nums[i] <= 10^91 <= K <= 100,0000 <= R < K0 <= len(s) <= 100,000scontains only lowercase ASCII letters ('a'–'z'),'(', and')'.- Required complexity:
O(len(nums))time andO(K)space for Task 1;O(len(s))time andO(1)extra space beyond the output string for Task 2.
Step-by-step walkthrough
Understand both tasks and constraints
solve_array_and_parentheses(nums, K, R, s)bundles two independent algorithmic tasks and returns[subarray_count, balanced_text]:- Task 1 — Subarrays with given remainder (
count_subarrays_by_remainder): Given an integer arraynums(which may contain negative numbers and zeros), a modulusK >= 1, and a target remainder0 <= R < K, count how many non-empty contiguous subarraysnums[i..j]satisfysum(nums[i..j]) mod K == RinO(n)time andO(K)space. Note that we use the standard mathematical remainder in[0, K - 1], so-5 mod 4 == 3. - Task 2 — Minimum parentheses removal: Given a string
sof lowercase letters,'(', and')', delete as few parentheses as possible so the remaining string is balanced while keeping every letter and preserving relative order, inO(n)time andO(1)extra space beyond the output.
- Task 1 — Subarrays with given remainder (
Why naive solutions fall short
- Task 1 brute force: Looping over every start index
iand end indexjchecksn * (n + 1) / 2subarrays, takingO(n^2)time — roughly5 * 10^9steps whenn = 10^5. - Task 2 brute force or stack: Trying subsets of parentheses to delete takes exponential time. Even the classic stack-of-indices approach pushes up to
nindices whens = "(((...(", usingO(n)auxiliary memory instead ofO(1)extra space beyond the output.
- Task 1 brute force: Looping over every start index
Task 1 key idea: turn subarray sums into prefix remainders
Define the prefix sums
P[0] = 0andP[t] = nums[0] + nums[1] + ... + nums[t - 1]. Any contiguous subarraynums[i..j]is the difference between two prefix sums:Index: 0 1 ... i i+1 ... j nums: [ a0, a1, ..., ai, ..., aj ] |<----- P[i] ----->|<-- nums[i..j] ----->| |<--------------- P[j+1] --------------->| sum(nums[i..j]) = P[j+1] - P[i]When does
P[j+1] - P[i]leave remainderRupon division byK? Rearrange the modular equation soiandj + 1sit on opposite sides:(P[j+1] - P[i]) mod K == R <=> P[j+1] - P[i] - R is a multiple of K <=> P[i] and (P[j+1] - R) leave the EXACT SAME remainder mod K <=> P[i] mod K == (P[j+1] - R) mod KAs we scan
numsleft to right maintainingprefix_rem = P[j+1] mod K, we want to know how many earlier prefixesP[i](0 <= i <= j) had remainder(prefix_rem - R) mod K: - Storeremainder_counts[r]= how many prefixes seen so far have remainderr. - Start withremainder_counts = {0: 1}to represent the empty prefixP[0] = 0(so subarrays starting at index0are counted). - Queryremainder_countsbefore recording the currentprefix_rem, soP[j+1]never pairs with itself as an empty subarray!Implement Task 1: count_subarrays_by_remainder
Python's
%operator with positiveKalways produces a non-negative remainder in[0, K - 1](even whenprefix_rem + numorprefix_rem - Ris negative), and the dictionary holds at mostmin(n + 1, K)keys.from typing import Dict, List def count_subarrays_by_remainder(nums: List[int], K: int, R: int) -> int: """Count contiguous non-empty subarrays nums[i..j] with sum(nums[i..j]) mod K == R.""" # remainder_counts: dict {rem: count_of_prefixes_seen_so_far} where 0 <= rem < K. # Seed with {0: 1} for the empty prefix P[0] = 0 so subarrays starting at index 0 match. remainder_counts: Dict[int, int] = {0: 1} prefix_rem = 0 matching_subarrays = 0 for num in nums: # Python's % operator always returns a canonical remainder in [0, K - 1], even for negatives. prefix_rem = (prefix_rem + num) % K # (P[j+1] - P[i]) mod K == R <=> P[i] mod K == (P[j+1] - R) mod K. # Look up BEFORE inserting prefix_rem so empty subarrays (i == j+1) are never counted. needed_prev_rem = (prefix_rem - R) % K matching_subarrays += remainder_counts.get(needed_prev_rem, 0) remainder_counts[prefix_rem] = remainder_counts.get(prefix_rem, 0) + 1 return matching_subarraysTask 2 key idea: count valid `()` pairs in O(1) space
A parentheses string is balanced if every
')'closes an earlier'('and no'('is left unclosed at the end. We can solve this cleanly in two linear passes using only integer counters beyond the output:- Pass 1 — Count total valid
()pairs: Scan left to right trackingunmatched_open. Each'('incrementsunmatched_open; each')'that seesunmatched_open > 0matches one'('(unmatched_open -= 1,valid_pairs += 1), while any')'withunmatched_open == 0has nothing to close and must be deleted. - Pass 2 — Emit the exact output: Now we know the balanced answer contains all letters plus exactly
valid_pairsopening'('s andvalid_pairsclosing')'s. Which'('s should we keep? Keeping the firstvalid_pairsoccurrences of'('(and skipping any leftover'('s on the right) ensures every valid')'still has an earlier'('partner waiting for it!
Example: s = "a)b(c(d)e" Pass 1: 'a' -> letter ')' -> unmatched_open == 0 (cannot match, skip) '(' -> unmatched_open = 1 '(' -> unmatched_open = 2 ')' -> unmatched_open > 0 -> unmatched_open = 1, valid_pairs = 1 Result of Pass 1: valid_pairs = 1 Pass 2 (open_to_keep = 1, open_unclosed = 0): 'a' -> keep 'a' ')' -> open_unclosed == 0 -> skip 'b' -> keep 'b' '(' -> open_to_keep == 1 > 0 -> keep '(', open_to_keep = 0, open_unclosed = 1 'c' -> keep 'c' '(' -> open_to_keep == 0 -> skip surplus '('! 'd' -> keep 'd' ')' -> open_unclosed == 1 > 0 -> keep ')', open_unclosed = 0 'e' -> keep 'e' Output: "ab(cd)e"Because
output_charsonly appends characters that appear in the final string, even an input like"(" * 100000(whose output is"") allocates0characters inoutput_chars— trueO(1)extra space beyond the output!- Pass 1 — Count total valid
Implement Task 2: remove_min_parentheses
from typing import List def remove_min_parentheses(s: str) -> str: """Delete the minimum number of '(' and ')' so s becomes balanced in O(1) extra space.""" # Pass 1: Count how many complete '()' pairs can be formed using O(1) integer state. unmatched_open = 0 valid_pairs = 0 for ch in s: if ch == "(": unmatched_open += 1 elif ch == ")": # Only a ')' with an earlier unmatched '(' can form a valid pair. if unmatched_open > 0: unmatched_open -= 1 valid_pairs += 1 # Pass 2: Emit only characters belonging to the final answer (zero extra slots beyond output). # Keeping the FIRST valid_pairs occurrences of '(' guarantees every valid ')' still has an # earlier '(' partner, while dropping the rightmost surplus '(' characters automatically. output_chars: List[str] = [] open_to_keep = valid_pairs open_unclosed = 0 for ch in s: if ch == "(": if open_to_keep > 0: open_to_keep -= 1 open_unclosed += 1 output_chars.append("(") elif ch == ")": if open_unclosed > 0: open_unclosed -= 1 output_chars.append(")") else: output_chars.append(ch) return "".join(output_chars)Trace Example 2 on both tasks
Let's walk through Example 2:
nums = [3, -5, 4],K = 4,R = 3,s = "x)y(z)w(".Task 1: nums = [3, -5, 4], K = 4, R = 3 Start: remainder_counts = {0: 1}, prefix_rem = 0, matching_subarrays = 0 1. num = 3: prefix_rem = (0 + 3) % 4 = 3, needed = (3 - 3) % 4 = 0 -> +1 (subarray [3]) remainder_counts = {0: 1, 3: 1} 2. num = -5: prefix_rem = (3 - 5) % 4 = 2, needed = (2 - 3) % 4 = 3 -> +1 (subarray [-5]) remainder_counts = {0: 1, 3: 1, 2: 1} 3. num = 4: prefix_rem = (2 + 4) % 4 = 2, needed = (2 - 3) % 4 = 3 -> +1 (subarray [-5, 4]) remainder_counts = {0: 1, 3: 1, 2: 2} Total matching_subarrays = 3 Task 2: s = "x)y(z)w(" Pass 1: ')' after 'x' has unmatched_open == 0 (ignored); '(z)' forms valid_pairs = 1; trailing '(' leaves unmatched_open = 1. Pass 2: skips the first ')', keeps the first '(' (open_to_keep = 1 -> 0) and matching ')', then skips the trailing '(' because open_to_keep == 0 -> "xy(z)w". Combined result: [3, "xy(z)w"]Assemble the complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_subarrays_by_remainder(nums: List[int], K: int, R: int) -> int: """Count contiguous non-empty subarrays nums[i..j] with sum(nums[i..j]) mod K == R.""" # remainder_counts: dict {rem: count_of_prefixes_seen_so_far} where 0 <= rem < K. # Seed with {0: 1} for the empty prefix P[0] = 0 so subarrays starting at index 0 match. remainder_counts: Dict[int, int] = {0: 1} prefix_rem = 0 matching_subarrays = 0 for num in nums: # Python's % operator always returns a canonical remainder in [0, K - 1], even for negatives. prefix_rem = (prefix_rem + num) % K # (P[j+1] - P[i]) mod K == R <=> P[i] mod K == (P[j+1] - R) mod K. # Look up BEFORE inserting prefix_rem so empty subarrays (i == j+1) are never counted. needed_prev_rem = (prefix_rem - R) % K matching_subarrays += remainder_counts.get(needed_prev_rem, 0) remainder_counts[prefix_rem] = remainder_counts.get(prefix_rem, 0) + 1 return matching_subarrays def remove_min_parentheses(s: str) -> str: """Delete the minimum number of '(' and ')' so s becomes balanced in O(1) extra space.""" # Pass 1: Count how many complete '()' pairs can be formed using O(1) integer state. unmatched_open = 0 valid_pairs = 0 for ch in s: if ch == "(": unmatched_open += 1 elif ch == ")": # Only a ')' with an earlier unmatched '(' can form a valid pair. if unmatched_open > 0: unmatched_open -= 1 valid_pairs += 1 # Pass 2: Emit only characters belonging to the final answer (zero extra slots beyond output). # Keeping the FIRST valid_pairs occurrences of '(' guarantees every valid ')' still has an # earlier '(' partner, while dropping the rightmost surplus '(' characters automatically. output_chars: List[str] = [] open_to_keep = valid_pairs open_unclosed = 0 for ch in s: if ch == "(": if open_to_keep > 0: open_to_keep -= 1 open_unclosed += 1 output_chars.append("(") elif ch == ")": if open_unclosed > 0: open_unclosed -= 1 output_chars.append(")") else: output_chars.append(ch) return "".join(output_chars) def solve_array_and_parentheses( nums: List[int], K: int, R: int, s: str ) -> List[object]: subarray_count = count_subarrays_by_remainder(nums, K, R) balanced_text = remove_min_parentheses(s) return [subarray_count, balanced_text]✅ Submit now — all tests should pass.
Intuition & how it works
Each half of this problem relies on turning a global property into a single running counter:
1. Subarray remainder counting: Think of a prefix sum (the running total from index 0 up to the current position) like mile markers along a highway, except we only care about each marker's modulo K value (the remainder in 0 .. K - 1 after dividing by K). A contiguous subarray (an unbroken slice nums[i..j]) has sum P[j+1] - P[i], so it leaves remainder R exactly when the earlier marker had remainder (P[j+1] - R) mod K. Keeping a hash map (a dictionary with O(1) average lookup) of how often each remainder has appeared lets us count all matching start positions in a single step!
2. Minimum parentheses removal: A string has balanced parentheses when reading left to right never sees more ')' than '(', and both counts finish equal at the end. In Pass 1, we scan with an integer counter to count how many complete () partnerships (valid_pairs) can possibly form. In Pass 2, we build the balanced subsequence (characters kept in their original left-to-right order) by keeping all letters, the first valid_pairs opening '(' characters, and every ')' that closes one of those kept openers.
Why do obvious approaches fall short? For Task 1, testing every (i, j) subarray takes O(n^2) time, which hits billions of steps at n = 10^5. For Task 2, pushing unmatched '(' indices onto a stack uses O(n) extra memory (violating the O(1) extra-space requirement), and even appending every '(' into a temporary list before deleting surplus ones wastes O(n) memory when s = "(((...(" has an empty output "".
Here is a quick trace of both algorithms on nums = [3, -5, 4], K = 4, R = 3 and s = "x)y(z)w(":
Task 1 (K = 4, R = 3): start remainder_counts = {0: 1}
x = 3 -> prefix_rem = 3, need (3 - 3) % 4 = 0 -> matches = 1; counts = {0:1, 3:1}
x = -5 -> prefix_rem = 2, need (2 - 3) % 4 = 3 -> matches = 2; counts = {0:1, 3:1, 2:1}
x = 4 -> prefix_rem = 2, need (2 - 3) % 4 = 3 -> matches = 3; counts = {0:1, 3:1, 2:2}
Task 2 (s = "x)y(z)w("):
Pass 1: ')' (unmatched_open=0, skip), '(' (open=1), ')' (open=0, valid_pairs=1), '(' (open=1)
Pass 2 (open_to_keep = 1): skips first ')', keeps '(z)', skips trailing '(' -> "xy(z)w"
Complexity
Let n be len(nums) for Task 1 and len(s) for Task 2.
- Task 1 (
count_subarrays_by_remainder):- Time:
O(n)average. We visit each number innumsonce and perform oneO(1)average-time dictionary lookup and oneO(1)average-time dictionary update per step. - Space:
O(min(n, K))(which satisfiesO(K)).remainder_countsstores at most one entry per distinct remainder in0 .. K - 1and at mostn + 1prefixes total.
- Time:
- Task 2 (
remove_min_parentheses):- Time:
O(n). Pass 1 scanssonce, Pass 2 scanssonce, and"".join(output_chars)copies the output characters once in linear time. - Space:
O(1)extra space beyond the output. Pass 1 uses two integers (unmatched_open,valid_pairs), and Pass 2 uses two integers (open_to_keep,open_unclosed) plusoutput_chars, which holds exclusively the characters of the final returned string.
- Time:
Edge cases
- Empty array (
nums = []): The loop never executes and returns0(empty subarrays do not count). K = 1andR = 0: Every integer sum leaves remainder0modulo1, so alln * (n + 1) // 2subarrays match.R = 0(divisible byK): Seeding{0: 1}counts prefixes divisible byK, while looking up before inserting prevents pairing a prefix with itself.- Negative numbers in
nums: In Example 2 ([3, -5, 4], K = 4),(3 - 5) % 4evaluates to2in Python, so negative sums like-5and-1map cleanly to non-negative remainders. - No parentheses or already balanced (
"abc","co(d(e)r)s"):valid_pairsmatches all'('and')', returning an identical copy ofs. - All parentheses invalid (
"))m(("or"(((("):valid_pairs = 0, so Pass 2 skips every parenthesis and keeps only letters. - Multiple valid minimal outputs (
"a(b(c)"): Both"ab(c)"and"a(bc)"delete one'('; keeping the firstvalid_pairsopeners deterministically produces"a(bc)".
Common mistakes
- Initializing
remainder_counts = {}instead of{0: 1}: ForgetsP[0] = 0, missing every valid subarray that starts at index0. - Updating
remainder_counts[prefix_rem]before queryingneeded_prev_rem: WhenR = 0,needed_prev_rem == prefix_rem, so every index wrongly counts an empty zero-length subarray and inflates the answer byn. - Writing
needed_prev_rem = (R - prefix_rem) % K: Reverses the subtraction and checks(P[j+1] + P[i]) mod K == Rinstead of(P[j+1] - P[i]) mod K == R. - Using C++/Java
%without normalizing negatives: In C++ and Java,-1 % 3is-1instead of2; there you must normalize with((x % K) + K) % K. - Deleting the first surplus
'('instead of the last ones: On"()(", deleting the first'('leaves")("(unbalanced!), whereas keeping the firstvalid_pairs = 1opener and dropping the last'('produces"()". - Concatenating strings with
res += chinside a loop: Repeated string concatenation can degrade toO(n^2)time; appending tooutput_charsand calling"".join(output_chars)once guaranteesO(n).
Alternative approaches
- Fixed-size array
[0] * Kfor Task 1: Replaces hash map hashing with direct array indexing inO(K)space, which is faster whenK <= 10^5is small, though a dictionary is safer ifKcan be much larger thann(e.g.,K = 10^9,n = 100). - Stack of unmatched
'('indices for Task 2: Push the index of each'(', pop on')', mark stray')'indices for deletion, and afterwards delete any'('indices still on the stack. Very intuitive andO(n)time, but usesO(n)auxiliary space for the stack and index set.
Follow-up questions
- What changes are needed for Task 1 in languages like C++ or Java where the
%operator can yield negative remainders or 32-bit counters can overflow? In languages where%preserves the dividend's sign (-5 % 4 == -1), normalize bothprefix_remandneeded_prev_remusing((val % K) + K) % Kso every bucket lies in0 .. K - 1. Reducingprefix_remmoduloKon every iteration prevents prefix-sum overflow, whilematching_subarraysmust be stored in a 64-bit integer (long long/long) becausen = 10^5can produce up ton * (n + 1) / 2 ≈ 5 * 10^9matching subarrays, exceeding 32-bitintlimits. - How would you adapt Task 1 if a subarray only counts when its length is at least
L? A subarray ending at prefixP[t](1 <= t <= n) has length at leastLif and only if its start prefixP[i]satisfiesi <= t - L. Keep a sliding history of prefixes (or recomputeP[t - L]with a second pointerLsteps behind) and insertP[t - L] mod Kintoremainder_countsright before querying(P[t] - R) mod Kfort >= L, preservingO(n)time. - How would Task 2 change if you had to return every distinct balanced string obtainable with the minimum number of deletions? A single greedy pass picks one canonical answer, whereas enumerating all distinct minimal fixes requires backtracking (exploring keep-vs-delete choices recursively) using the exact deletion budgets
drop_openanddrop_closecomputed in Pass 1 to prune branches immediately whenever either budget drops below0oropen_unclosed < 0. Because inputs like repeated"(a)b)"blocks have exponentially many distinct minimal answers, worst-case runtime becomes exponential inn, and a hash set is needed to deduplicate identical strings formed by deleting different parentheses in the same run (such as either')'in"a))").
Follow-up questions
- What changes are needed for Task 1 in languages like C++ or Java where the `%` operator can yield negative remainders or 32-bit counters can overflow?
- How would you adapt Task 1 if a subarray only counts when its length is at least `L`?
- How would Task 2 change if you had to return every distinct balanced string obtainable with the minimum number of deletions?
Similar questions
- Walking Through a Production Reliability Outage
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One