2459. Sort Array by Moving Items to Empty Space
Explanation
Given an array of integers where one or more elements are missing and replaced with a special value -1
, the task is to sort the array by moving the items to the empty spaces. The empty space is represented by -1
, and the relative order of the elements should be preserved.
To achieve this, we can utilize a modified version of the insertion sort algorithm. We can iterate over the array, moving each element to its correct position by shifting the other elements accordingly. Since the array might contain empty spaces represented by -1
, we need to handle this special case separately.
class Solution {
public void sortArray(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] == -1) {
int j = i - 1;
while (j >= 0 && nums[j] == -1) {
j--;
}
if (j >= 0) {
int temp = nums[j];
nums[j] = -1;
nums[i] = temp;
}
} else {
int j = i - 1;
int emptyCount = 0;
while (j >= 0) {
if (nums[j] == -1) {
emptyCount++;
} else if (nums[j] > nums[i]) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
i = j;
}
j--;
}
if (emptyCount > 0) {
nums[i - emptyCount] = -1;
}
}
}
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.