LeetCode 219: Contains Duplicate II Solution in Java

Just solved **LeetCode 219: Contains Duplicate II** (Easy) using a clean **sliding window + HashSet** approach in Java! 🚀 The key insight: Maintain a set of at most (k+1) recent elements. If you encounter a duplicate before sliding out older ones, the indices are guaranteed to be ≤ k apart. java class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { // If we've already seen this number in the current window, it's a duplicate! if (set.contains(nums[i])) { return true; } // Add the current number to the set (window) set.add(nums[i]); // If the window is too big (more than k+1 elements), remove the oldest one if (set.size() > k) { set.remove(nums[i - k]); } } return false; // No nearby duplicates found } } - Time: O(n) - Space: O(k) What's your favorite sliding window problem? Drop it below! 👇 #LeetCode #Coding #DataStructures #Algorithms #Java #SystemDesign #Tech #InterviewPrep

  • text

To view or add a comment, sign in

Explore content categories