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]:

  1. 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 divisor K, and a target remainder R (0 <= R < K), compute subarray_count: how many non-empty contiguous subarrays nums[i..j] (0 <= i <= j < len(nums)) satisfy: text sum(nums[i..j]) mod K == R Here mod K denotes the standard non-negative mathematical remainder in 0 .. K - 1 (for instance, -5 mod 4 == 3 and -1 mod 4 == 3). Your solution for Task 1 must run in O(len(nums)) time and O(K) auxiliary space.

  2. Task 2 — Remove the fewest parentheses to balance a string: Given a string s consisting of lowercase English letters ('a'–'z'), '(', and ')', return balanced_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 in O(len(s)) time and use O(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^9
  • 1 <= K <= 100,000
  • 0 <= R < K
  • 0 <= len(s) <= 100,000
  • s contains only lowercase ASCII letters ('a'–'z'), '(', and ')'.
  • Required complexity: O(len(nums)) time and O(K) space for Task 1; O(len(s)) time and O(1) extra space beyond the output string for Task 2.

Step-by-step walkthrough

  1. Understand both tasks and constraints

    solve_array_and_parentheses(nums, K, R, s) bundles two independent algorithmic tasks and returns [subarray_count, balanced_text]:

    1. Task 1 — Subarrays with given remainder (count_subarrays_by_remainder): Given an integer array nums (which may contain negative numbers and zeros), a modulus K >= 1, and a target remainder 0 <= R < K, count how many non-empty contiguous subarrays nums[i..j] satisfy sum(nums[i..j]) mod K == R in O(n) time and O(K) space. Note that we use the standard mathematical remainder in [0, K - 1], so -5 mod 4 == 3.
    2. Task 2 — Minimum parentheses removal: Given a string s of lowercase letters, '(', and ')', delete as few parentheses as possible so the remaining string is balanced while keeping every letter and preserving relative order, in O(n) time and O(1) extra space beyond the output.
  2. Why naive solutions fall short

    • Task 1 brute force: Looping over every start index i and end index j checks n * (n + 1) / 2 subarrays, taking O(n^2) time — roughly 5 * 10^9 steps when n = 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 n indices when s = "(((...(", using O(n) auxiliary memory instead of O(1) extra space beyond the output.
  3. Task 1 key idea: turn subarray sums into prefix remainders

    Define the prefix sums P[0] = 0 and P[t] = nums[0] + nums[1] + ... + nums[t - 1]. Any contiguous subarray nums[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 remainder R upon division by K? Rearrange the modular equation so i and j + 1 sit 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 K
    

    As we scan nums left to right maintaining prefix_rem = P[j+1] mod K, we want to know how many earlier prefixes P[i] (0 <= i <= j) had remainder (prefix_rem - R) mod K: - Store remainder_counts[r] = how many prefixes seen so far have remainder r. - Start with remainder_counts = {0: 1} to represent the empty prefix P[0] = 0 (so subarrays starting at index 0 are counted). - Query remainder_counts before recording the current prefix_rem, so P[j+1] never pairs with itself as an empty subarray!

  4. Implement Task 1: count_subarrays_by_remainder

    Python's % operator with positive K always produces a non-negative remainder in [0, K - 1] (even when prefix_rem + num or prefix_rem - R is negative), and the dictionary holds at most min(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_subarrays
    
  5. Task 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:

    1. Pass 1 — Count total valid () pairs: Scan left to right tracking unmatched_open. Each '(' increments unmatched_open; each ')' that sees unmatched_open > 0 matches one '(' (unmatched_open -= 1, valid_pairs += 1), while any ')' with unmatched_open == 0 has nothing to close and must be deleted.
    2. Pass 2 — Emit the exact output: Now we know the balanced answer contains all letters plus exactly valid_pairs opening '('s and valid_pairs closing ')'s. Which '('s should we keep? Keeping the first valid_pairs occurrences 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_chars only appends characters that appear in the final string, even an input like "(" * 100000 (whose output is "") allocates 0 characters in output_chars — true O(1) extra space beyond the output!

  6. 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)
    
  7. 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"]
    
  8. 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 in nums once and perform one O(1) average-time dictionary lookup and one O(1) average-time dictionary update per step.
    • Space: O(min(n, K)) (which satisfies O(K)). remainder_counts stores at most one entry per distinct remainder in 0 .. K - 1 and at most n + 1 prefixes total.
  • Task 2 (remove_min_parentheses):
    • Time: O(n). Pass 1 scans s once, Pass 2 scans s once, 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) plus output_chars, which holds exclusively the characters of the final returned string.

Edge cases

  • Empty array (nums = []): The loop never executes and returns 0 (empty subarrays do not count).
  • K = 1 and R = 0: Every integer sum leaves remainder 0 modulo 1, so all n * (n + 1) // 2 subarrays match.
  • R = 0 (divisible by K): Seeding {0: 1} counts prefixes divisible by K, 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) % 4 evaluates to 2 in Python, so negative sums like -5 and -1 map cleanly to non-negative remainders.
  • No parentheses or already balanced ("abc", "co(d(e)r)s"): valid_pairs matches all '(' and ')', returning an identical copy of s.
  • 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 first valid_pairs openers deterministically produces "a(bc)".

Common mistakes

  • Initializing remainder_counts = {} instead of {0: 1}: Forgets P[0] = 0, missing every valid subarray that starts at index 0.
  • Updating remainder_counts[prefix_rem] before querying needed_prev_rem: When R = 0, needed_prev_rem == prefix_rem, so every index wrongly counts an empty zero-length subarray and inflates the answer by n.
  • Writing needed_prev_rem = (R - prefix_rem) % K: Reverses the subtraction and checks (P[j+1] + P[i]) mod K == R instead of (P[j+1] - P[i]) mod K == R.
  • Using C++/Java % without normalizing negatives: In C++ and Java, -1 % 3 is -1 instead of 2; 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 first valid_pairs = 1 opener and dropping the last '(' produces "()".
  • Concatenating strings with res += ch inside a loop: Repeated string concatenation can degrade to O(n^2) time; appending to output_chars and calling "".join(output_chars) once guarantees O(n).

Alternative approaches

  • Fixed-size array [0] * K for Task 1: Replaces hash map hashing with direct array indexing in O(K) space, which is faster when K <= 10^5 is small, though a dictionary is safer if K can be much larger than n (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 and O(n) time, but uses O(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 both prefix_rem and needed_prev_rem using ((val % K) + K) % K so every bucket lies in 0 .. K - 1. Reducing prefix_rem modulo K on every iteration prevents prefix-sum overflow, while matching_subarrays must be stored in a 64-bit integer (long long / long) because n = 10^5 can produce up to n * (n + 1) / 2 ≈ 5 * 10^9 matching subarrays, exceeding 32-bit int limits.
  • How would you adapt Task 1 if a subarray only counts when its length is at least L? A subarray ending at prefix P[t] (1 <= t <= n) has length at least L if and only if its start prefix P[i] satisfies i <= t - L. Keep a sliding history of prefixes (or recompute P[t - L] with a second pointer L steps behind) and insert P[t - L] mod K into remainder_counts right before querying (P[t] - R) mod K for t >= L, preserving O(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_open and drop_close computed in Pass 1 to prune branches immediately whenever either budget drops below 0 or open_unclosed < 0. Because inputs like repeated "(a)b)" blocks have exponentially many distinct minimal answers, worst-case runtime becomes exponential in n, 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

Similar questions

More Shein interview questions

All 2 Shein questions →