DSA and problem solving

Stage 2 · Lesson 5 of 6

Prefix sums and frequency counts

Arrays, hashing, linked lists, stacks and queues

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

Practise

Keep handy

  • The Collections Framework section: ArrayList, LinkedList, HashMap and ArrayDeque

Also worth your time

Mark this stage as not done?