KatInterview

Permutation Search Sort: Order a List by Brute Force

Heaps, Sorting & SearchAuto-graded · 24 test cases
EasyAuto-gradedHeaps, Sorting & Searchsortingpermutationsbrute-force

Last updated

Implement a factorial-time sort that tries arrangements until one is non-decreasing, handling duplicates and empty input, and reason about its cost.

Permutation Search Sort

Some sorting methods are famous for being slow on purpose. One of them works like this: look through the possible orderings of the input one at a time, and stop at the first ordering in which every element is less than or equal to the one after it.

Write a function that takes a list of integers and returns a new list containing the same values in non-decreasing (ascending) order.

Requirements

  • The returned list must contain exactly the same values as the input, with the same multiplicities. Duplicates are allowed and must all be kept.
  • The returned list must be in non-decreasing order.
  • An empty input returns an empty list.
  • Do not modify the input list. Return a new list.
  • Aim to implement the brute-force idea described above: generate arrangements of the input and test each one for sortedness. Only the returned list is checked, so the result must match what a correct sort would produce.

Constraints

  • 0 <= len(values) <= 9, so a factorial-time search is feasible.
  • Each value is an integer, possibly negative, and values may repeat.
  • The function returns a List[int].

Examples

Example 1

Input: permutation_search_sort([3, 1, 2])

Output: [1, 2, 3]

Example 2

Input: permutation_search_sort([5, -1, 5, 0])

Output: [-1, 0, 5, 5]

Example 3

Input: permutation_search_sort([])

Output: []

Example 4

Input: permutation_search_sort([1, 2, 3, 4])

Output: [1, 2, 3, 4]

Hints

Hint 1

Think about what a sorted list looks like in terms of adjacent pairs: every element must be less than or equal to its right neighbour.

Hint 2

Python's itertools.permutations generates every ordering of the positions, including repeated-looking ones when values are duplicated. That is fine, because you stop at the first ordering that passes the check.

Hint 3

Check the empty list and the single-element list: each has exactly one arrangement, which is already sorted. Convert the winning tuple back to a list before returning it.