LeetCode 2459: Sort Array by Moving Items to Empty Space Solution
Master LeetCode problem 2459 (Sort Array by Moving Items to Empty Space), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
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.
Solution Code
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;
}
}
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2459 (Sort Array by Moving Items to Empty Space)?
This page provides optimized solutions for LeetCode problem 2459 (Sort Array by Moving Items to Empty Space) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2459 (Sort Array by Moving Items to Empty Space)?
The time complexity for LeetCode 2459 (Sort Array by Moving Items to Empty Space) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2459 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2459 in Java, C++, or Python.