Move Zeroes
LeetCode 283 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Two pointers: swap the next non-zero into the first zero slot.
నేను Move Zeroes (LeetCode 283) ను ఇలా పరిష్కరించాను — Two Pointers ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Keep a slow pointer l at the first zero. A fast pointer r scans ahead; whenever it finds a non-zero while l sits on a zero, swap them and advance l. Non-zeros keep their order and zeros drift to the end.
Approach
- 1
l starts at 0, r scans from l+1.
- 2
If nums[l] is non-zero, just advance l.
- 3
Otherwise, when nums[r] is non-zero, swap and advance l.
నేను ఎలా పరిష్కరించాను
Two pointers swapPythonO(n) time · O(1) space
class Solution:
def moveZeroes(self, nums):
l = 0
for r in range(l + 1, len(nums)):
# if left pointer is not zero, move left to right
if nums[l] != 0:
l += 1
else:
# right pointer is not zero: swap with left pointer
if nums[r] != 0:
nums[l], nums[r] = nums[r], nums[l]
l += 1
return numsMove Zeroes — తరచూ అడిగే ప్రశ్నలు
Move Zeroes వెనుక ఉన్న intuition ఏమిటి?
Keep a slow pointer l at the first zero. A fast pointer r scans ahead; whenever it finds a non-zero while l sits on a zero, swap them and advance l. Non-zeros keep their order and zeros drift to the end.
Move Zeroes (LeetCode 283) ను ఎలా పరిష్కరించాలి?
1. l starts at 0, r scans from l+1. 2. If nums[l] is non-zero, just advance l. 3. Otherwise, when nums[r] is non-zero, swap and advance l.
Move Zeroes యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Two pointers swap.)
Move Zeroes లో సాధారణ పొరపాట్లు ఏమిటి?
Order of the non-zero elements must be preserved — swapping keeps it.