🪙
Leetcode
  • Content
  • Algorithms
    • Linear Search
    • Binary Search
    • Counting Sort
    • Merge Sort
    • Insertion Sort
    • Selection Sort
  • Array and String
    • Introduction to Array
      • Introduction to Array
      • Introduction to Dynamic Array
      • Find Pivot Index
      • Largest Number At Least Twice of Others
      • Plus One
    • Introduction to 2D Array
      • Introduction to 2D Array
      • Diagonal Traverse
      • Spiral Matrix
      • Pascal's Triangle
    • Introduction to String
      • Introduction to String
      • Immutable String - Problems & Solutions
      • Add binary
      • Implement strStr()
      • Longest Common Prefix
    • Two-Pointer Technique
      • Two-pointer Technique - Scenario I
      • Reverse String
      • Array Partition I
      • Two Sum II - Input array is sorted
      • Two-pointer Technique - Scenario II
      • Remove Element
      • Max Consecutive Ones
      • Minimum Size Subarray Sum
    • Conclusion
      • Array-related Techniques
      • Rotate Array
      • Pascal's Triangle II
      • Reverse Words in a String
      • Reverse Words in a String III
      • Remove Duplicates from Sorted Array
      • Move Zeroes
  • Linked List
    • Singly Linked List
      • Introduction - Singly Linked List
      • Add Operation - Singly Linked List
      • Delete Operation - Singly Linked List
      • Design Linked List
    • Two Pointer Technique
      • Two-Pointer in Linked List
      • Linked List Cycle
      • Linked List Cycle II
      • Intersection of Two Linked Lists
      • Remove Nth Node From End of List
      • Summary - Two-Pointer in Linked List
  • Problems
    • 1. Two Sum
    • 2. Add Two Numbers
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 11. Container With Most Water
    • 12. Integer to Roman
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 15. 3Sum
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Find the Index of the First Occurrence in a String
    • 34. Find First and Last Position of Element in Sorted Array
    • 35. Search Insert Position
    • 43. Multiply Strings
    • 49. Group Anagrams
    • 50. Pow(x, n)
    • 54. Spiral Matrix
    • 58. Length of Last Word
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 73. Set Matrix Zeroes
    • 75. Sort Colors
    • 88. Merge Sorted Array
    • 104. Maximum Depth of Binary Tree
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 136. Single Number
    • 146. LRU Cache
    • 189. Rotate Array
    • 206. Reverse Linked List
    • 217. Contains Duplicate
    • 219. Cotains Duplicate II
    • 226. Invert Binary Tree
    • 238. Product of Array Except Self
    • 242. Valid Anagram
    • 268. Missing Number
    • 283. Move Zeroes
    • 350. Intersection of Two Arrays II
    • 383. Ransom Note
    • 389. Find the Difference
    • 412. Fizz Buzz
    • 414. Third Maximum Number
    • 445. Add Two Numbers II
    • 448. Find All Numbers Disappeared in an Array
    • 459. Repeated Substring Pattern
    • 485. Max Consecutive Ones
    • 509. Fibonacci Number
    • 637. Average of Levels in Binary Tree
    • 657. Robot Return to Origin
    • 682. Baseball Game
    • 704. Binary Search
    • 705. Design HashSet
    • 709. To Lower Case
    • 724. Find Pivot Index
    • 876. Middle of the Linked List
    • 896. Monotonic Array
    • 860. Lemonade Change
    • 905. Sort Array By Parity
    • 916. Word Subsets
    • 941. Valid Mountain Array
    • 976. Largest Perimeter Triangle
    • 977. Squares of a Sorted Array
    • 1041. Robot Bounded In Circle
    • 1051. Height Checker
    • 1089. Duplicate Zeros
    • 1232. Check If It Is a Straight Line
    • 1275. Find Winner on a Tic Tac Toe Game
    • 1295. Find Numbers with Even Number of Digits
    • 1299. Replace Elements with Greatest Element on Right Side
    • 1342. Number of Steps to Reduce a Number to Zero
    • 1346. Check If N and Its Double Exist
    • 1476. Subrectangle Queries
    • 1480. Running Sum of 1d Array
    • 1491. Average Salary Excluding the Minimum and Maximum Salary
    • 1502. Can Make Arithmetic Progression From Sequence
    • 1523. Count Odd Numbers in an Interval Range
    • 1572. Matrix Diagonal Sum
    • 1672. Richest Customer Wealth
    • 1768. Merge Strings Alternately
    • 1752. Check if Array Is Sorted and Rotated
    • 1769. Minimum Number of Operations to Move All Balls to Each Box
    • 1790. Check if One String Swap Can Make Strings Equal
    • 1800. Maximum Ascending Subarray Sum
    • 1822. Sign of the Product of an Array
    • 1930. Unique Length-3 Palindromic Subsequences
    • 1991. Find the Middle Index in Array
    • 2185. Counting Words With a Given Prefix
    • 2235. Add Two Integers
    • 2236. Root Equals Sum of Children
    • 2270. Number of Ways to Split Array
    • 2381. Shifting Letters II
    • 2559. Count Vowel Strings in Ranges
    • 2610. Convert an Array Into a 2D Array With Conditions
    • 2657. Find the Prefix Common Array of Two Arrays
    • 3042. Count Prefix and Suffix Pairs I
    • 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
    • 3151. Special Array I
    • 3223. Minimum Length of String After Operations
Powered by GitBook
On this page
  • Example 1
  • Example 2
  • Example 3
  • Constraints
  • Solution
  • Approach Analysis
  • Visualization of Approaches
  • Complexity Analysis
  • Why Solutions Work
  • When to Use
  • Common Patterns & Applications
  • Interview Tips

Was this helpful?

Edit on GitHub
  1. Problems

219. Cotains Duplicate II

🟩 Easy

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Example 1

Input: nums = [1,2,3,1], k = 3 Output: true

Example 2

Input: nums = [1,0,1,1], k = 1 Output: true

Example 3

Input: nums = [1,2,3,1,2,3], k = 2 Output: false

Constraints

  • 1 <= nums.length <= 10^5

  • -10^9 <= nums[i] <= 10^9

  • 0 <= k <= 10^5

Solution

My Solution (Hash Map with Index)

func containsNearbyDuplicate(nums []int, k int) bool {
    m := make(map[int]int)

    for i, num := range nums {
        if j, ok := m[num]; ok && abs(i-j) <= k{
            return true
        }
        m[num]=i
    }

    return false
}

func abs(x int) int {
    if x < 0 {
        x *= -1
    }
    return x
}

Optimal Solution 1 (Sliding Window)

func containsNearbyDuplicate(nums []int, k int) bool {
    window := make(map[int]bool)
    
    for i := 0; i < len(nums); i++ {
        // Remove element outside window
        if i > k {
            delete(window, nums[i-k-1])
        }
        
        // Check if current number exists in window
        if window[nums[i]] {
            return true
        }
        
        // Add current number to window
        window[nums[i]] = true
    }
    
    return false
}

Optimal Solution 2 (Two Pointers)

func containsNearbyDuplicate(nums []int, k int) bool {
    n := len(nums)
    
    for i := 0; i < n; i++ {
        // Only check up to k positions ahead
        for j := i + 1; j <= i + k && j < n; j++ {
            if nums[i] == nums[j] {
                return true
            }
        }
    }
    
    return false
}

Approach Analysis

This problem demonstrates different approaches to handle window constraints:

  1. Hash Map with Index (Your Solution):

    • Store value-index pairs

    • Check distance on duplicates

    • Early termination

    • Space-time balanced

  2. Sliding Window:

    • Maintain k-sized window

    • Remove old elements

    • Check current window

    • Memory efficient

  3. Two Pointers:

    • Direct index comparison

    • Limited search range

    • No extra space

    • Simple implementation

Visualization of Approaches

Hash Map Process (Your Solution)

Input: nums = [1,2,3,1], k = 3

Step 1: map = {1: 0}
Step 2: map = {1: 0, 2: 1}
Step 3: map = {1: 0, 2: 1, 3: 2}
Step 4: Check 1 → found at index 0
        abs(3-0) = 3 ≤ k(3)
        return true

Sliding Window Process

Input: nums = [1,2,3,1], k = 3

Step 1: window = {1}
Step 2: window = {1,2}
Step 3: window = {1,2,3}
Step 4: Check 1 → found in window
        return true

Two Pointers Process

Input: nums = [1,2,3,1], k = 3

i=0: check [1,2,3] → no match
i=1: check [2,3,1] → no match
i=2: check [3,1] → no match
i=3: done (previous checks covered all pairs)

Complexity Analysis

Hash Map Solution (Your Solution)

  • Time: O(n)

    • Single pass through array

    • O(1) map operations

    • Early termination

  • Space: O(n)

    • Stores all unique indices

    • Map overhead

    • Worst case: all unique

Sliding Window Solution

  • Time: O(n)

    • Linear scan

    • Window operations O(1)

    • Delete operations O(1)

  • Space: O(k)

    • Fixed window size

    • Maximum k elements

    • More memory efficient

Two Pointers Solution

  • Time: O(n*k)

    • Nested loops

    • k comparisons per element

    • No early termination

  • Space: O(1)

    • No extra storage

    • Only pointers

    • Most space efficient

Why Solutions Work

  1. Hash Map Logic:

    • Track last seen index

    • Quick distance check

    • Update on duplicates

    • Maintain history

  2. Sliding Window:

    • Fixed size window

    • Remove old elements

    • Contains duplicates

    • Distance guaranteed

  3. Two Pointers:

    • Direct comparison

    • Limited range check

    • No extra storage

    • Simple but slower

When to Use

  1. Hash Map When:

    • Memory available

    • Quick lookups needed

    • Early termination helps

    • Index tracking important

  2. Sliding Window When:

    • Memory constrained

    • Fixed window size

    • Stream processing

    • Order matters

  3. Two Pointers When:

    • No extra space allowed

    • k is small

    • Simple code preferred

    • Memory critical

Common Patterns & Applications

  1. Related Problems:

    • Contains Duplicate III

    • Sliding Window Maximum

    • Find All Anagrams

    • Longest Substring

  2. Key Techniques:

    • Sliding window

    • Hash map tracking

    • Two pointers

    • Distance constraints

Interview Tips

  1. Solution Highlights:

    • Multiple approaches

    • Space-time tradeoffs

    • Early termination

    • Window management

  2. Common Pitfalls:

    • Off-by-one errors

    • Window boundaries

    • Index calculations

    • Memory management

  3. Testing Strategy:

    • k = 0 case

    • k > array length

    • Duplicate at distance k

    • No duplicates

    • All duplicates

  4. Follow-up Questions:

    • Streaming data?

    • Limited memory?

    • Parallel processing?

    • Different distance metrics?

Previous217. Contains DuplicateNext226. Invert Binary Tree

Last updated 5 months ago

Was this helpful?

Leetcode:

link
result