Given an integer array nums, move all the 0's to the end of the array. The relative order of the other elements must remain the same. This must be done in place, without making a copy of the array.
Input: nums = [0, 1, 4, 0, 5, 2]
Output: [1, 4, 5, 2, 0, 0]
Explanation: Both the zeroes are moved to the end and the order of the other elements stay the same
Input: nums = [0, 0, 0, 1, 3, -2]
Output: [1, 3, -2, 0, 0, 0]
Explanation: All 3 zeroes are moved to the end and the order of the other elements stay the same
Input: nums = [0, 20, 0, -20, 0, 20]
To ideate a solution for the problem, store the non-zero numbers separately and then place those elements back into the original array. This ensures that all the non-zero numbers are kept at the front of the array. Lastly, fill the remaining positions in the array with zeros.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to move zeroes to the end
void moveZeroes(vector<int>& nums) {
int n = nums.size();
/*Create a temporary array to
store non-zero elements*/
vector<int> temp;
for (int i = 0; i < n; i++) {
// Copy non-zero elements to temp
if (nums[i] != 0) {
temp.push_back(nums[i]);
}
}
// Number of non-zero elements
int nz = temp.size();
for (int i = 0; i < nz; i++) {
// Copy non-zero elements back to nums
nums[i] = temp[i];
}
for (int i = nz; i < n; i++) {
// Fill the rest with zeroes
nums[i] = 0;
}
}
};
int main() {
vector<int> nums = {1, 0, 2, 3, 2, 0, 0, 4, 5, 1};
//Create an instance of Solution class
Solution sol;
sol.moveZeroes(nums);
cout << "Array after moving zeroes: ";
// Print the modified array
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
return 0;
}
import java.util.*;
class Solution {
// Function to move zeroes to the end
public void moveZeroes(int[] nums) {
int n = nums.length;
// Create a temporary array to store non-zero elements
int[] temp = new int[n];
int count = 0;
// Copy non-zero elements to temp
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {
temp[count++] = nums[i];
}
}
// Copy non-zero elements back to nums
for (int i = 0; i < count; i++) {
nums[i] = temp[i];
}
// Fill the rest with zeroes
for (int i = count; i < n; i++) {
nums[i] = 0;
}
}
public static void main(String[] args) {
int[] nums = {1, 0, 2, 3, 2, 0, 0, 4, 5, 1};
// Create an instance of Solution class
Solution sol = new Solution();
sol.moveZeroes(nums);
System.out.print("Array after moving zeroes: ");
// Print the modified array
System.out.println(Arrays.toString(nums));
}
}
from typing import List
class Solution:
# Function to move zeroes to the end
def moveZeroes(self, nums: List[int]) -> None:
n = len(nums)
"""Create a temporary array
to store non-zero elements"""
temp = [0] * n
count = 0
# Copy non-zero elements to temp
for i in range(n):
if nums[i] != 0:
temp[count] = nums[i]
count += 1
# Copy non-zero elements back to nums
for i in range(count):
nums[i] = temp[i]
# Fill the rest with zeroes
for i in range(count, n):
nums[i] = 0
if __name__ == "__main__":
nums = [1, 0, 2, 3, 2, 0, 0, 4, 5, 1]
# Create an instance of Solution class
sol = Solution()
sol.moveZeroes(nums)
print("Array after moving zeroes:", nums)
class Solution {
// Function to move zeroes to the end
moveZeroes(nums) {
const n = nums.length;
/* Create a temporary array
to store non-zero elements*/
const temp = new Array(n).fill(0);
let count = 0;
// Copy non-zero elements to temp
for (let i = 0; i < n; i++) {
if (nums[i] !== 0) {
temp[count++] = nums[i];
}
}
// Copy non-zero elements back to nums
for (let i = 0; i < count; i++) {
nums[i] = temp[i];
}
// Fill the rest with zeroes
for (let i = count; i < n; i++) {
nums[i] = 0;
}
}
}
// Test the code
const nums = [1, 0, 2, 3, 2, 0, 0, 4, 5, 1];
// Create an instance of Solution class
const sol = new Solution();
sol.moveZeroes(nums);
console.log("Array after moving zeroes:", nums);
Imagine having a row of empty(represented by 0) and non empty(espresented by non zero number) boxes on a conveyor belt. Given a task to move all the empty boxes to the end of the conveyor belt while keeping the order of the boxes with items intact.
To achieve this efficiently, you decide to use two workers (pointers) who will work together to sort the boxes. Here's how they do it:
By the end of this process, all the non-empty boxes will have been moved to the front of the conveyor belt in their original order, and all the empty boxes will have been moved to the end.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = -1; // Initialize j to -1
int n = nums.size();
// Find the first zero element's index
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
j = i;
break;
}
}
// If no zeros are found, return
if (j == -1) return;
// Move non-zero elements to the position of the first zero
for (int i = j + 1; i < n; i++) {
if (nums[i] != 0) {
swap(nums[i], nums[j]);
j++;
}
}
}
};
int main() {
vector<int> arr = {1, 0, 2, 3, 2, 0, 0, 4, 5, 1};
// Create an instance of the Solution class
Solution solution;
// Call the moveZeroes function
solution.moveZeroes(arr);
// Print the elements
for (auto &it : arr) {
cout << it << " ";
}
cout << '\n';
return 0;
}
class Solution {
public void moveZeroes(int[] nums) {
int j = 0; // Initialize j to 0
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
// Fill the remaining elements with zeros
while (j < nums.length) {
nums[j++] = 0;
}
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {1, 0, 2, 3, 2, 0, 0, 4, 5, 1};
// Create an instance of the Solution class
Solution solution = new Solution();
// Modify the array in place
solution.moveZeroes(arr);
// Print the elements
for (int it : arr) {
System.out.print(it + " ");
}
System.out.println();
}
}
from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
j = -1
# length of nums
n = len(nums)
# place the pointer j:
for i in range(n):
if nums[i] == 0:
j = i
break
# no non-zero elements:
if j == -1:
return
"""Move the pointers i and
j and swap accordingly"""
for i in range(j + 1, n):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
# Example usage:
if __name__ == "__main__":
arr = [1, 0, 2, 3, 2, 0, 0, 4, 5, 1]
#Create an instance of Solution class
solution = Solution()
solution.moveZeroes(arr)
# Print the modified array
print(arr)
class Solution {
moveZeroes(nums) {
let j = -1;
// length of nums
const n = nums.length;
// place the pointer j:
for (let i = 0; i < n; i++) {
if (nums[i] === 0) {
j = i;
break;
}
}
// no non-zero elements:
if (j === -1) {
return nums;
}
/* Move the pointers i and
j and swap accordingly*/
for (let i = j + 1; i < n; i++) {
if (nums[i] !== 0) {
[nums[i], nums[j]] = [nums[j], nums[i]];
j++;
}
}
return nums;
}
}
// Example usage:
const arr = [1, 0, 2, 3, 2, 0, 0, 4, 5, 1];
//Create an instance of the class
const solution = new Solution();
solution.moveZeroes(arr);
// Print the modified array
console.log(arr);
Q: What ensures the relative order of non-zero elements is preserved?
A: By iterating through the array from left to right and moving each non-zero element to the next available position, the algorithm maintains the original order of non-zero elements. Zeros are simply moved to the end without disrupting this sequence.
Q: Can this logic be generalized for multi-dimensional arrays?
A: For multi-dimensional arrays, apply the same principle to each row or column independently. The complexity increases due to additional dimensions, requiring nested loops or recursive logic to process all elements
Q: How would you modify the algorithm to move all zeros to the beginning instead?
A: To move zeros to the beginning: - Iterate through the array from right to left. - Shift non-zero elements to the rightmost available position, and place zeros at the beginning. - This maintains the relative order of non-zero elements.
Q: How can you adapt this algorithm for other conditions, like moving all negative numbers to the end?
A: Instead of checking for zeros, modify the condition to identify negative numbers. Use the same two-pointer approach to shift non-negative numbers to the front while maintaining their order.