# 0283. Move Zeroes

{% tabs %}
{% tab title="❓ Problem Statement" %}

> Source: [LeetCode - Move Zeroes](https://leetcode.com/problems/move-zeroes/)\
> GitHub: [Solution / Performance](https://github.com/yylou/leetcode/tree/main/0283-move-zeroes)

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

**Note** that you must do this **in-place without making a copy** of the array.
{% endtab %}

{% tab title="✍🏻 Constraints & Example" %}
**Constraints:**

* `1 <= nums.length <= 10^4`
* `-2^31 <= nums[i] <= 2^31 - 1`

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

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

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="💡 Ideas" %}
{% hint style="info" %}
**Two pointers**: one is for **placing non-zero numbers** (since we need to move zero to the end), the other one is for **iterating** from the beginning.
{% endhint %}

Whenever move-pointer meets the non-zero integer, we swap it with the element pointed by the place-pointer, which is initialized at the index 0.

Also, for each iteration, we move the place-pointer by increasing its index when we perform a swap operation.
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="🤖 Python3" %}

```python
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        #  (base case)
        if len(nums) == 1: return
        
        # ==================================================
        #  Array + Two Pointer                             =
        # ==================================================
        # time  : O(n)
        # space : O(1)
        
        placeP, moveP = 0, 0
        
        while moveP < len(nums):
            if nums[moveP] != 0: 
                nums[placeP], nums[moveP] = nums[moveP], nums[placeP]
                placeP += 1
            
            moveP += 1
```

{% endtab %}

{% tab title="🤖 Java" %}

```java
class Solution {
    /**
     * @time  : O(n)
     * @space : O(1)
     */
    
    public void moveZeroes(int[] nums) {
        /* base case */
        if(nums.length == 1) return;
        
        int moveP = 0, placeP = 0;
        
        while(moveP < nums.length) {
            if(nums[moveP] != 0) {
                /* swap */
                int tmp = nums[placeP];
                nums[placeP] = nums[moveP];
                nums[moveP] = tmp;
                
                placeP += 1;
            }
            
            moveP += 1;
        }
    }
}
```

{% endtab %}
{% endtabs %}
