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.