Move Zeroes
Move Zeroes is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the In-place Array Modification subpattern.
Problem statement
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.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Constraints:
- 1 <= nums.length <= 104
- -231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
Topics and companies
Topics: Array, Two Pointers.
Reported in interviews at Facebook, Bloomberg, Microsoft, Adobe, Capital One, Apple, Amazon, Google, eBay, SAP, Uber, Paypal and others.
How to practise Move Zeroes on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n), where n is the length of nums. We traverse the array twice: once to move non-zeroes forward, and once to fill zeros at the end. time and O(1), since the operation is done in-place and no extra space proportional to input size is used. space.
Open Move Zeroes in the code editor, or read the Move Zeroes editorial for a worked solution with its approach and complexity analysis.
Where Move Zeroes sits in the DSA pattern sheet
- Two Pointers pattern guide
- In-place Array Modification subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Move Zeroes
Other problems that use the same In-place Array Modification and Two Pointers techniques:
- Intersection of Two Arrays — Easy, same subpattern
- Move Pieces to Obtain a String — Medium, same subpattern
- Remove Duplicates from Sorted Array — Easy, same subpattern
- Remove Duplicates from Sorted Array II — Medium, same subpattern
- Remove Element — Easy, same subpattern
- Separate Black and White Balls — Medium, same subpattern
Preparing your workspace
Progress is saved as you study.