I was practicing some leetcode and I am pretty new to it. So, there is this problem where you need to shift the 0s to the right. I wrote the code and the output is coming as expected but the results yields []
.
Can anyone explain what's wrong?
Here is the snippet of my code.
And here is the result.
As you can clearly see in the stdout
, the output is correct but the answer is coming as an empty list. What am I doing wrong? I appreciate your help. Thanks.
Ok, The question is based on Inplace operations and your logic is quite correct. I will explain with 3 things so it will be clear to you.
1. Good programming practice:-
The output yields [], because there is clear statement in 19th line
//19 nums.clear();
//20 nums=nonZeroArray;
Idea:- nums is cleared. contents of nonZeroArray is copied to nums.
Actual thing:- But in this case if we use clear, then result will be cleared i.e [] and 20th line is not having any impact.
Proof:- ->As the question is in place traversal, don't use clear statement. This is bad programming practice. Instead of 19th and 20th line you can try this
for(int i=0; i<nums.length; i++)
{
nums[i]=nonZeroArray[I];
}
Don't use clear, instead of that copy element by element you will get result.
2. Logic correction:- Even after doing this, you will get error because there is logic error in code.
The question says if array is [0,1,0,3,12]. The output should be [1,3,12,0,0]. pushing zeros to end.
In line 2, no need of sort function. suppose take example of arr=[0,2,1]. the output should be [2,1,0]. if we sort in line 2, then output will be [1,2,0] which is wrong. so don't sort.
The final corrected code will be:-
class Solution {
void moveZeroes(List<int> nums) {
List<int> nonZeroArray=[];
for(int i=0; i<nums.length; i++){
if(nums[i]!=0){
nonZeroArray.add(nums[i]);
}
}
if(nums.length != nonZeroArray.length){
int rem=nums.length-nonZeroArray.length;
for(int i=0; i<rem; i++){
nonZeroArray.add(0);
}
// print(nonZeroArray);
}
// nums.clear();
// nums=nonZeroArray;
for(int i=0; i<nums.length; i++)
{
nums[i]=nonZeroArray[I];
}
}
}
3. Good programming practice with Inplace traversal -> don't try to use additional variables (like nonZeroArray her). Try to solve in nums itself in case of in place traversal,
Alternative code:-
class Solution {
void moveZeroes(List<int> nums) {
int listLenght = nums.length;
nums.removeWhere((element) => element == 0);
int listRemaningLenght = listLenght - nums.length;
for (var i = 0; i < listRemaningLenght; i++) {
nums.add(0);
}
}
}
I hope this cleared your doubt.
Thank you. Happy Coding.
Regards:-
Rakshath U Shetty