Relative Sort Array solution explained
The clean Relative Sort Array solution counts how often each value appears, writes the values in the order the second list dictates, then appends whatever is left in ascending order. With a hash map that runs in O(n + m + k log k) time, and when values are small bounded integers a plain counting array makes it linear.
By Evin JohnPublished 8 min read
The problem in plain words
You get two lists of non-negative integers. Call the first one items and the second one order. Every value in order is distinct, and every value in order also appears somewhere in items, possibly several times. Rearrange items so that all copies of order[0] come first, then all copies of order[1], and so on. Values in items that never appear in order go at the very end, sorted from smallest to largest.
| items | order | Result | What happened |
|---|---|---|---|
| [5, 3, 9, 3, 1, 5, 8] | [3, 5] | [3, 3, 5, 5, 1, 8, 9] | The 3s, then the 5s, then the rest ascending |
| [7, 2, 7, 2] | [7, 2] | [7, 7, 2, 2] | Every value is in order, so nothing trails |
| [4, 0, 6, 0] | [6] | [6, 0, 0, 4] | Zero is a normal leftover and sorts first among them |
| [12] | [12] | [12] | A single matching value |
Questions worth asking before you write anything: can order contain a value that is missing from items (the usual statement says no, but a defensive answer handles it), are the values bounded, and should you sort in place or return a new list? The bound matters most, because it decides whether a counting array is allowed.
Why it shows up in interviews
It looks like a sorting question, and that is the trap. Candidates who reach for a custom comparator straight away get a working O(n log n) answer, which is fine. The stronger signal is noticing that the order list already fixes most of the output and only the leftovers actually need sorting. That observation turns the problem into counting, and counting is the idea the interviewer is usually fishing for. It also tests whether you know that JavaScript's default sort compares numbers as strings.
Slow approach: one scan per order value
Walk through order. For each value, scan the whole items list and copy every match into the result. After that, collect the values that never appeared in order and sort them. With n items and m order values the scanning part costs O(n × m), plus O(n log n) for the leftovers. It is correct and easy to read, and it is a good opening statement before you improve it.
def relative_sort_slow(items, order):
result = []
for v in order:
for x in items:
if x == v:
result.append(x)
placed = set(order)
rest = [x for x in items if x not in placed]
return result + sorted(rest)Main approach: count, emit, then sort the remainder
The inner scan in the slow version keeps asking the same thing: how many copies of v are in items? Answer that once for every value with a frequency table. Then the output writes itself. For each value in order, emit it as many times as it was counted and remove it from the table. Whatever stays in the table never appeared in order, so sort those distinct keys and emit each one by its count.
Notice what gets sorted: only the distinct leftover values, not the whole list. If items has a million entries but only five values outside order, the sort touches five keys.
from collections import Counter
def relative_sort(items, order):
counts = Counter(items)
result = []
for v in order:
result.extend([v] * counts.pop(v, 0))
for v in sorted(counts):
result.extend([v] * counts[v])
return resultfunction relativeSort(items, order) {
const counts = new Map();
for (const x of items) counts.set(x, (counts.get(x) || 0) + 1);
const result = [];
for (const v of order) {
const c = counts.get(v) || 0;
for (let i = 0; i < c; i++) result.push(v);
counts.delete(v);
}
const rest = [...counts.keys()].sort((a, b) => a - b);
for (const v of rest) {
for (let i = 0; i < counts.get(v); i++) result.push(v);
}
return result;
}When the values are small: a counting array
If the interviewer confirms that every value lies between 0 and some small ceiling (the common version of this problem uses a ceiling around one thousand), swap the hash map for a list of counters indexed by value. Walking that list from 0 upward gives the leftovers in ascending order for free, so no comparison sort is needed at all.
def relative_sort_bounded(items, order, top=1000):
tally = [0] * (top + 1)
for x in items:
tally[x] += 1
result = []
for v in order:
result.extend([v] * tally[v])
tally[v] = 0
for v in range(top + 1):
result.extend([v] * tally[v])
return resultThe comparator version
A compact alternative gives each value a rank: its position in order, or len(order) if it is absent. Sorting by the pair (rank, value) puts ranked values in order-list order and pushes the unranked ones to the end in ascending order. It is O(n log n), slightly slower than counting, but it is short and hard to get wrong. Many interviewers accept it as long as you can say why the tie-break on value is there.
def relative_sort_by_rank(items, order):
rank = {v: i for i, v in enumerate(order)}
m = len(order)
return sorted(items, key=lambda x: (rank.get(x, m), x))function relativeSortByRank(items, order) {
const rank = new Map(order.map((v, i) => [v, i]));
const m = order.length;
return [...items].sort((a, b) => {
const ra = rank.has(a) ? rank.get(a) : m;
const rb = rank.has(b) ? rank.get(b) : m;
return ra - rb || a - b;
});
}Complexity
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Scan per order value | O(n × m + n log n) | O(n) | Fine as a first statement only |
| Hash map count | O(n + m + k log k) | O(n) | The general answer, no bound needed |
| Counting array | O(n + m + V) | O(V) plus output | Best when values are small and non-negative |
| Sort by (rank, value) | O(n log n) | O(n + m) | Shortest code, slightly slower |
Output space is O(n) in every version because you build a new list. If the interviewer asks for in-place, the counting versions can write back into items instead of a fresh result, which removes that copy but keeps the table.
Edge cases to test
- An empty order list: the answer is simply items sorted ascending.
- Every value of items appears in order: nothing trails the ordered block.
- Heavy duplicates, such as forty copies of one value, to confirm counts are emitted in full.
- Zero as a value, both inside order and as a leftover.
- A value in order that does not occur in items, if the interviewer relaxes the guarantee. The Counter and Map versions emit nothing for it; the counting array version also emits nothing because its count is zero.
- A single-element items list.
Mistakes that cost points
- Calling the default JavaScript sort on numbers. Without a comparator, [10, 9, 1] sorts to [1, 10, 9] because the values are compared as strings.
- Forgetting to remove ordered values from the table, which emits them a second time in the leftover section.
- Sorting the leftovers by count or by first appearance instead of by value.
- Emitting one copy per distinct value and dropping the duplicates.
- Using the counting array without checking the bound, then crashing on a negative value or a large one.
- Quoting O(n) for the hash map version while still sorting the leftover keys. Say O(n + m + k log k), or explain why k is small.
How to explain it out loud
Fictional example
- Candidate
- The order list already decides where most values go, so I do not need a full sort. I only need to know how many copies of each value there are.
- Candidate
- I count items into a map. Then for each value in order I append it count-many times and delete it from the map. What remains are values order never mentioned, so I sort those keys and append each by its count.
- Candidate
- On [5, 3, 9, 3, 1, 5, 8] with order [3, 5], I get two 3s, two 5s, then the leftover keys 1, 8 and 9. Time is linear plus the sort of leftover keys. If values are capped, I would use a counting array and skip that sort too.
Related problems in this set
Two other ordering puzzles sit next to this one. Wiggle Sort II asks for an alternating low, high, low pattern instead of a fixed order, and Pancake Sorting restricts you to prefix reversals. When the input arrives sorted and you only need a position, Find Smallest Letter Greater Than Target is the binary search counterpart. For broader practice, see the algorithm interview questions and the data structure questions, where hash maps and counting come up again.
Practice it with Natively
When you rehearse a problem like this, Natively can read it from a screenshot and suggest a pattern, such as counting before sorting, which you can hold up against your own plan once you have tried it. It also transcribes the mock session on your computer, so afterwards you can check whether you stated the bound question and the leftover sort cost. More on an AI interview assistant for Mac and Windows.
Questions people ask
What is the best solution to Relative Sort Array?
Count every value with a hash map, emit the values of the order list in sequence by their counts, then sort the remaining distinct keys and emit them. That is O(n + m + k log k), and with small bounded values a counting array makes it linear.
Can Relative Sort Array be solved with a custom comparator?
Yes. Give each value its index in the order list as a rank, or the order list's length if it is absent, and sort by (rank, value). It runs in O(n log n) and is the shortest correct version.
Why does my JavaScript solution put 10 before 9?
Array.prototype.sort compares values as strings when no comparator is given. Pass (a, b) => a - b when sorting the leftover numbers.
What happens to values that are not in the second list?
They go at the end of the result in ascending order, with every duplicate kept.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
