Simple O(N) java solution, 6 lines take care of it

  • 3

    The thought process is that we don't care about saving the 0 in the array, when we are scanning the array, as soon as we see a 0, just keep i incrementing without assigning. We only assign value when the element is not 0. In the end, the index save the spot that should have all the zeroes and we can simply fill it with zeroes using Arrays.fill();

    public class Solution {
        public void moveZeroes(int[] nums) {
            int index = 0;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] != 0) {
                    nums[index++] = nums[i];
            Arrays.fill(nums, index, nums.length, 0);

Log in to reply

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