Stage 2 · Lesson 5 of 6
Prefix sums and frequency counts
Two small techniques, built on arrays and , solve a surprising number of problems. A array stores the running total up to each position. The sum of any range from i to j is then prefix[j + 1] minus prefix[i].
You pay O(n) once to build it, and each range question after that is O(1). A tallies how often each value appears. Keep it in a hash map or, for a small alphabet like lowercase letters, an array of 26.
Anagrams, majority elements and "count the that sum to k" all come down to these; the last one keeps prefix sums in a hash map. In Java and C++, watch for : a number growing past the largest value its type can hold and wrapping round to a wrong one.
A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock
Resources for this stage
Start with· follow one of these
- CoursePaidGrokking Data Structures & Algorithms for Coding Interviews
Design Gurus · Beginner · Subscription
Each structure from first principles, with solutions in Python, Java, C++ and JavaScript
- CourseFreeMIT 6.006 Introduction to Algorithms
MIT OpenCourseWare · Intermediate
Free: lectures 2 and 4 cover dynamic arrays, linked lists, sets and hashing
Practise
Keep handy
Also worth your time
How to pick a structure from the operations a problem needs