easyStack
Rearrange Integer Array Solution
Problem Statement
Given an array of integers `array`, reorder the elements so that all zero values are relocated to the end of the array, preserving the original sequence of non-zero elements.
Examples
Example 1:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Explanation: Move all zeroes to the end of the array while maintaining the relative order of non-zero elements
Example 2:
Input:[0,0,1]
Output:[1,0,0]
Explanation: Move all zeroes to the end of the array while maintaining the relative order of non-zero elements
Time: O(n) Space: O(1)
The optimal approach uses a two-pointer technique, where one pointer is used to track the position of the next non-zero element and the other pointer is used to iterate through the array, resulting in a time complexity of O(n).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def moveZeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
return nums