Monday, April 20, 2015

[SAP Labs] Move all zeroes to end of array

Problem: Given an array of integers, move all the zero’s in a given array to the end of the array. The order of all other elements should remain same. We need to do it inplace.

Example:
Input: nums = [0,2,0,7,19]
Output: [2,7,19,0,0]


Approach: It's a simple problem to solve using two pointers approach. The only problem here is we need to maintain the order so we can't go with start and end pointers but what we can do is first we move all the nonzero elements in the begining using two pointers and then just fill the rest of the array with 0.


Implementation:

    public void MoveZeroes(int[] nums)
    {
        int length = nums?.Length ?? 0;
        if (length <= 1)
        {
            return;
        }
        int j = 0;
        for (int i = 0; i < length; ++i)
        {
            if (nums[i] != 0)
            {
                nums[j++] = nums[i];
            }
        }
        for (; j < length; ++j)
        {
            nums[j] = 0;
        }
    }


Complexity: O(n)

No comments:

Post a Comment