Move Zeroes
Easy About 10 min Free, no account needed
Push all zeros to the end while keeping the other values in order.
The brief
Given an integer array nums, return it with all 0s moved to the end
while the relative order of the non-zero values is preserved.
The obvious approach finds each zero and shifts everything after it left by one; shifting is O(n) per zero, so an array full of zeros costs O(n2). The hidden test is 100,000 zeros followed by a one, so the per-zero shifting is too slow. You will need a single-pass approach, O(n).
Starter code
using System;
public class Solution
{
// TODO: return the array with all zeros pushed to the end and non-zero order preserved.
public int[] MoveZeroes(int[] nums)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Two pointers
- Walk a sorted or symmetric sequence from both ends, or fast and slow, instead of checking every pair.
Related katas
- Happy Number Easy Free Does repeatedly summing squared digits reach 1 - and how do you KNOW it will not?
- Merge Sorted Arrays Easy Free Merge two sorted arrays into one - without destroying what makes them special.
- Remove Duplicates From Sorted Array Easy Free Deduplicate a sorted array without forgetting that it is sorted.
- Two Sum II (Sorted Input) Easy Free Two Sum again - but the array is sorted, and that changes everything.