Skip to lesson

Topic set: hashing and sorting

Hashing and sorting are the two primary workhorses of algorithmic interview problem solving. We examine when to trade memory for O(1) lookups and when ordering unlocks optimal solutions.

Brute force comparisons versus hash-table lookups

Two Sum is a classic interview question: find two numbers in an unsorted array that add up to a target value.

Java
// Brute force: every pair, O(N^2)for (int i = 0; i < nums.length; i++)    for (int j = i + 1; j < nums.length; j++)        if (nums[i] + nums[j] == target) return new int[]{i, j};
// Hash map: one pass, O(N) time and O(N) spaceMap<Integer, Integer> seen = new HashMap<>();for (int i = 0; i < nums.length; i++) {    Integer j = seen.get(target - nums[i]);  // complement seen earlier?    if (j != null) return new int[]{j, i};    seen.put(nums[i], i);}

The brute-force solution checks every pair (i, j) with nested loops, performing N * (N - 1) / 2 comparisons and running in O(N^2) quadratic time. When N is one hundred thousand, this brute-force approach executes five billion comparisons and immediately times out.

A hash map transforms this search into an O(N) linear-time algorithm by trading space for speed. As we scan each element x, the required complement is target - x. Instead of scanning the rest of the array, we check if the complement already exists in our hash map in O(1) average time. If found, we return the pair immediately; if not, we record x and its index in the map. The entire array is traversed in a single pass of N steps. By consuming O(N) auxiliary space, the runtime drops from quadratic O(N^2) down to linear O(N).

Sorting as a canonical canonicalizer

Sorting is not merely a way to present data in numerical order; it acts as an algorithmic canonicalizer that brings related elements adjacent to one another. Consider grouping anagrams: checking if two arbitrary strings are anagrams character-by-character across N words takes O(N^2) pairwise comparisons.

Example 1 · Grouping Anagrams via Character Sorting

GroupAnagramsDemo.javaJava
import java.util.*;
public class GroupAnagramsDemo {    public static List<List<String>> groupAnagrams(String[] strs) {        Map<String, List<String>> map = new HashMap<>();        for (String s : strs) {            char[] chars = s.toCharArray();            Arrays.sort(chars);            String key = new String(chars);            map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);        }        return new ArrayList<>(map.values());    }
    public static void main(String[] args) {        String[] words = {"stop", "pots", "tan", "tops", "nat", "bat"};        List<List<String>> groups = groupAnagrams(words);        System.out.println("Total groups: " + groups.size());    }}
Output
Total groups: 3

What this code does

  • Group 1 contains stop, pots, tops (canonical key opst).
  • Group 2 contains tan, nat (canonical key ant).
  • Group 3 contains bat (canonical key abt).

By sorting the characters of each string (e.g. converting "stop", "pots", and "tops" into "opst"), every anagram produces an identical canonical key. We use this sorted string as a key in a HashMap<String, List<String>>, grouping all anagrams together in O(N * K log K) time, where K is maximum string length. Similarly, in interval problems such as Merge Intervals, overlapping intervals can appear in arbitrary order. Sorting intervals by their start time ensures that any overlapping intervals are strictly adjacent in the array. A single linear scan then merges overlaps in O(N log N) time.

Custom comparators and tie-breaking

Java provides the Comparator interface to customize object ordering in Arrays.sort and Collections.sort. A dangerous beginner pitfall is using simple subtraction for integer comparisons: (a, b) -> a - b.

Example 2 · Robust Custom Comparator with Tie-Breaking

CustomComparatorSortDemo.javaJava
import java.util.*;
public class CustomComparatorSortDemo {    public static void main(String[] args) {        int[][] intervals = {{3, 5}, {1, 4}, {1, 2}, {2, 6}};        Arrays.sort(intervals, (a, b) -> {            if (a[0] != b[0]) {                return Integer.compare(a[0], b[0]);            }            return Integer.compare(a[1], b[1]);        });
        StringBuilder sb = new StringBuilder();        for (int[] inv : intervals) {            sb.append("[").append(inv[0]).append(",").append(inv[1]).append("] ");        }        System.out.println("Sorted: " + sb.toString().trim());    }}
Output
Sorted: [1,2] [1,4] [2,6] [3,5]

What this code does

  • [1, 2] precedes [1, 4] due to tie-break on the second element.
  • Uses Integer.compare to avoid numeric overflow bugs.
  • Sorts in O(N log N) time and provides stable ordering.

If a is Integer.MAX_VALUE and b is -1, the difference a - b overflows the 32-bit signed integer into a negative value, violating the mathematical transitivity contract of Comparator and throwing IllegalArgumentException: Comparison method violates its general contract. Always use the built-in static method Integer.compare(a, b). When sorting multidimensional objects like intervals or coordinate points, tie-breaking is critical. For example, sorting intervals primarily by start time: if two intervals have identical start times (a[0] == b[0]), tie-break by end time via Integer.compare(a[1], b[1]). This guarantees deterministic, stable ordering across all edge cases.

Prefix sums with hash maps: subarray sums equal to K

Finding the total number of continuous subarrays whose sum equals K is an iconic interview problem. The brute force calculates the sum of all N * (N + 1) / 2 subarrays using two nested loops, taking O(N^2) time.

Example 3 · Subarray Sum Equals K via Prefix Frequency Map

SubarraySumEqualsKDemo.javaJava
import java.util.*;
public class SubarraySumEqualsKDemo {    public static int subarraySum(int[] nums, int k) {        int count = 0, currSum = 0;        Map<Integer, Integer> prefixCounts = new HashMap<>();        prefixCounts.put(0, 1); // Base case: prefix sum of empty subarray is 0
        for (int x : nums) {            currSum += x;            count += prefixCounts.getOrDefault(currSum - k, 0);            prefixCounts.put(currSum, prefixCounts.getOrDefault(currSum, 0) + 1);        }        return count;    }
    public static void main(String[] args) {        int[] arr1 = {1, 1, 1};        System.out.println("Subarrays sum 2 in {1, 1, 1}: " + subarraySum(arr1, 2));        int[] arr2 = {1, -1, 0};        System.out.println("Subarrays sum 0 in {1, -1, 0}: " + subarraySum(arr2, 0));    }}
Output
Subarrays sum 2 in {1, 1, 1}: 2
Subarrays sum 0 in {1, -1, 0}: 3

What this code does

  • {1, 1, 1} has subarrays [0..1] and [1..2] summing to 2.
  • {1, -1, 0} has subarrays [0..1], [2..2], and [0..2] summing to 0.
  • Single-pass O(N) algorithm handles positive, zero, and negative numbers seamlessly.

We optimize this to O(N) time by combining prefix sums with a frequency hash map. Let currSum be the running prefix sum from index 0 to i. A subarray ending at index i has sum K if and only if there exists some earlier prefix sum equal to currSum - K, because currSum - (currSum - K) = K. We maintain a HashMap<Integer, Integer> tracking the frequency of each prefix sum observed so far, initialized with map.put(0, 1) to account for subarrays starting at index 0. At each index i, we add map.getOrDefault(currSum - K, 0) to our answer and increment the count of currSum in the map. This achieves an optimal single-pass O(N) time complexity with O(N) space.

Next step

Check your understanding

10 quick questions