Subarray Sum Equals K
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Count the continuous sub-lists whose sum is exactly k.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Let total(i) be the sum of the first i numbers. What is the sum from position a to b?
- Hint 2It is total(b) minus total(before a). You need that difference to equal k.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Your bank passbook shows the balance after every transaction. How much did you spend between two moments? Just the difference of the two balances. To find every period in which you spent exactly ₹500, at each new balance ask your notebook: "how many times earlier was the balance exactly ₹500 higher?". Each such time is one period.
- The obvious way
Try every start and end: O(n²).
- The key insight
Keep the running total and a notebook counting how many times each running total has occurred. At each step the number of ranges ending here with sum k = how many earlier totals equal (current total - k). Start the notebook with total 0 seen once, so ranges that begin at the very start count too.
- The algorithm
- Notebook: total 0 has been seen once. Running total = 0, answer = 0.
- Add the next number to the running total.
- Look up (running total - k) in the notebook; add that count to the answer.
- Write the running total in the notebook (count + 1) and continue.
Watch it run
Examplenumbers = [1, 2, 3], k = 3
Start: notebook says total 0 was seen once.
totals seen: {0: 1} answer 0Where people slip
- Sliding window fails here because numbers can be negative; running totals do not care.
- Record the running total in the notebook AFTER counting, not before.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def subarray_sum(nums, k):
seen = {0: 1} # running total -> how many times
running = 0
answer = 0
for number in nums:
running += number
answer += seen.get(running - k, 0) # ranges ending here with sum k
seen[running] = seen.get(running, 0) + 1
return answerNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.