Move zeros to end

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


Problem Link : https://leetcode.com/problems/move-zeroes

Time complexity : O(n) Space Complexity : O(1)

class Solution {
    public void moveZeroes(int[] nums) {
        int index = 0;
        for(int idx = 0; idx < nums.length; idx++)
        {
            if(nums[idx] != 0)
            {
                nums[idx] = nums[idx] ^ nums[index];
                nums[index] = nums[idx] ^ nums[index];
                nums[idx] = nums[idx] ^ nums[index];

                index++;
            }
        }
    }
}


© 2024 by Chiranjeevi Karthik