283. Move Zeroes

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

Note that you must do this in-place without making a copy of the array.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

Follow up: 

Could you minimize the total number of operations done?

Solution:

  • Approach 1: We can create an additional array of the same size (initialized with and if the value is not zero we can keep copying numbers. It’s simple but required additional space of O(n). Definitely can be optimized in term of space complexity
  • Approach 2: We can use two pointer approach. One pointer will always point to zero and another one will move towards non-zero, and whenever non-zero number found it will be replaced with zero and both pointers will be moved.
class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length;
  
        if(n == 0 || n == 1){
          return;
        }
        int right = 0, left = 0;
        int temp;
        while (right < n){
          if(nums[right] == 0){
            ++right;
          }
          else{
            temp = nums[right];
            nums[right] = nums[left];
            nums[left] = temp;
            ++right;
            ++left;
          }
        }
    }
}
Advertisement

Leave a Reply

Your email address will not be published. Required fields are marked *

five × 5 =