Move Zeroes

Easyarraytwo-pointers
Category: Array & Hashing
Companies that ask this question:
FacebookAmazonBloomberg

Approach

Move Zeroes

Problem Statement

Given an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements.

Note: You must do this in-place without making a copy of the array.

Examples

Example 1:

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

Example 2:

Input: nums = [0]
Output: [0]

Approach

Two pointers: one tracks position to place next non-zero, other scans array. Swap non-zeros to front.

Complexity

  • Time: O(n)
  • Space: O(1)

Solution

java
1class Solution {
2    public void moveZeroes(int[] nums) {
3        int left = 0;
4        for (int right = 0; right < nums.length; right++) {
5            if (nums[right] != 0) {
6                int temp = nums[left];
7                nums[left] = nums[right];
8                nums[right] = temp;
9                left++;
10            }
11        }
12    }
13}
Loading visualizer...