#283

Move Zeroes

Easy
ArrayTwo PointersTwo PointersIn-place Array Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a two-pointer technique to efficiently rearrange the elements in-place. One pointer tracks the position for non-zero elements, while the other iterates through the array.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a pointer 'lastNonZeroFoundAt' to 0.
  2. 2Step 2: Iterate through the array with another pointer 'current'.
  3. 3Step 3: If the current element is non-zero, place it at 'lastNonZeroFoundAt' and increment 'lastNonZeroFoundAt'.
  4. 4Step 4: After the loop, fill the remaining positions in the array with zeros.
solution.py8 lines
1def moveZeroes(nums):
2    lastNonZeroFoundAt = 0
3    for current in range(len(nums)):
4        if nums[current] != 0:
5            nums[lastNonZeroFoundAt] = nums[current]
6            lastNonZeroFoundAt += 1
7    for i in range(lastNonZeroFoundAt, len(nums)):
8        nums[i] = 0

Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we are rearranging the elements in-place without using extra space.

  • 1Using in-place operations minimizes space complexity.
  • 2Two-pointer technique is efficient for rearranging elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.