Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 26 · Two Pointers

Remove Duplicates from Sorted Array

LeetCode 26 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Write pointer advances only on a new value.

ಸುಲಭArrayTwo Pointers
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Remove Duplicates from Sorted Array (LeetCode 26) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Pointers ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

In a sorted array duplicates sit together. Keep a write index; copy an element forward only when it differs from the one before it. The first insert_index slots end up holding each value once.

Approach

  1. 1

    insert_index starts at 1 (the first element is always kept).

  2. 2

    Skip nums[i] if it equals nums[i−1].

  3. 3

    Otherwise write it at insert_index and advance.

  4. 4

    Return insert_index — the count of unique values.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Read / write pointersPythonO(n) time · O(1) space
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        insert_index=1
        for i in range(1,len(nums)):
            if nums[i]==nums[i-1]:
                continue
            nums[insert_index]=nums[i]
            insert_index+=1
        return insert_index
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Remove Duplicates from Sorted Array — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Remove Duplicates from Sorted Array ಹಿಂದಿನ intuition ಏನು?

In a sorted array duplicates sit together. Keep a write index; copy an element forward only when it differs from the one before it. The first insert_index slots end up holding each value once.

Remove Duplicates from Sorted Array (LeetCode 26) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. insert_index starts at 1 (the first element is always kept). 2. Skip nums[i] if it equals nums[i−1]. 3. Otherwise write it at insert_index and advance. 4. Return insert_index — the count of unique values.

Remove Duplicates from Sorted Array ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(1). (Accepted approach: Read / write pointers.)

Remove Duplicates from Sorted Array ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Compare with nums[i−1] (the original neighbour), not with the write slot.