1326. Signed Radix In Place

Medium3.5 points estimatedRadix SortArraySortingBit Manipulation

A telemetry buffer holds signed 32-bit readings in the array nums, and the firmware must sort it ascending in place without a comparison sort. Modify nums itself; nothing is returned, and the final contents of nums are what gets checked.

Use least-significant-digit radix sort on the four 8-bit digits of each value, which gives four stable counting-sort passes of 256 buckets each. Negative numbers have the top bit set in two's complement and would land after the positive ones, so flip the sign bit of every value before sorting (equivalently add 2^31) and undo it at the end. Values lie between -10^9 and 10^9. The expected solution runs in O(n) time with O(n) auxiliary space for the pass buffer.

Example 1

Input:
nums = [3,-1,2,-7,0]
Output:
[-7,-1,0,2,3]
Explanation:

After sorting, the negative readings come first: -7, -1, 0, 2, 3.

Example 2

Input:
nums = [5,5,-5,5,-5]
Output:
[-5,-5,5,5,5]
Explanation:

Duplicates are kept together, so the final contents are -5, -5, 5, 5, 5.

Example 3

Input:
nums = [1000000000,-1000000000,0]
Output:
[-1000000000,0,1000000000]
Explanation:

The extreme values -10^9, 0 and 10^9 end up in ascending order.

Constraints

  • 1 ≤ n ≤ 105
  • -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.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

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…