1. Description

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

Constraints:

  1. You must do this in-place without making a copy of the array.
  2. \(1\leq nums.length \leq 10^{4}\)
  3. \(-2^{31} \leq nums[i] \leq 2^{31}-1\)

1.1. Examples:

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

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

2. Solution

2.1. Understanding the problem

Again, let's first consider the trivial case where len(nums) == 1. We don't need to do anything in this case.

In general, we will have to at least scan nums once.

2.2. Algorithm

Scan the array and look for 0's and record their position. Iterate through their positions and remove zeroes, append zero in the end.

2.3. Code

def moveZeroes(nums):
    """
    :type nums: List[int]
    :rtype: None Do not return anything, modify nums in-place instead.
    """
    poses = []
    for i, n in enumerate(nums):
        if n == 0:
            poses.append(i)

    for i, pos in enumerate(poses):
        # we use pos-i because we moved i number of zeros to the end
        nums.append(nums.pop(pos-i))


# tests
nums = [0]
moveZeroes(nums)
print(nums == [0])

nums = [0, 1]
moveZeroes(nums)
print(nums == [1, 0])

nums = [0, 1, 2, 0]
moveZeroes(nums)
print(nums == [1, 2, 0, 0])

nums = [1, 2 ]
moveZeroes(nums)
print(nums == [1, 2])
True
True
True
True

2.3.1. Complexity

2.3.1.1. Time complexity:

O(n), one full scan.

2.3.1.2. Space complexity:

O(n), potentially nums can be all zeroes so len(poses) == len(nums).

2.4. Leetcode solution

nil.

<<imports for typing>>


2.4.1. Time complexity:

2.4.2. Space complexity:

3. More analysis

3.1. General thoughts

3.2. Related problems

4. Log time