1328. Unit Digit Line-up

Easy1.5 points estimatedCounting SortArraySorting

A queue of ticket numbers is called by last digit. Rearrange the array nums in place, so that the final contents of nums are the answer, with numbers ordered by their last decimal digit from 0 to 9. The last digit of a negative number is the last digit of its absolute value, so the last digit of -13 is 3 and of -10 is 0. Numbers with the same last digit must keep the relative order they had in the input, which means the rearrangement is stable. The values themselves are never changed.

The intended method is a counting sort with ten buckets, running in O(n) time and O(n) space. Nothing is returned.

Example 1

Input:
nums = [21,13,-5,40,3]
Output:
[40,21,13,3,-5]
Explanation:

The last digits are 1, 3, 5, 0, 3, so 40 goes first, then 21, then 13 and 3 (in input order), then -5.

Example 2

Input:
nums = [10,20,30]
Output:
[10,20,30]
Explanation:

All last digits are 0, so the order does not change.

Example 3

Input:
nums = [-13,-23,13,-3]
Output:
[-13,-23,13,-3]
Explanation:

All four values end in 3, so the stable rearrangement keeps the input order.

Constraints

  • 1 ≤ n ≤ 1000
  • -109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from nums after your method returns.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…