Optimized LeetCode 219 solution with HashMap

💻 Day 89 of #100DaysOfCoding Challenge 📘 Problem: LeetCode 219 — Contains Duplicate II 🎯 Level: Easy 🧩 Problem Statement: Given an integer array nums and an integer k, return true if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k. 🧠 Approach: Initially, I solved this problem using nested loops, but it resulted in a Time Limit Exceeded (TLE) due to O(n²) complexity. To optimize it, I used a HashMap to store each element and its latest index. This allows checking duplicates within distance k in O(1) time for each iteration — giving an overall O(n) solution. 🕒 Time Complexity: O(n) 💾 Space Complexity: O(n) ✅ Key Takeaway: Sometimes, a brute-force solution may pass small test cases but fail large ones due to inefficiency. Optimizing with appropriate data structures like HashMap or HashSet can significantly improve performance. #LeetCode #Java #HashMap #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories