Back to Main
Learn DSA
Depth-First Search
Greedy Algorithms
Get Premium
Two Pointers
Move Zeroes
easy
Python
DESCRIPTION (credit Leetcode.com)
Given an integer array nums, write a function to rearrange the array by moving all zeros to the end while keeping the order of non-zero elements unchanged. Perform this operation in-place without creating a copy of the array.
Input:
Output:
Explanation
We can solve this problem by keeping a pointer i that iterates through the array and another pointer nextNonZero that points to the position where the next non-zero element should be placed. We can then swap the elements at i and nextNonZero if the element at i is non-zero. This way, we can maintain the relative order of the non-zero elements while moving all the zeroes to the end of the array.
Solution
move zeros
0 / 13
1x
Login to track your progress
Your account is free and you can post anonymously if you choose.