Skip to content
RED SAGSkills
hard20 pts · first answer countshash-mapprefix-sumsdebugging

Prefix count updated too early

This subarray-sum-equals-k code gives too high a result when k = 0. Why?

const count = new Map([[0, 1]])
let sum = 0, ans = 0
for (const x of nums) {
  sum += x
  count.set(sum, (count.get(sum) ?? 0) + 1)
  ans += count.get(sum - k) ?? 0
}
Choose one answer

Discussion 0

Join free to post in the discussion.

Related questions