hash_table.state
Input
Hash table
Current look-up
Match / window
Stored entry
What is Subarray Sum Equals K
A subarray sum from i+1 to j is prefix[j] − prefix[i]. That equals k exactly when a previous prefix prefix[j] − k exists. A hash map stores how many times each prefix has appeared.
{0: 1} so a prefix that itself equals k counts as a subarray from the start.1, 2, 3, k = 3. Prefixes 1, 3, 6 produce two subarrays: [1,2] and [3].Interactive trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each prefix | O(1) expected |
| Full scan | O(n) |
| Space | O(n) |
Python implementation