Foundations
Linear Structures
Hashing
Array and String Patterns
Recursion, Search, and Sorting
Problem Solving Patterns
Algorithm Searching
Sorting Algorithms
Array Algorithms
Grid Algorithms
Linear Structure Algorithms
Hashing Algorithms
Recursion and Backtracking
Greedy Algorithms
Tree and Heap Algorithms
Graph Algorithms
Dynamic Programming Algorithms
String Algorithms
Math Algorithms
Keyboard ready
Space plays. Arrow keys step. R restarts.
LAB Prefix Sum Lab
Arrays
Problem shape
Beginner
4
8
15
16
23
42
Core idea
Store cumulative totals so range sums are answered by subtraction.
Step 1 / 5
Problem shape
Arrays Beginner
Prefix Sum
Welcome to the Prefix Sum algorithm lab. Store cumulative totals so range sums are answered by subtraction. Use it when: Use when many range-sum queries or subarray-sum checks are needed. The time complexity is O(n) build, O(1) query, and the space complexity is O(n). The pseudocode is: prefix[0] = 0 for i from 0 to n - 1 prefix[i + 1] = prefix[i] + a[i] sum(l, r) = prefix[r + 1] - prefix[l] As you practice, track the state that changes and the condition that makes the algorithm stop.
Time
O(n) build, O(1) query
Space
O(n)
Pseudocode
prefix[0] = 0
for i from 0 to n - 1
prefix[i + 1] = prefix[i] + a[i]
sum(l, r) = prefix[r + 1] - prefix[l] 1.0x