Cyclic Sort

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given an array nums of n distinct integers where each value is in the range [1, n], sort the array in-place using the cyclic sort algorithm and return it.

Cyclic sort works by iterating through the array and placing each element at its correct index (nums[i] - 1), swapping with the element currently at that position until every value is in place.

Examples

Example 1:

Input: nums = [3, 1, 5, 4, 2]

Output: [1, 2, 3, 4, 5]

Explanation: 3 belongs at index 2, 1 belongs at index 0, etc.

Example 2:

Input: nums = [2, 6, 4, 3, 1, 5]

Output: [1, 2, 3, 4, 5, 6]

Example 3:

Input: nums = [1, 5, 6, 4, 3, 2]

Output: [1, 2, 3, 4, 5, 6]

Constraints

  • n == nums.length
  • 1 <= n <= 10^4
  • All integers in nums are distinct and in the range [1, n]
Source: Cyclic Sort pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle