Cyclic Sort Problem

Cyclic Sort Problem — ExecCode Easy DSA Practice

Solve the Cyclic Sort problem on ExecCode. Free online easy DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.

Problem description

You are given an unsorted array containing n distinct numbers, each in the range from 1 to n (inclusive). Sort the array in-place using the cyclic sort pattern, which achieves this in O(n) time without any extra space by placing every number at its correct index in a single pass.

Examples

Input nums = [3, 1, 5, 4, 2]; Output [1, 2, 3, 4, 5]. Input nums = [2, 6, 4, 3, 1, 5]; Output [1, 2, 3, 4, 5, 6]. Input nums = [1]; Output [1]

Constraints

1 <= nums.length <= 10^5 Every value in nums is unique and in the range [1, n].

Practice Cyclic Sort free on ExecCode. Browse DSA problems, topic map, and placement guides.