Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 283 · Two Pointers

Move Zeroes

LeetCode 283 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Two pointers: swap the next non-zero into the first zero slot.

எளிதுArrayTwo Pointers
LeetCode இல் திற ↗

நான் 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. 1

    l starts at 0, r scans from l+1.

  2. 2

    If nums[l] is non-zero, just advance l.

  3. 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 nums
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Move 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.