# Why does my solution beat only 14% of java submissions(O(1)Space and O(n)Time)?

• ``````public class Solution {
public void moveZeroes(int[] nums) {
if (nums != null) {
for (int i = 0, j = 0; j < nums.length; i++,j++) {
if (nums[i] == 0) {
j = indexOfNonZero(nums, i + 1);
if (j < nums.length) {
nums[i] = nums[j];
nums[j] = 0;
}
}
}
}
}

private int indexOfNonZero(int nums[], int startIndex) {
int i = startIndex;
for(; i < nums.length; i++) {
if (nums[i] != 0) {
return i;
}
}
return i;
}
}
``````

I think my solution :

1. Space Complexity : O(1).
2. Time Complexity: O(n).

But my run time just beats only 14% of java submissions.

• @KobeAndLebron i think you have troubles with algorithm ,and worst case is when all elements are zero [0,0,0,0,0,......0] and it is O(n^2/2)

• @KobeAndLebron see my algorythm

``````	public void moveZeroes(final int[] nums) {
int zeroCounter = 0;
for (int i = 0; i < nums.length; i++)
{
final int num = nums[i];
if(num == 0){
zeroCounter++;
}else if (zeroCounter!=0){
nums[i-zeroCounter] = num;
nums[i] = 0;
}
}
}
``````

• @vova-rova-gmail-com You look my solution carefully? The worst case you say is O(n).

• @KobeAndLebron Your solutions's worst time complexity should be `O(n^2)` while actually the best solution should be `O(n)` while taking advantage of `pointer` ignoring the `zeros` since they are known. Check this solution as a reference.

• @KobeAndLebron you can calculate how much accesses to array your algorythm has when all elements are zero. Include also indexOfNonZero method to your analyses , because I think you skip it.

• @vova-rova-gmail-com Let's say that the array is a, for this case that all elements are zero, indexOfNonZero will return a.length, and the for loop of moveZeros will break, so the solution in this case only accesses array a.length times.

• @LHearen What's your worst case?

• @KobeAndLebron You should check the `top-voted` post yourself and simply the worst case should be `O(n)`.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.