# Leetcode Move-Zeroes #### 2022-07-11 09:55 > ##### Algorithms: > #algorithm #two_pointers #array_in_place_operation > ##### Data structures: > #DS #array > ##### Difficulty: > #coding_problem #difficulty-easy > ##### Additional tags: > #leetcode > ##### Revisions: > N/A ##### Related topics: ```expander tag:#array_in_place_operation OR tag:#two_pointers ``` - [[Leetcode Intersection-of-Two-Arrays-II]] - [[Leetcode Merge-Sorted-Array]] - [[Leetcode Merge-Two-Sorted-Lists]] - [[Leetcode Rotate-Array]] - [[Leetcode Squares-of-a-Sorted-Array]] - [[Two pointers approach]] ##### Links: - [Link to problem](https://leetcode.com/problems/move-zeroes/) ___ ### Problem 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. **Follow up:** Could you minimize the total number of operations done? #### Examples **Example 1:** **Input:** nums = [0,1,0,3,12] **Output:** [1,3,12,0,0] **Example 2:** **Input:** nums = [0] **Output:** [0] #### Constraints **Constraints:** - `1 <= nums.length <= 104` - `-231 <= nums[i] <= 231 - 1` ### Thoughts > [!summary] > This is a #array_in_place_operation problem. Because the data can be overwritten, and zeros can be predicted in the result array, I use in-place array operations. ### Solution ```cpp class Solution { public: void moveZeroes(vector &nums) { // Tow pointers, since data can be overwritten and one pointer is faster // than another. int num = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[num++] = nums[i]; } } for (int j = num; j < nums.size(); j++) { nums[j] = 0; } } }; ```