Leetcode 283. Move Zeroes [ Solution + Code Explained]

preview_player
Показать описание
One of the most frequently asked coding interview questions on Array in companies like Google, Facebook, Amazon, LinkedIn, Microsoft, Uber, Apple, Adobe etc.

LeetCode : Move Zeroes

Question : Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Рекомендации по теме
Комментарии
Автор

Thas very very easy one, kindly take tougher ones

code
Автор

This is an easy question you could have experimented with different formats of solutions, there's tons of interesting ideas in the discuss tab even discussing those would be a more worthwhile video.

xzero
Автор

Below should be sufficient. No need of nested while loops.

public static int[] move(int[] array) {
int i = 0;
while (i<array.length && array[i] != 0) {
i++;
}
int j = i+1;
while (j<array.length) {
if (array[j] != 0) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
}
j++;
}
return array;
}

ykuldeep
Автор

How about something like this

int counter = 0;
for(int i=0;i<nums.length;i++) {
If(nums[i] !=0){
nums[counter++]=nums[i];
}

}
for(int i=counter;i<nums.length;i++) {
nums[i] =0;
}

kacp
Автор

Make tougher ones, this is very easy 🥺

shubhamsharma-sflx
Автор

This one is very inefficient. Its running in n(n^2) time, you can make it linear.

FitnessChaos
join shbcf.ru