LeetCode #283 Move Zeroes

Easy

Len Chen
1 min readSep 15, 2018

Problem

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

Example:

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

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Solution

Use two pointers iand j. i denotes to first zero position in list and j is for iterating whole list. Once we found a none zero element in iteration, swap i and j, then move i to next position.

Complexity

Obviously list will be iterated only once so it takes O(n) times with only O(1) extra space.

--

--

Len Chen
Len Chen

No responses yet