Algorithms and Data Structures · Middle · Question 57 of 75

Subarray sum equals k: why do we store counts of prefix sums in a hash map?

Explanation

The sum of (i, j] equals prefix[j] - prefix[i]. For each position, add how many earlier prefixes equal prefix - k. One pass, O(n), and it works with negative numbers, unlike a sliding window.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 57

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz