MemotivaLeetCode Patterns Flashcards: Arrays and Hashing, Frequency Maps, Duplicates

How does the prefix sum pattern work and what problems does it solve?

LeetCode Patterns Flashcards: Arrays and Hashing, Frequency Maps, Duplicates

Аудио-карточка · 0:29

Nortren·

How does the prefix sum pattern work and what problems does it solve?

0:29

The prefix sum pattern precomputes cumulative sums so that any subarray sum can be calculated in constant time. Build an array where each position stores the sum of all elements from the start up to that index. The sum of elements from index i to j equals prefix sum at j minus prefix sum at i minus one. This transforms repeated subarray sum queries from O of n each to O of one each after O of n preprocessing. Use it when the problem asks for subarray sums, range sums, or finding subarrays with a target sum. Combined with a hash map, it solves "subarray sum equals k" in O of n time.
neetcode.io