Skip to content

Sort by Another List's Order

Easy#counting-sort#custom-order~15 min

The mission

Problem

A shop sorts its stock codes by a preferred order from the marketing team. Given values and a list order of distinct codes, rearrange values so that codes appearing in order come first, grouped and in the same sequence as order, followed by every other code in ascending order. Both lists hold at most 1,000 items, every code in order also appears in values, and each code is between 0 and 1,000.

Examples

Input:  values = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], order = [2, 1, 4, 3, 9, 6]
Output: [2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]
Why:    7 and 19 are not in order, so they go last in ascending order
Input:  values = [28, 6, 22, 8, 44, 17], order = [22, 28, 8, 6]
Output: [22, 28, 8, 6, 17, 44]
Input:  values = [5, 5], order = []
Output: [5, 5]
Why:    edge case, with an empty order the result is a plain ascending sort

Hints

0 / 3

Target time
O(n + k)
Target space
O(n + k)

Constraints

  • values.length ≤ 1,000 and order.length ≤ 1,000
  • 0 ≤ code ≤ 1,000
  • codes in order are distinct
  • every code in order also appears in values

Stuck on the idea rather than the code? Counting Sort covers it.

Python 3Ctrl+Enter runs