Day 46 of 150 Days LeetCode Challenge: Contains Duplicate II

🚀 Day 46 of 150 Days LeetCode Challenge #150DaysOfCode #LeetCode #CodingChallenge #DSA #HashMap #CPlusPlus #Programming #SoftwareEngineering #TechLearning #ProblemSolving #CodeDaily #LeetCode150DaysChallenge #Algorithm #DataStructures 🔹 Problem Statement:Contains Duplicate II Given an integer array nums and an integer k, check if there exist two distinct indices i and j in the array such that: nums[i] == nums[j] |i - j| <= k In simple words: “Does the array contain a duplicate within a distance of k?” 🔹 Example: Input: nums = [1,2,3,1], k = 3 Output: true Explanation: nums[0] and nums[3] are both 1, and the distance between them is 3 ≤ k. 🔹 Approach: Use a hash map to store each number with its most recent index. Iterate through the array: If the number already exists in the map, calculate the distance between the current index and the previous index. If this distance ≤ k, return true. Update the map with the current index. Return false if no such pair is found. Time Complexity: O(n) | Space Complexity: O(n) 🔹 Key Insights: ✅ Hash maps allow O(1) lookups for duplicates. ✅ Always update the index to track the most recent occurrence. ✅ Brute-force approaches take O(n²), but hash maps reduce it to O(n).

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories