Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 219 · Fixed Window

Contains Duplicate II

LeetCode 219 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Last-seen index map; compare distance.

सोपाArrayHash TableSliding Window

मी Contains Duplicate II (LeetCode 219) असा सोडवला — Fixed Window पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Remember the last index of every value. When the same value shows up again, check whether the distance to its last occurrence is at most k.

Approach

  1. 1

    For each index i and value num.

  2. 2

    If num was seen and i − last ≤ k, return True.

  3. 3

    Update the last index for num.

मी कसा सोडवला

Last-index mapPythonO(n) time · O(n) space
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        seen = {}
        for i,num in enumerate(nums):
            if num in seen:
                 j = seen.get(num)
                 if abs(i-j)<=k:
                    return True
            seen[num]=i
        return False
स्टेप-थ्रू लोड होत आहे…

Contains Duplicate II — वारंवार विचारले जाणारे प्रश्न

Contains Duplicate II मागील intuition काय आहे?

Remember the last index of every value. When the same value shows up again, check whether the distance to its last occurrence is at most k.

Contains Duplicate II (LeetCode 219) कसा सोडवावा?

1. For each index i and value num. 2. If num was seen and i − last ≤ k, return True. 3. Update the last index for num.

Contains Duplicate II ची time आणि space complexity किती आहे?

Time: O(n). Space: O(n). (Accepted approach: Last-index map.)

Contains Duplicate II मध्ये सामान्य चुका कोणत्या?

Always update to the latest index — older ones are farther away.