Problem
Given an array of length N
where elements are in the range of 1
to N
, and some elements may not be present, being represented by -1
, rearrange the array such that A[i] = i
. If an element i
is not present, the position should be filled with -1
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Simply iterate and swap with -1
Iterate through the array and place elements at their correct positions (A[i] = i
). Use repeated swapping to ensure each element goes to its correct position.
- If an element is
-1
or already in its correct position, move to the next element.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of elements in the array. Each element is moved to its correct position in a single pass. - 🧺 Space complexity:
O(1)
, as the transformation is done in place without using extra space.