Prefix Sum Pattern: Template + 157 LeetCode Problems

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

  • 14 Easy
  • 102 Medium
  • 41 Hard
  • O(n) to build, O(1) per range query time

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.

Prefix Sum — Python 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.

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)

#ProblemDifficultyTopics
303Range Sum Query - ImmutableEasyDesign, Array, Prefix Sum
724Find Pivot IndexEasyArray, Prefix Sum
1732Find the Highest AltitudeEasyArray, Prefix Sum
1413Minimum Value to Get Positive Step by Step SumEasyArray, Prefix Sum
1422Maximum Score After Splitting a StringEasyString, Prefix Sum
1480Running Sum of 1d ArrayEasyArray, Prefix Sum
1588Sum of All Odd Length SubarraysEasyArray, Math, Prefix Sum
1854Maximum Population YearEasyArray, Counting, Prefix Sum
1893Check if All the Integers in a Range Are CoveredEasyArray, Hash Table, Prefix Sum
1991Find the Middle Index in ArrayEasyArray, Prefix Sum
2389Longest Subsequence With Limited SumEasyGreedy, Array, Binary Search +2
2485Find the Pivot IntegerEasyMath, Prefix Sum
2574Left and Right Sum DifferencesEasyArray, Prefix Sum
2848Points That Intersect With CarsEasyArray, Hash Table, Prefix Sum

Medium (102)

#ProblemDifficultyTopics
209Minimum Size Subarray SumMediumArray, Binary Search, Prefix Sum +1
238Product of Array Except SelfMediumArray, Prefix Sum
304Range Sum Query 2D - ImmutableMediumDesign, Array, Matrix +1
497Random Point in Non-overlapping RectanglesMediumReservoir Sampling, Array, Math +4
523Continuous Subarray SumMediumArray, Hash Table, Math +1
525Contiguous ArrayMediumArray, Hash Table, Prefix Sum
528Random Pick with WeightMediumArray, Math, Binary Search +2
560Subarray Sum Equals KMediumArray, Hash Table, Prefix Sum
713Subarray Product Less Than KMediumArray, Binary Search, Prefix Sum +1
731My Calendar IIMediumDesign, Segment Tree, Array +3
1004Max Consecutive Ones IIIMediumArray, Binary Search, Prefix Sum +1
253Meeting Rooms IIPremiumMediumGreedy, Array, Two Pointers +3
325Maximum Size Subarray Sum Equals kPremiumMediumArray, Hash Table, Prefix Sum
370Range AdditionPremiumMediumArray, Prefix Sum
813Largest Sum of AveragesMediumArray, Dynamic Programming, Prefix Sum
848Shifting LettersMediumArray, String, Prefix Sum
930Binary Subarrays With SumMediumArray, Hash Table, Prefix Sum +1
974Subarray Sums Divisible by KMediumArray, Hash Table, Prefix Sum
1094Car PoolingMediumArray, Prefix Sum, Sorting +2
1109Corporate Flight BookingsMediumArray, Prefix Sum
1124Longest Well-Performing IntervalMediumStack, Array, Hash Table +2
1140Stone Game IIMediumArray, Math, Dynamic Programming +2
1177Can Make Palindrome from SubstringMediumBit Manipulation, Array, Hash Table +2
1208Get Equal Substrings Within BudgetMediumString, Binary Search, Prefix Sum +1
1248Count Number of Nice SubarraysMediumArray, Hash Table, Math +2
1292Maximum Side Length of a Square with Sum Less than or Equal to ThresholdMediumArray, Binary Search, Matrix +1
1310XOR Queries of a SubarrayMediumBit Manipulation, Array, Prefix Sum
1314Matrix Block SumMediumArray, Matrix, Prefix Sum
1352Product of the Last K NumbersMediumDesign, Array, Math +2
1371Find the Longest Substring Containing Vowels in Even CountsMediumBit Manipulation, Hash Table, String +1
1423Maximum Points You Can Obtain from CardsMediumArray, Prefix Sum, Sliding Window
1442Count Triplets That Can Form Two Arrays of Equal XORMediumBit Manipulation, Array, Hash Table +2
1508Range Sum of Sorted Subarray SumsMediumArray, Two Pointers, Binary Search +2
1524Number of Sub-arrays With Odd SumMediumArray, Math, Dynamic Programming +1
1546Maximum Number of Non-Overlapping Subarrays With Sum Equals TargetMediumGreedy, Array, Hash Table +1
1589Maximum Sum Obtained of Any PermutationMediumGreedy, Array, Prefix Sum +1
1590Make Sum Divisible by PMediumArray, Hash Table, Prefix Sum
1658Minimum Operations to Reduce X to ZeroMediumArray, Hash Table, Binary Search +2
1664Ways to Make a Fair ArrayMediumArray, Prefix Sum
1674Minimum Moves to Make Array ComplementaryMediumArray, Hash Table, Prefix Sum
1685Sum of Absolute Differences in a Sorted ArrayMediumArray, Math, Prefix Sum
1712Ways to Split Array Into Three SubarraysMediumArray, Two Pointers, Binary Search +1
1737Change Minimum Characters to Satisfy One of Three ConditionsMediumHash Table, String, Counting +1
1738Find Kth Largest XOR Coordinate ValueMediumBit Manipulation, Array, Divide and Conquer +5
1744Can You Eat Your Favorite Candy on Your Favorite Day?MediumArray, Prefix Sum
1769Minimum Number of Operations to Move All Balls to Each BoxMediumArray, String, Prefix Sum
1829Maximum XOR for Each QueryMediumBit Manipulation, Array, Prefix Sum
1838Frequency of the Most Frequent ElementMediumGreedy, Array, Binary Search +3
1856Maximum Subarray Min-ProductMediumStack, Array, Prefix Sum +1
1871Jump Game VIIMediumString, Dynamic Programming, Prefix Sum +1
1878Get Biggest Three Rhombus Sums in a GridMediumArray, Math, Matrix +3
1894Find the Student that Will Replace the ChalkMediumArray, Binary Search, Prefix Sum +1
1895Largest Magic SquareMediumArray, Matrix, Prefix Sum
1915Number of Wonderful SubstringsMediumBit Manipulation, Hash Table, String +1
1930Unique Length-3 Palindromic SubsequencesMediumBit Manipulation, Hash Table, String +1
1943Describe the PaintingMediumArray, Hash Table, Prefix Sum +1
1983Widest Pair of Indices With Equal Range SumPremiumMediumArray, Hash Table, Prefix Sum
2017Grid GameMediumArray, Matrix, Prefix Sum
2021Brightest Position on StreetPremiumMediumArray, Ordered Set, Prefix Sum +1
2024Maximize the Confusion of an ExamMediumString, Binary Search, Prefix Sum +1
2055Plates Between CandlesMediumArray, String, Binary Search +1
2083Substrings That Begin and End With the Same LetterPremiumMediumHash Table, Math, String +2
2100Find Good Days to Rob the BankMediumArray, Dynamic Programming, Prefix Sum
2121Intervals Between Identical ElementsMediumArray, Hash Table, Prefix Sum
2145Count the Hidden SequencesMediumArray, Prefix Sum
2171Removing Minimum Number of Magic BeansMediumGreedy, Array, Enumeration +2
2207Maximize Number of Subsequences in a StringMediumGreedy, String, Prefix Sum
2219Maximum Sum Score of ArrayPremiumMediumArray, Prefix Sum
2222Number of Ways to Select BuildingsMediumString, Dynamic Programming, Prefix Sum
2237Count Positions on Street With Required BrightnessPremiumMediumArray, Prefix Sum
2245Maximum Trailing Zeros in a Cornered PathMediumArray, Matrix, Prefix Sum
2256Minimum Average DifferenceMediumArray, Prefix Sum
2270Number of Ways to Split ArrayMediumArray, Prefix Sum
2271Maximum White Tiles Covered by a CarpetMediumGreedy, Array, Binary Search +3
2381Shifting Letters IIMediumArray, String, Prefix Sum
2391Minimum Amount of Time to Collect GarbageMediumArray, String, Prefix Sum
2406Divide Intervals Into Minimum Number of GroupsMediumGreedy, Array, Two Pointers +3
2420Find All Good IndicesMediumArray, Dynamic Programming, Prefix Sum
2428Maximum Sum of an HourglassMediumArray, Matrix, Prefix Sum
2438Range Product Queries of PowersMediumBit Manipulation, Array, Prefix Sum
2439Minimize Maximum of ArrayMediumGreedy, Array, Binary Search +2
2483Minimum Penalty for a ShopMediumString, Prefix Sum
2489Number of Substrings With Fixed RatioPremiumMediumHash Table, Math, String +1
2505Bitwise OR of All Subsequence SumsPremiumMediumBit Manipulation, Brainteaser, Array +2
2536Increment Submatrices by OneMediumArray, Matrix, Prefix Sum
2559Count Vowel Strings in RangesMediumArray, String, Prefix Sum
2587Rearrange Array to Maximize Prefix ScoreMediumGreedy, Array, Prefix Sum +1
2588Count the Number of Beautiful SubarraysMediumBit Manipulation, Array, Hash Table +1
2602Minimum Operations to Make All Array Elements EqualMediumArray, Binary Search, Prefix Sum +1
2615Sum of DistancesMediumArray, Hash Table, Prefix Sum
2640Find the Score of All Prefixes of an ArrayMediumArray, Prefix Sum
2680Maximum ORMediumGreedy, Bit Manipulation, Array +1
2731Movement of RobotsMediumBrainteaser, Array, Prefix Sum +1
2772Apply Operations to Make All Array Elements Equal to ZeroMediumArray, Prefix Sum
2838Maximum Coins Heroes Can CollectPremiumMediumArray, Two Pointers, Binary Search +2
2845Count of Interesting SubarraysMediumArray, Hash Table, Prefix Sum
2875Minimum Size Subarray in Infinite ArrayMediumArray, Hash Table, Prefix Sum +1
2906Construct Product MatrixMediumArray, Matrix, Prefix Sum
2947Count Beautiful Substrings IMediumHash Table, Math, String +3
2950Number of Divisible SubstringsPremiumMediumHash Table, String, Counting +1
2955Number of Same-End SubstringsPremiumMediumArray, Hash Table, String +2
2971Find Polygon With the Largest PerimeterMediumGreedy, Array, Prefix Sum +1

Hard (41)

#ProblemDifficultyTopics
363Max Sum of Rectangle No Larger Than KHardArray, Binary Search, Matrix +2
410Split Array Largest SumHardGreedy, Array, Binary Search +2
689Maximum Sum of 3 Non-Overlapping SubarraysHardArray, Dynamic Programming, Prefix Sum +1
732My Calendar IIIHardDesign, Segment Tree, Binary Search +2
548Split Array with Equal SumPremiumHardArray, Hash Table, Prefix Sum
644Maximum Average Subarray IIPremiumHardArray, Binary Search, Prefix Sum
798Smallest Rotation with Highest ScoreHardArray, Prefix Sum
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
903Valid Permutations for DI SequenceHardString, Dynamic Programming, Prefix Sum
995Minimum Number of K Consecutive Bit FlipsHardBit Manipulation, Queue, Array +2
1000Minimum Cost to Merge StonesHardArray, Dynamic Programming, Prefix Sum
1074Number of Submatrices That Sum to TargetHardArray, Hash Table, Matrix +1
1420Build Array Where You Can Find The Maximum Exactly K ComparisonsHardDynamic Programming, Prefix Sum
1444Number of Ways of Cutting a PizzaHardMemoization, Array, Dynamic Programming +2
1687Delivering Boxes from Storage to PortsHardSegment Tree, Queue, Array +4
1703Minimum Adjacent Swaps for K Consecutive OnesHardGreedy, Array, Prefix Sum +1
1788Maximize the Beauty of the GardenPremiumHardGreedy, Array, Hash Table +1
1862Sum of Floored PairsHardArray, Math, Binary Search +1
1872Stone Game VIIIHardArray, Math, Dynamic Programming +2
1889Minimum Space Wasted From PackagingHardArray, Binary Search, Prefix Sum +1
2025Maximum Number of Ways to Partition an ArrayHardArray, Hash Table, Counting +2
2106Maximum Fruits Harvested After at Most K StepsHardArray, Binary Search, Prefix Sum +1
2132Stamping the GridHardGreedy, Array, Matrix +1
2209Minimum White Tiles After Covering With CarpetsHardString, Dynamic Programming, Prefix Sum
2218Maximum Value of K Coins From PilesHardArray, Dynamic Programming, Prefix Sum
2234Maximum Total Beauty of the GardensHardGreedy, Array, Two Pointers +4
2251Number of Flowers in Full BloomHardArray, Hash Table, Binary Search +3
2281Sum of Total Strength of WizardsHardStack, Array, Prefix Sum +1
2302Count Subarrays With Score Less Than KHardArray, Binary Search, Prefix Sum +1
2382Maximum Segment Sum After RemovalsHardUnion Find, Array, Ordered Set +1
2398Maximum Number of Robots Within BudgetHardQueue, Array, Binary Search +4
2448Minimum Cost to Make Array EqualHardGreedy, Array, Binary Search +2
2478Number of Beautiful PartitionsHardString, Dynamic Programming, Prefix Sum
2488Count Subarrays With Median KHardArray, Hash Table, Prefix Sum
2528Maximize the Minimum Powered CityHardGreedy, Queue, Array +3
2552Count Increasing QuadrupletsHardBinary Indexed Tree, Array, Dynamic Programming +2
2681Power of HeroesHardArray, Math, Dynamic Programming +2
2819Minimum Relative Loss After Buying ChocolatesPremiumHardArray, Binary Search, Prefix Sum +1
2949Count Beautiful Substrings IIHardHash Table, Math, String +2
2968Apply Operations to Maximize Frequency ScoreHardArray, Binary Search, Prefix Sum +2
2983Palindrome Rearrangement QueriesHardHash Table, String, Prefix Sum

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the prefix sum problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.