Leetcode [283] - Move Zeros (Java Solution)

Rugved avatar

Rugved

Leetcode [283] - Move Zeros (Java Solution)
Category: Easy
What is used: Array

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 1:

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

Note:

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

Solution

I am using Simple Array to solve this problem. There are various different methods to solve this problem but this is one the most straight forward and simple way.

I traverse through the array and keep count of non-zero numbers. While iterating through the array, set array[count++] = arr[i]. In the end, traverse again to set the remaining elements as zero.

class Solution {
    public void moveZeroes(int[] nums) {
        int count = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++){
            if(nums[i] != 0){
                nums[count++] = nums[i];
            }
        }
        for (int j = count; j < n; j++){
            nums[j] = 0;
        }
    }
}

Time complexity:

The time complexity of this code is O(n)
The space complexity of this code is O(1)

Submission Details:

Runtime: 0 ms. Runtime beats 100.00 % of java submissions.
Memory Usage: 37.7 MB

Rugved avatar
Written By

Rugved

Android Developer based in Los Angeles trying to be improve programming skills!
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.