Move Zeros to the Front with Two Pointers
Updated
Problem statement
Move every zero in an integer array to the beginning. The relative order of nonzero values need not be preserved.
Use this two-pointer rule: repeatedly swap the leftmost nonzero value with the rightmost zero strictly to its right. Stop when no such pair remains. Return the resulting array.
For example, [1,0,5,6,0,2,0] could become [0,0,0,5,2,6,1], but the specified swaps produce [0,0,0,6,5,2,1]; both move every zero to the front.
Function
moveZerosToFront(nums: int[]) → int[]Examples
Example 1
nums = [1,0,5,6,0,2,0]return = [0,0,0,6,5,2,1]Swap the leftmost 1 with the last zero, then swap 5 with the remaining rightmost zero.
Example 2
nums = [0,4,0,-2,9]return = [0,0,4,-2,9]The first zero is already at the front. Swap 4 with the zero at index 2.
Example 3
nums = [2,3,4]return = [2,3,4]No zero exists, so the array stays unchanged.
Constraints
0 <= nums.length <= 100000.-1000000000 <= nums[i] <= 1000000000.- The two-pointer algorithm uses constant working variables; language-level input and return copies are outside this bound.
More NVIDIA Onsite Interview questions
- Check Endianness Of A Byte ArrayONSITE INTERVIEW · Seen Sep 2026
- Implement MallocONSITE INTERVIEW · Seen Sep 2026
- Implement PrintfONSITE INTERVIEW · Seen Sep 2026
- Merge Two Arrays Into Sorted OrderONSITE INTERVIEW · Seen Sep 2026
- Middle Node Of A Linked ListONSITE INTERVIEW · Seen Sep 2026
- Ping Reply TrackingONSITE INTERVIEW · Seen Sep 2026
- Reverse A StringONSITE INTERVIEW · Seen Sep 2026
- Maximum Fish in a GridONSITE INTERVIEW · Seen Sep 2024
- Minimum in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Sep 2024
- First Register Overflow TickONSITE INTERVIEW · Seen May 2024
Similar questions at other companies
- Sparse Vector Dot Product from TuplesMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Merge Sorted ArrayDP World · ONSITE INTERVIEW
- Remove Duplicates From Sorted Array In PlaceKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Maximize Distance to the Closest Occupied SeatAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Alternate Positive and Negative ValuesTesla · ONSITE INTERVIEWTesla interview questions
- Make a Sorted Array Unique In PlaceAlpaca · ONSITE INTERVIEW
- Two SumMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximize Distance to Closest Person — Return the SeatRoblox · ONSITE INTERVIEWRoblox interview questions
- Move ZeroesBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Rotate an Array to the RightScale AI · ONSITE INTERVIEWScale AI interview questions