Skip to content
Onsite

Stable Sort by Modulo K

EasyP3Coding

Sort nums by each element's remainder when divided by k, smallest remainder first. Elements with the same remainder must keep the order they had in the input (a stable sort).

Return the sorted array. All values are non-negative, so remainders are unambiguous.

Example 1

Input
nums = [5,3,8,1,6], k = 3
Output
[3,6,1,5,8]
Why
Remainders are 2,0,2,1,0. Remainder 0: 3,6. Remainder 1: 1. Remainder 2: 5,8.

Example 2

Input
nums = [4,2,6], k = 2
Output
[4,2,6]

Example 3

Input
nums = [10], k = 7
Output
[10]

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^9
  • 1 <= k <= 10^9

Hints

Run checks the 3 visible tests, Submit all 10.