Recognition guide
Hash map or sorting? How to choose
Many array and string problems can be solved two ways. You can remember what you have seen in a hash map, or you can sort the input so related values sit next to each other. Both remove a nested loop. They pay for it differently, and the problem statement usually says which payment it can afford.
This guide is about that choice. It does not re-teach either tool. For that, read the Hash Map and Two Pointers pattern pages. Here you learn what to look for before you write a line of code.
The one-sentence test
Ask what the answer is made of.
- If it is made of original positions or the original order (return the indexes, keep the first occurrence), you want a hash map, because sorting would scramble them.
- If it is made of neighbors in value order (the smallest gap, overlapping ranges, the k-th largest), you want sorting, because the order is the structure.
- If it is only "have I seen this" or "how many of these", you want a hash map. Sorting works but does more than the question needs.
Signals that point to a hash map
A map answers "where is the thing I need?" in one lookup. These phrases mean you are looking something up again and again.
- "Return the indexes" of an unsorted input. The answer is positions, and sorting would renumber them.
- "Have I seen", "first duplicate", "first repeated". One pass with a set or map answers it as you go.
- "Count", "frequency", "most common". You tally values under keys.
- "Group by", "same letters", "same pattern". Compute a key for each item, then collect items under that key.
- "Complement", "pair that adds up to", "difference of k". For each value, the partner you need is known, so look it up.
- A stream or an input you may not rearrange. A map works one item at a time.
Signals that point to sorting
Sorting costs O(n log n) time, and then neighbors carry information. These phrases mean order itself is the tool.
- "Smallest difference", "closest pair", "minimum gap". After sorting, the best pair is always adjacent.
- "Merge", "overlapping", "intervals". Sort by start, then one scan joins what touches.
- "Largest", "k-th", "rank", "order the output". The answer is a position in sorted order.
- "Every unique triple or quadruple". Sort first, then fix one value and run two pointers on the rest. The sorted order also makes skipping repeats easy.
- "Use constant extra space." A map takes O(n) memory. An in-place sort does not.
Counter-signals
These look like a reason to pick one and are not.
- "Duplicate" does not mean sort. Checking for a repeat is a one-pass set problem, O(n). Sorting is a fine fallback only when memory is the limit.
- "Pair that adds up to a target" is not always a map. If the row is already sorted, two pointers does it with no extra memory. If you must return indexes of an unsorted row, use a map.
- "Closest" over an unsorted row does not have a map answer. A map finds exact matches, not near ones.
- "Sorted" in the statement usually means neither tool: it is a hint for binary search or two pointers.
- "Order of first appearance" rules out a plain sort. Keep a map, then walk the input again to read it in order.
The decision checklist
- Does the answer use original indexes or the original order? Use a map, or sort pairs of value and index.
- Are you asking about exact matches, counts, or groups? Use a map.
- Are you asking about the nearest, smallest gap, ranges, or the k-th? Sort.
- Is memory capped at constant extra space? Sort, or two pointers if it is already sorted.
- Is the input a stream, or too large to hold in full? Map, if the distinct keys fit.
- Still tied? Take the simpler code and say the other option out loud, with its cost.
The same question, both ways
"Does this list contain any value twice?" has both answers. Each is correct. They trade time for memory.
function hasDuplicateMap(nums: number[]): boolean {const seen = new Set<number>();for (const n of nums) {if (seen.has(n)) return true; // check before you addseen.add(n);}return false; // O(n) time, O(n) memory}function hasDuplicateSort(nums: number[]): boolean {const sorted = [...nums].sort((a, b) => a - b);for (let i = 1; i < sorted.length; i++) {if (sorted[i] === sorted[i - 1]) return true; // equal values are adjacent}return false; // O(n log n) time, O(n) for the copy}
Three worked examples
1. "Given an unsorted list and a target, return the indexes of the two values that add up to it."
Clues: "unsorted" and "return the indexes". Sorting would lose the positions. For each value, ask the map whether its complement was already stored, and store the current value after the check.
Pattern: hash map.
2. "Given a list of numbers, return the smallest difference between any two of them."
Clues: "smallest difference" and "any two". Comparing every pair is O(n squared). After sorting, the closest two values must be neighbors, so one pass over adjacent pairs finishes it. A map cannot find a near match.
Pattern: sorting.
3. "Group the words that are anagrams of each other."
Clues: "group" and "same letters". Here both tools appear. Sort the letters of each word to build a key, so
"tea"and"eat"both become"aet". Then collect the words in a map under that key. Sorting makes the key. The map does the grouping.Pattern: hash map, with sorting inside the key.
Common traps
- Sorting when you need the indexes. After the sort the positions are gone. Sort pairs of value and index, or use a map.
- Adding to the map before the lookup. A value can match itself and pair with its own position. Look first, then store.
- Sorting with the default comparator on numbers. In some languages the default sort compares numbers as text, so 10 comes before 2. Pass a numeric comparator.
- Using a map when the keys are not exact. Floating-point values and near matches do not behave as keys.
- Forgetting the cost of sorting inside a loop. A sort inside a loop quietly turns O(n log n) into O(n squared log n).
Quick answers
Is a hash map always faster than sorting?
On paper, O(n) beats O(n log n). A map also uses extra memory and has overhead per item. For small inputs, or when memory is capped, sorting can be the better choice.
Can I sort and then use a map?
Yes. The anagram problem does exactly that: sort each word to build a key, then group by that key.
What if the input is already sorted?
Look at two pointers or binary search first. They use no extra memory and use the order you were given.
Practice it on Algofily
Recognizing the pattern is a skill on its own, so Algofily trains it before you write code. Each problem moves through seven stages: Understand, Pattern, Think, Code, Tests, Debug, and Explain. In the Code stage, Algofily AI can give progressive hints (sign-in required).
- Read the Hash Map pattern page for the unsorted pair walk-through and the problems that practice it.
- Read the Two Pointers pattern page for what happens when the row is sorted, and see Clues that a problem needs two pointers.
While you code, Algofily AI can ask a question and open the next hint.