Arrays & Hashing

The base of most coding problems: index into arrays in constant time, and use a hash map or set to remember what you have seen so one pass replaces a nested loop.

Overview

An array stores items side by side and finds any one of them by its position in constant time. A hash map (a dictionary) stores key-value pairs and finds a value by its key in constant time on average. Together they turn many brute-force answers that compare every pair, O(n²), into a single pass, O(n).

These problems test whether you can spot the repeated work in a brute-force answer and remove it by remembering what you have already seen. A strong answer names the brute force, says why it is slow, picks what to store in the map, and states the new time and space cost.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

What each structure costs

The rule: a lookup by key in a hash map costs the same, on average, as a lookup by index in an array. Of the three structures you reach for most, only the hash map finds a value in constant time.

  • A dynamic array: reads any index in O(1) and adds at the end in O(1) amortized. Finding a value means scanning the array, O(n), and inserting or deleting a given item shifts everything after it, also O(n). It keeps items in insertion order.
  • A hash map or hash set: cannot read by index at all. In return, finding a value, adding one, and inserting or deleting a given item all cost O(1) on average. Whether it keeps any order depends on the language.
  • A sorted array: reads by index in O(1) and finds a value by binary search in O(log n). Keeping it sorted is the price: adding at the end costs O(n) to keep order, and inserting or deleting a given item costs an O(n) shift.

That constant-time find is the move this whole chapter repeats.

> [!NOTE] > The hash map's O(1) is an average. It assumes the hash function spreads keys well, so few keys share a bucket; with many collisions, one lookup can take O(n). Python's time-complexity notes state both cases for dict and set.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio