Sort Array by Consecutive Elements Problem
Sort Array by Consecutive Elements Problem — ExecCode Medium DSA Practice
Solve the Sort Array by Consecutive Elements problem on ExecCode. Free online medium DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.
Problem description
Given an array nums of n integers where each value is meant to represent a position from 1 to n (though duplicates or out-of-range values may occur), rearrange the array in-place so that every valid value sits as close as possible to index value-1, using the cyclic sort swap pattern.
Examples
Input nums = [3, 1, 4, 2]; Output [1, 2, 3, 4]. Input nums = [2, 4, 1, 4]; Output [1, 2, 4, 4]. Input nums = [1, 3, 2]; Output [1, 2, 3]
Constraints
1 <= nums.length <= 10^5 Values outside [1, n] are left untouched at their current index.
Practice Sort Array by Consecutive Elements free on ExecCode. Browse DSA problems, topic map, and placement guides.