Pattern 04 of 22

Prefix Sum Pattern: Template + 157 LeetCode Problems

Precompute running totals once so any range query becomes a single subtraction.

Easy
14
Medium
102
Hard
41

What the prefix sum pattern is

A prefix sum array stores the total of everything before each index, so the sum of any range is the difference of two entries and costs one subtraction no matter how long the range is. Building it is one pass; after that, a thousand range queries are a thousand subtractions instead of a thousand scans. The version that actually shows up in interviews is subtler: to count subarrays whose sum equals k, walk the array keeping the running total and a hash map of how many times each running total has been seen, because a subarray summing to k exists exactly where the current total minus k has appeared before. Seed that map with a zero total seen once, or every subarray that starts at index zero is missed. The same trick generalises past sums — replace the running total with a running parity, a running count difference, or a bitmask of seen characters, and the same map counts subarrays with equal ones and zeros, or with all characters appearing an even number of times.

When to use it

  • Many range-sum queries are made over an array that does not change between them.
  • You are counting subarrays whose sum, parity or balance hits a target.
  • The brute force recomputes the sum of overlapping ranges from scratch.
  • A two-dimensional version is needed: the same idea with inclusion-exclusion over four corners.

The prefix sum template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 157 problems listed below.

PythonPrefix Sum template
from collections import defaultdict

def count_subarrays_with_sum(nums, k):
    counts = defaultdict(int)
    counts[0] = 1            # the empty prefix, so a whole prefix can match
    running = 0
    total = 0

    for value in nums:
        running += value
        total += counts[running - k]   # every earlier prefix that closes a window
        counts[running] += 1

    return total

Complexity characteristics

Time
O(n) to build, O(1) per range query
Auxiliary space
O(n)

One pass builds the running totals; after that any range sum is a single subtraction, so k queries cost O(n + k) instead of O(n·k). The hash-map variant that counts subarrays hitting a target sum is a single O(n) pass with an O(n) map. The two-dimensional version costs O(r·c) to build and O(1) per rectangle query, using inclusion–exclusion over four corners.

Eyes only

Meet the prefix sum problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 157 prefix sum LeetCode problems

Every problem in the library the prefix sum pattern applies to, grouped by LeetCode's own difficulty rating. 139 of the 157 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (14)

Easy problems
No.Problem
0303Range Sum Query - Immutable
0724Find Pivot Index
1732Find the Highest Altitude
1413Minimum Value to Get Positive Step by Step Sum
1422Maximum Score After Splitting a String
1480Running Sum of 1d Array
1588Sum of All Odd Length Subarrays
1854Maximum Population Year
1893Check if All the Integers in a Range Are Covered
1991Find the Middle Index in Array
2389Longest Subsequence With Limited Sum
2485Find the Pivot Integer
2574Left and Right Sum Differences
2848Points That Intersect With Cars

Medium (102)

Medium problems
No.Problem
0209Minimum Size Subarray Sum
0238Product of Array Except Self
0304Range Sum Query 2D - Immutable
0497Random Point in Non-overlapping Rectangles
0523Continuous Subarray Sum
0525Contiguous Array
0528Random Pick with Weight
0560Subarray Sum Equals K
0713Subarray Product Less Than K
0731My Calendar II
1004Max Consecutive Ones III
0253Meeting Rooms IIPremium
0325Maximum Size Subarray Sum Equals kPremium
0370Range AdditionPremium
0813Largest Sum of Averages
0848Shifting Letters
0930Binary Subarrays With Sum
0974Subarray Sums Divisible by K
1094Car Pooling
1109Corporate Flight Bookings
1124Longest Well-Performing Interval
1140Stone Game II
1177Can Make Palindrome from Substring
1208Get Equal Substrings Within Budget
1248Count Number of Nice Subarrays
1292Maximum Side Length of a Square with Sum Less than or Equal to Threshold
1310XOR Queries of a Subarray
1314Matrix Block Sum
1352Product of the Last K Numbers
1371Find the Longest Substring Containing Vowels in Even Counts
1423Maximum Points You Can Obtain from Cards
1442Count Triplets That Can Form Two Arrays of Equal XOR
1508Range Sum of Sorted Subarray Sums
1524Number of Sub-arrays With Odd Sum
1546Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
1589Maximum Sum Obtained of Any Permutation
1590Make Sum Divisible by P
1658Minimum Operations to Reduce X to Zero
1664Ways to Make a Fair Array
1674Minimum Moves to Make Array Complementary
1685Sum of Absolute Differences in a Sorted Array
1712Ways to Split Array Into Three Subarrays
1737Change Minimum Characters to Satisfy One of Three Conditions
1738Find Kth Largest XOR Coordinate Value
1744Can You Eat Your Favorite Candy on Your Favorite Day?
1769Minimum Number of Operations to Move All Balls to Each Box
1829Maximum XOR for Each Query
1838Frequency of the Most Frequent Element
1856Maximum Subarray Min-Product
1871Jump Game VII
1878Get Biggest Three Rhombus Sums in a Grid
1894Find the Student that Will Replace the Chalk
1895Largest Magic Square
1915Number of Wonderful Substrings
1930Unique Length-3 Palindromic Subsequences
1943Describe the Painting
1983Widest Pair of Indices With Equal Range SumPremium
2017Grid Game
2021Brightest Position on StreetPremium
2024Maximize the Confusion of an Exam
2055Plates Between Candles
2083Substrings That Begin and End With the Same LetterPremium
2100Find Good Days to Rob the Bank
2121Intervals Between Identical Elements
2145Count the Hidden Sequences
2171Removing Minimum Number of Magic Beans
2207Maximize Number of Subsequences in a String
2219Maximum Sum Score of ArrayPremium
2222Number of Ways to Select Buildings
2237Count Positions on Street With Required BrightnessPremium
2245Maximum Trailing Zeros in a Cornered Path
2256Minimum Average Difference
2270Number of Ways to Split Array
2271Maximum White Tiles Covered by a Carpet
2381Shifting Letters II
2391Minimum Amount of Time to Collect Garbage
2406Divide Intervals Into Minimum Number of Groups
2420Find All Good Indices
2428Maximum Sum of an Hourglass
2438Range Product Queries of Powers
2439Minimize Maximum of Array
2483Minimum Penalty for a Shop
2489Number of Substrings With Fixed RatioPremium
2505Bitwise OR of All Subsequence SumsPremium
2536Increment Submatrices by One
2559Count Vowel Strings in Ranges
2587Rearrange Array to Maximize Prefix Score
2588Count the Number of Beautiful Subarrays
2602Minimum Operations to Make All Array Elements Equal
2615Sum of Distances
2640Find the Score of All Prefixes of an Array
2680Maximum OR
2731Movement of Robots
2772Apply Operations to Make All Array Elements Equal to Zero
2838Maximum Coins Heroes Can CollectPremium
2845Count of Interesting Subarrays
2875Minimum Size Subarray in Infinite Array
2906Construct Product Matrix
2947Count Beautiful Substrings I
2950Number of Divisible SubstringsPremium
2955Number of Same-End SubstringsPremium
2971Find Polygon With the Largest Perimeter

Hard (41)

Hard problems
No.Problem
0363Max Sum of Rectangle No Larger Than K
0410Split Array Largest Sum
0689Maximum Sum of 3 Non-Overlapping Subarrays
0732My Calendar III
0548Split Array with Equal SumPremium
0644Maximum Average Subarray IIPremium
0798Smallest Rotation with Highest Score
0862Shortest Subarray with Sum at Least K
0903Valid Permutations for DI Sequence
0995Minimum Number of K Consecutive Bit Flips
1000Minimum Cost to Merge Stones
1074Number of Submatrices That Sum to Target
1420Build Array Where You Can Find The Maximum Exactly K Comparisons
1444Number of Ways of Cutting a Pizza
1687Delivering Boxes from Storage to Ports
1703Minimum Adjacent Swaps for K Consecutive Ones
1788Maximize the Beauty of the GardenPremium
1862Sum of Floored Pairs
1872Stone Game VIII
1889Minimum Space Wasted From Packaging
2025Maximum Number of Ways to Partition an Array
2106Maximum Fruits Harvested After at Most K Steps
2132Stamping the Grid
2209Minimum White Tiles After Covering With Carpets
2218Maximum Value of K Coins From Piles
2234Maximum Total Beauty of the Gardens
2251Number of Flowers in Full Bloom
2281Sum of Total Strength of Wizards
2302Count Subarrays With Score Less Than K
2382Maximum Segment Sum After Removals
2398Maximum Number of Robots Within Budget
2448Minimum Cost to Make Array Equal
2478Number of Beautiful Partitions
2488Count Subarrays With Median K
2528Maximize the Minimum Powered City
2552Count Increasing Quadruplets
2681Power of Heroes
2819Minimum Relative Loss After Buying ChocolatesPremium
2949Count Beautiful Substrings II
2968Apply Operations to Maximize Frequency Score
2983Palindrome Rearrangement Queries

Prefix Sum pattern FAQ

What is the prefix sum pattern?

A prefix sum array stores the total of everything before each index, so the sum of any range is the difference of two entries and costs one subtraction no matter how long the range is.

How many LeetCode problems use the prefix sum pattern?

This page lists 157 LeetCode problems that the prefix sum pattern applies to: 14 Easy, 102 Medium and 41 Hard. 139 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the prefix sum pattern?

O(n) to build, O(1) per range query time and O(n) space. One pass builds the running totals; after that any range sum is a single subtraction, so k queries cost O(n + k) instead of O(n·k). The hash-map variant that counts subarrays hitting a target sum is a single O(n) pass with an O(n) map. The two-dimensional version costs O(r·c) to build and O(1) per rectangle query, using inclusion–exclusion over four corners.

When should I use the prefix sum pattern in an interview?

Many range-sum queries are made over an array that does not change between them. You are counting subarrays whose sum, parity or balance hits a target.

Which prefix sum problem should I start with?

LeetCode 303. Range Sum Query - Immutable is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to prefix sum?

Hash Map, Sliding Window, Dynamic Programming, Two Pointers. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.