Easy · Read and Write Pointers
Understand → Visualise → Practice.
Move all zero values to the end while preserving the relative order of non-zero values.
A write pointer marks where the next non-zero goes. Copying non-zeros forward in order keeps their relative order; the remaining slots become zeros.
Look at every value in order.
Copy each non-zero to position write and advance write.
Set every position from write to the end to 0.
O(n) time and O(1) extra space.
Swapping each zero with the last element breaks the order of the non-zero values.
Read the full guide first: Two Pointers and Sliding Windows.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.