Workspace Arrays And Hashing
0d
DSA topics

Arrays and Hashing

Arrays give a stable index to each slot. A hash table associates a key with a remembered fact, such as its first position or frequency.

Picture the idea

The desk number in an exam hall gives direct access to a seat. An attendance tally answers how many students share a surname.

When to use it

Use indices for position and order. Use a map when your repeated question is whether a value has appeared before.

How it works

For a target of 9 and values [4, 2, 5], remember 4 and 2. When reading 5, the needed complement 4 is already in the table.

  • Read or overwrite a slot by index.
  • Shift the suffix to insert or delete in the middle.
  • Build prefix totals with a leading zero.
  • Record counts under value keys.

Random access is O(1). Middle insertion is O(n). Hash lookup is expected O(1) under suitable hashing, while collision-heavy inputs can be slower.

Watch for this mistake

In a two-sum scan, looking up after inserting can accidentally pair one index with itself.

Ask if values may repeat, if the input can change and whether the answer needs indices or values.

Practice in the lab

Related learning