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
Time Complexity: O(n)
Space Complexity:O(1) which means it uses constant space regardless of the size of the input list
How it works:
It initializes two variables,
leftandright, to keep track of the positions in the list. Theleftvariable represents the index where the next non-zero element should be placed, and therightvariable iterates over the list elements.It starts iterating over the
numslist using a for loop that ranges from 0 to the length of the list.Inside the loop, it checks if the current element at index
rightis non-zero (since 0 evaluates to False in Python). If the element is non-zero, it proceeds with the next steps.It swaps the element at index
leftwith the element at indexrightusing a simultaneous assignment. This effectively moves the non-zero element to the correct position at the beginning of the list. After the swap, theleftindex is incremented by 1.The loop continues until all elements in the
numslist have been processed.Finally, it returns the modified
numslist. Since the modification is done in-place, the original list is modified directly.
Overall, this code effectively moves all the non-zero elements to the beginning of the list while maintaining their relative order.

Comments
Post a Comment