Subarray Sum Equals K
Python data engineering interview problem. Difficulty: intermediate. Pattern: Hashing. About 14 minutes. Part of the Pro drill bank.
Count subarrays whose sum equals k. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A sales list can contain positive and negative adjustments. The same target total may be reached by several continuous groups, and you must count every group. Return the number of contiguous subarrays whose values add exactly to k. A subarray must contain at least one value, and different start or end positions count separately. Write the function subarray_sum(nums: list, k: int) -> int. For [1, 1, 1] and k = 2, the first 2 values and the last 2 values both total 2, so the answer is 2. The starter file already has the function name and the harness print lines. Keep them, and fill only the function body.
Requirements
- Count every continuous range with sum k.
- Allow overlapping ranges when their positions differ.
- Return the count as an integer.
Constraints
- Values may be positive, zero or negative, so a sliding window is not always safe.
- The return type is int, and an empty list has count 0.
Examples
Input: subarray_sum([1, 1, 1], 2) Output: 2 Two windows of sum 2.
Topics: lakebench, python, prefix sum, hash map.
More Python interview questions · All interview problems · Learn data engineering
Subarray Sum Equals K
Interview-style drill: Count subarrays whose sum equals k.
Implement `subarray_sum(nums: list, k: int) -> int`. Example: `[1, 1, 1], 2` → `2`. Keep the harness.