DSAPrefix + HashFirst index

Longest Subarray Sum K Visualizer

What is Longest Subarray with Sum K

Same prefix identity as “count subarrays”, but we want the longest span. Store the first index where each prefix appeared. If pref − k was seen at index j, the window (j+1 … i) is a candidate of length i − j.

  • Keep the earliest prefix — a later same prefix would only shorten the window.
  • Seed 0 → -1 so a prefix equal to k starts at index 0.
  • Negatives: still correct; a two-pointer shrink would not be.

How this visualizer works

Array 10, 5, 2, 7, 1, 9, k = 15. Prefixes reveal [5,2,7,1] of length 4.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def longestSubarray(arr, k):
2first, pref, best = {0: -1}, 0, 0
3for i, x in enumerate(arr):
4pref += x
5if pref-k in first:
6best = max(best, i - first[pref-k])
7first.setdefault(pref, i)
8return best

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def longestSubarray(arr, k):
2first, pref, best = {0: -1}, 0, 0
3for i, x in enumerate(arr):
4pref += x
5if pref-k in first:
6best = max(best, i - first[pref-k])
7first.setdefault(pref, i)
8return best

complexity.md

OperationTime
Each prefixO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def longestSubarray(arr, k):
2 first, pref, best = {0: -1}, 0, 0
3 for i, x in enumerate(arr):
4 pref += x
5 if pref - k in first:
6 best = max(best, i - first[pref - k])
7 first.setdefault(pref, i)
8 return best