cswork / libraryOpen practice workspace

Coding questions · Akuna Capital

Count subarrays equal to target

This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Count subarrays equal to target states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.

Given an integer array nums and an integer k, count the number of contiguous subarrays whose sum equals k. Solve it in O(n) time and O(n) space by maintaining a running prefix sum and a hash map of prefix-sum frequencies. Explain why this works with negative numbers, analyze complexity, and provide code or pseudocode.

What a Strong Answer Covers

  • A clear algorithm with the right data structures and enough pseudocode or code-level detail to implement it.
  • A correctness argument that explains why the algorithm covers all required cases.
  • Time and space complexity, plus at least one alternative approach when relevant.
  • Focused tests for normal cases, edge cases, and failure modes.

Follow-up Questions

  • How would the approach change if the input were streaming or too large for memory?
  • What invariants would you assert in production code?
  • Which tests would catch off-by-one, duplicate, or tie-breaking bugs?

Count Subarrays Equal to Target

Given an integer array nums and an integer k, count the number of contiguous (non-empty) subarrays whose elements sum to exactly k.

Return the total count of such subarrays.

Solve it in O(n) time and O(n) space by maintaining a running prefix sum and a hash map of prefix-sum frequencies. The map records how many times each prefix sum has occurred so far; at each index, the number of subarrays ending here with sum k equals the number of earlier prefixes equal to prefix - k.

Why it works with negative numbers: Unlike a sliding-window approach, this method never assumes the running sum is monotonically increasing. It relies only on the algebraic identity sum(i+1..j) = prefix[j] - prefix[i], which holds regardless of sign. The same prefix value can recur (e.g. after a +1, -1), and the frequency map counts every such occurrence, so subarrays formed by cancellation are all captured. Seeding the map with {0: 1} accounts for subarrays that start at index 0.

Examples:

  • nums = [1, 1, 1], k = 2 -> 2 (the subarrays [1,1] at indices 0-1 and 1-2)
  • nums = [1, 2, 3], k = 3 -> 2 ([1,2] and [3])
  • nums = [1, -1, 1, -1], k = 0 -> 4

Constraints

  • 1 <= nums.length <= 2 * 10^4 (an empty array yields 0)
  • -1000 <= nums[i] <= 1000 (values may be negative or zero)
  • -10^7 <= k <= 10^7
  • Subarrays are contiguous and non-empty; count every distinct index range that qualifies.

Hints

  1. A subarray sum equals prefix[j] - prefix[i]. Fix the right end j and ask: how many earlier prefixes i satisfy prefix[j] - prefix[i] = k, i.e. prefix[i] = prefix[j] - k?
  2. Keep a hash map from prefix-sum value to how many times it has occurred. Before inserting the current prefix, add freq[prefix - k] to your answer.
  3. Seed the map with {0: 1} so subarrays that start at index 0 are counted. Because you query for prefix - k BEFORE inserting the current prefix, you never count an empty subarray.

Solution

Solution Alignment

The prompt asks for an implementation-level answer. The safest way to present it is to define the state, maintain clear invariants, then walk through complexity and tests.

Problem Restatement

Given an integer array nums and an integer k, count the number of contiguous subarrays whose sum equals k. Solve it in O(n) time and O(n) space by maintaining a running prefix sum and a hash map of prefix-sum frequencies. Explain why this works with negative numbers, analyze complexity, and provide code or pseudocode.

Recommended Approach

Start with a brute-force baseline to confirm correctness, then identify the repeated work or ordering property that enables a better data structure such as a hash map, heap, stack, queue, two pointers, prefix sums, BFS/DFS, or dynamic programming. Write the implementation around a small invariant and test that invariant directly.

Correctness

The implementation should maintain an invariant after each loop or operation that directly matches the problem statement. At termination, that invariant implies the returned value has considered every valid candidate exactly once, or has preserved the required data-structure state after every API call.

Complexity

State the baseline complexity and the optimized complexity. For most interview constraints, justify why the optimized approach meets the expected input size.

Edge Cases and Tests

Empty and singleton inputs, duplicates, ties, invalid inputs, boundary values, and tests that exercise the main invariant.