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

मैंने 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.