Fixed Java Code for "Contains Duplicate II" with Sliding Window

🚀 Fixed a Logical Bug in “Contains Duplicate II” (Sliding Window Problem in Java) Today I revisited one of the seemingly simple problems — “Contains Duplicate II” — and realized how small syntax choices can completely change logic flow 😅 At first, I wrote the code using a mix of C++ and Java syntax, which caused compilation and logical issues. But while debugging, I learned some key lessons that made my solution cleaner, faster, and interview-ready 💪 🧩 The Problem 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] && |i - j| <= k ⚙️ My Fixed Java Code import java.util.HashSet; class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> set = new HashSet<>(); int i = 0; int j = 0; int n = nums.length; while (j < n) { if (Math.abs(j - i) > k) { set.remove(nums[i]); i++; } if (set.contains(nums[j])) { return true; } set.add(nums[j]); j++; } return false; } } ❌ Mistakes I Made Initially 1️⃣ Used set.get() and set.end — which belong to C++, not Java. ✅ Fixed by using set.contains(nums[j]). 2️⃣ Didn’t maintain a proper sliding window size. ✅ Simplified with if (Math.abs(j - i) > k) to ensure the window never exceeds k elements. 3️⃣ Didn’t clearly understand the window logic — that we remove older elements as we move forward. ✅ Learned to visualize the window as a moving frame over the array. 4️⃣ Overcomplicated the logic. ✅ Cleaned it up using a simple while loop and HashSet. 🧠 What I Learned Clean, minimal code > fancy syntax. Always check for language-specific methods — C++ vs Java can trick you! The sliding window technique isn’t about moving two pointers randomly — it’s about maintaining constraints efficiently. Debugging teaches more than success on the first try. 🎯 Targeting Product-Based & EdTech Companies As part of my SDE preparation for product-based and EdTech companies like FloBiz, Scaler, Razorpay, Unacademy, and Swiggy, I’m focusing on building strong fundamentals — not just solving problems, but deeply understanding why they work. 💬 Final Thought Every “wrong submission” is just a lesson wrapped in logic. Keep coding, keep debugging, and every small improvement compounds over time 💻🔥 Masai Prepleaf by Masai Newton School PhonePe Paytm Paytm Payments Bank Razorpay Razor Group PayU #Java #DSA #ProblemSolving #LeetCode #LearningInPublic #SoftwareDevelopment #ProductBasedPreparation #CodeWithDilsah #EdTech #FrontendDeveloper #FloBiz

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories