Skip to lesson

Practice: prefix sums and hashing

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Some subarray and lookup problems need only a prefix sum array, some need only a HashMap/HashSet, and the deepest ones need both working together. This practice lesson gives you a clear decision guide and six interview-grade challenges.

Choosing prefix sums, a map or both

When reading a new array or string problem, use this 4-way decision guide:

  1. Prefix Sums alone (long[n + 1]): You are given fixed range queries [L, R] or asked to split an array into a left prefix and right suffix (Range Sum Query 1D/2D, Pivot/Equilibrium Index).
  2. Difference Array (long[n + 1]): You are given batch range-addition updates [L, R, +val] before reading the final state (Flight Bookings, Car Pooling).
  3. HashMap / HashSet alone: Order does not matter or you are matching single elements/groups (Two Sum, Group Anagrams, Top K Frequent Words, Longest Consecutive Sequence).
  4. Prefix Sums + HashMap together: You need to count or find the longest/shortest contiguous subarray whose sum (or XOR, or balance of categories, or modulo remainder) equals a target k when negative numbers or non-monotonic operations prevent a sliding window.
  • Count subarrays with sum/XOR == k -> Map<PrefixValue, Frequency> seeded with (0, 1).
  • Longest subarray with sum/balance == k -> Map<PrefixValue, EarliestIndex> seeded with (0, -1).
  • Group items by equivalence -> Map<CanonicalKey, List<Item>> with computeIfAbsent.

Group anagrams, Top K frequent words, and Subarray XOR equal to k

Two important variations appear frequently in coding rounds.

  1. For Top K Frequent Words: count with HashMap, then sort unique words by (freq desc, word asc) and take the first k.
  2. For Subarray XOR == k: seed xorFreq.put(0, 1), maintain currXor ^= x, add xorFreq.getOrDefault(currXor ^ k, 0), and increment xorFreq for currXor.

Example 1 · Top K Frequent Words with lexicographical tie-breaking

TopKFrequentWordsDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class TopKFrequentWordsDemo {    public static List<String> topKFrequent(String[] words, int k) {        Map<String, Integer> freq = new HashMap<>();        for (String w : words) {            freq.put(w, freq.getOrDefault(w, 0) + 1);        }        List<String> unique = new ArrayList<>(freq.keySet());        unique.sort((a, b) -> {            int cmp = Integer.compare(freq.get(b), freq.get(a));            return cmp != 0 ? cmp : a.compareTo(b);        });        return unique.subList(0, k);    }
    public static void main(String[] args) {        String[] words = {"i", "love", "leetcode", "i", "love", "coding"};        System.out.println(topKFrequent(words, 2));    }}
Output
[i, love]

What this code does

  • Both "i" and "love" appear twice, while "coding" and "leetcode" appear once.
  • When frequencies tie (2 == 2), a.compareTo(b) places "i" before "love" alphabetically.

Example 2 · Count of Subarrays with XOR Equal to K

SubarrayXorEqualsKDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class SubarrayXorEqualsKDemo {    public static int subarraysWithXorK(int[] nums, int k) {        Map<Integer, Integer> xorFreq = new HashMap<>();        xorFreq.put(0, 1);        int currXor = 0;        int count = 0;
        for (int x : nums) {            currXor ^= x;            count += xorFreq.getOrDefault(currXor ^ k, 0);            xorFreq.put(currXor, xorFreq.getOrDefault(currXor, 0) + 1);        }        return count;    }
    public static void main(String[] args) {        int[] a = {4, 2, 2, 6, 4};        System.out.println("XOR == 6 in [4,2,2,6,4]: " + subarraysWithXorK(a, 6));        int[] b = {5, 6, 7, 8, 9};        System.out.println("XOR == 5 in [5,6,7,8,9]: " + subarraysWithXorK(b, 5));    }}
Output
XOR == 6 in [4,2,2,6,4]: 4
XOR == 5 in [5,6,7,8,9]: 2

What this code does

  • In [4, 2, 2, 6, 4], the 4 subarrays with XOR 6 are [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], and [6].
  • Because (a ^ b == k) is equivalent to (a == b ^ k), looking up currXor ^ k works in O(1) expected time.
  • Top K Frequent Words: First count word frequencies in a Map<String, Integer>. Then sort the unique keys (or use a bounded PriorityQueue) with a custom two-key comparator: higher frequency first (Integer.compare(freq.get(b), freq.get(a))), breaking ties by lexicographical order (a.compareTo(b)).
  • Count of Subarrays with XOR Equal to K: Because XOR is its own inverse (x ⊕ x = 0), the XOR of nums[left .. right] is prefXor[right + 1] ^ prefXor[left]. Setting prefXor[right + 1] ^ prefXor[left] = k and XORing both sides by k gives:

prefXor[left] = prefXor[right + 1] ⊕ k This is identical to Subarray Sum Equals K, with currXor ^ k replacing currSum - k!

Range sum query, equilibrium index, and Contiguous Array

Two techniques save space and balance categories.

Example 3 · Product of Array Except Self using prefix and suffix running products in O(1) extra space

ProductExceptSelfPrefixDemo.javaJava
import java.util.Arrays;
public class ProductExceptSelfPrefixDemo {    public static int[] productExceptSelf(int[] nums) {        int n = nums.length;        int[] ans = new int[n];        int prefixProd = 1;        for (int i = 0; i < n; i++) {            ans[i] = prefixProd;            prefixProd *= nums[i];        }        int suffixProd = 1;        for (int i = n - 1; i >= 0; i--) {            ans[i] *= suffixProd;            suffixProd *= nums[i];        }        return ans;    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4};        System.out.println(Arrays.toString(productExceptSelf(nums)));    }}
Output
[24, 12, 8, 6]

What this code does

  • Pass 1 writes the product of elements strictly to the left of i into ans[i].
  • Pass 2 multiplies ans[i] by the product of elements strictly to the right of i, avoiding division (and handling zeroes safely!).
  • Equilibrium (Pivot) Index: Instead of allocating a long[n + 1] array just to compare left and right sums at each index i, compute totalSum first and sweep leftSum from 0 to n - 1, checking leftSum == totalSum - leftSum - nums[i] in O(1) space.
  • Contiguous Array (Equal 0s and 1s): Map 0 -> -1 and 1 -> +1 so any subarray with equal 0s and 1s has net sum 0, then track the earliest index of each running balance in a HashMap seeded with (0, -1).
Whenever you combine a comparator with frequency lookups for Top K Frequent Words, use Integer.compare(freqB, freqA) rather than subtraction to stay safe from overflow.

Finish up

Mark complete & continue

Next: How binary search works