Solved LeetCode #219 with Java and HashMap

🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories