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
LeetCode 219: Contains Duplicate II Solution in Java
More Relevant Posts
-
Day26 - LeetCode Journey Solved LeetCode 345: Reverse Vowels of a String in Java ✅ This problem was a fun twist on the classic string reversal pattern. Instead of reversing the whole string, the focus was only on vowels, which makes you think a little more carefully about pointer movement and conditions. Using the two-pointer approach here felt really clean. One pointer moves from the start, the other from the end, and both skip non-vowel characters until a valid swap is possible. Simple logic, but very effective. It’s a great example of how a small condition change can turn an easy problem into a nice logical exercise. What I enjoyed most was how this problem strengthens selective traversal. You’re not touching every character blindly, you’re filtering and acting only when needed. That mindset is very useful in optimizing solutions. Key takeaways: • Strong practice of the two-pointer technique • Efficient handling of character filtering • Clean in-place swapping logic • Better understanding of conditional traversal ✅ Solution accepted successfully ✅ Solid performance with clean and readable code Problems like this make string manipulation feel more intuitive and structured. One more step forward in sharpening fundamentals 💪 #LeetCode #DSA #Java #Strings #TwoPointers #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #Consistency #DailyPractice
To view or add a comment, sign in
-
-
Day25 - LeetCode Journey Solved LeetCode 344: Reverse String in Java ✅ This was a simple problem on the surface, but it perfectly highlights how powerful clean logic can be. The goal was to reverse a string in-place using O(1) extra space, which means no extra arrays and no shortcuts. Just pure two-pointer logic. Using the left and right pointers and swapping characters step by step felt very satisfying. It’s one of those patterns that looks small but appears everywhere in interviews and real-world problems. Mastering this makes many string and array problems much easier later on. What I liked about this problem is how it teaches efficiency. Instead of creating new memory, we directly modify the existing array. That mindset of optimizing space is extremely important in DSA. Key takeaways: • Strong practice of the two-pointer technique • In-place operations with constant extra space • Clean and readable swapping logic • Reinforced fundamentals of string manipulation ✅ Accepted successfully ✅ 0 ms runtime with optimal performance Sometimes the simplest problems build the strongest foundations. Consistency with basics is what makes complex problems feel easier later 💪 #LeetCode #DSA #Java #Strings #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #TwoPointers #Consistency #DailyPractice
To view or add a comment, sign in
-
-
🌙Shallow Copy (clone / Arrays.copyOf) of an array ☐☐☐ Outer array becomes new ✅ Inner arrays are still SAME references ❌ So if you change inside value → both change. ✅ original and shallow point to different outer arrays (different addresses) ❌ but original[i] and shallow[i] point to the same inner row arrays (same addresses) In one line:✅ “Two variables point to different outer arrays, but the rows inside are pointing to the same memory.” ✅ in shallow copy, outer array is new, but the rows are shared, so changing a cell changes both. ❌If you assign a new 1D row to the copied 2D array, only that row becomes different in the copy; the other rows still stay shared with original. A 2D array in Java is actually: ✅ “array of references to 1D arrays” So when you clone the outer array, Java copies: the list of references (outer) not the actual row arrays (inner) Cell change: shallow[0][0] = 5 ➡️ You edited the same shared row → both see it ✅ Row replacement: shallow[0] = new int[]{...} ➡️ You changed only which row reference shallow points to → original remains same ✅ ✅ toString() prints only the memory address of inner arrays (useless). ✅ Arrays.deepToString() prints the actual values inside all rows (proper output). GitHub Link: https://lnkd.in/g2j8X_-z 🔖Frontlines EduTech (FLM) #Java #Arrays #DeepCopy #2DArray #JavaProgramming #Coding #DSA #ProgrammingBasics #LearnJava #CodeSnippet
To view or add a comment, sign in
-
-
#Day 63: LeetCode 1984 - Minimum Difference Between Highest and Lowest of K Scores Code:- import java.util.Arrays; class Solution { public int minimumDifference(int[] nums, int k) { // Step 1: Handle the edge case where only one score is picked if (k == 1) return 0; // Step 2: Sort the scores to bring close values together Arrays.sort(nums); int minDiff = Integer.MAX_VALUE; // Step 3: Slide a window of size k through the array // The window starts at 'i' and ends at 'i + k - 1' for (int i = 0; i <= nums.length - k; i++) { int currentDiff = nums[i + k - 1] - nums[i]; // Step 4: Update the global minimum difference if (currentDiff < minDiff) { minDiff = currentDiff; } } return minDiff; } } #The Strategy: ->Sort the scores to align them by magnitude. ->Apply a Sliding Window of size $k$ to look at every possible 'cluster' of scores. ->Calculate the spread (Max - Min) for each cluster and capture the minimum. #100DaysOfCode #Java #SoftwareEngineering #Algorithms #LeetCode #SDE #ProblemSolving #SlidingWindow"
To view or add a comment, sign in
-
-
Day 1 of #DSAChallenge 🚀 📌 Problem: Longest Common Prefix 📍 Platform: LeetCode 🔹 Problem Statement: Given an array of strings, find the longest common prefix among them. If no common prefix exists, return an empty string. ━━━━━━━━━━━━━━━━━━ 🔹 Approach: ✔ Took the first string as the initial prefix ✔ Compared it with every other string ✔ Reduced the prefix step-by-step using character comparison ✔ Stopped comparison as soon as mismatch occurs ━━━━━━━━━━━━━━━━━━ 🔹 Java Implementation: class Solution { public String common(String s1, String s2) { int n = Math.min(s1.length(), s2.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (s1.charAt(i) == s2.charAt(i)) sb.append(s1.charAt(i)); else break; } return sb.toString(); } public String longestCommonPrefix(String[] strs) { String res = strs[0]; for (int i = 0; i < strs.length; i++) { res = common(res, strs[i]); } return res; } }
To view or add a comment, sign in
-
-
🚀 Day 28 of my DSA Journey (LeetCode + Java) Today’s focus was completely on Sliding Window + Hashing patterns. All three problems looked different, but the core logic was about maintaining a valid window and updating the answer efficiently. ✅ Problems Solved Today: LC 3 – Longest Substring Without Repeating Characters LC 424 – Longest Repeating Character Replacement LC 1004 – Max Consecutive Ones III 🧠 My Experience Solving These: 🔸 3. Longest Substring Without Repeating Characters This is a classic sliding window + HashMap problem. Used a HashMap to store last index of characters If a character repeats, moved left pointer smartly Calculated window length using right - left + 1 Very clean logic once the window movement is clear. 🔸 424. Longest Repeating Character Replacement This one was tricky but powerful. Maintained frequency array for characters Tracked the most frequent character (maxCount) If window size – maxCount > k → shrink window Understanding why maxCount doesn’t decrease was the key insight. 🔸 1004. Max Consecutive Ones III Sliding window on array with condition. Count number of zeros in the window If zeros > k → move left pointer Always track maximum window length Simple idea, very effective solution. 📌 Key Takeaway Today: Sliding Window problems are all about maintaining a valid window. ✔ Decide what makes window invalid ✔ Expand using right pointer ✔ Shrink using left pointer ✔ Update answer at every step ✔ Avoid nested loops → O(n) always wins The more I practice, the faster I recognize patterns. 💪 Consistency + daily effort = confidence. On to Day 29 🚀 #DSA #LeetCode #Java #SlidingWindow #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
LeetCode Daily — Problem #3794: Reverse String Prefix Today’s challenge was a fun string manipulation task: Problem: Given a string s and an integer k, reverse the first k characters and return the resulting string. Example: Input: s = "abcd", k = 2 Output: "bacd" Approach: I converted the string to a character array, reversed the first k characters using a loop, and then appended the rest. Here's the Java solution:✅ Result: Accepted with 0 ms runtime! Takeaway: This problem reinforced how simple logic and clean iteration can solve string-based challenges efficiently. It’s a great reminder that even “Easy” problems can sharpen your fundamentals. #LeetCode #Java #StringManipulation #CodingChallenge #100DaysOfCode #ProblemSolving #LinkedInLearning
To view or add a comment, sign in
-
-
🚀 Day 23 of my DSA Journey (LeetCode + Java) Today’s practice was all about Sliding Window — one of the most powerful and efficient patterns for subarray and substring problems. All three problems became easy once I identified the correct window movement. ✅ Problems Solved Today: LC 209 – Minimum Size Subarray Sum LC 1456 – Maximum Number of Vowels in a Substring of Given Length LC 643 – Maximum Average Subarray I 🧠 My Experience Solving These: 🔸 209. Minimum Size Subarray Sum This problem looked complicated at first, but then I realized it can be solved using the two-pointer sliding window. Expand window using right Shrink window using left Update minimum window length whenever sum ≥ target Once I applied this approach, the solution became fully optimized. 🔸 1456. Maximum Number of Vowels in a Substring of Length k This was a clean sliding-window substring problem. First, count vowels in the first window Then slide the window by ✔ adding new char ✔ removing old char Keep track of the maximum vowel count Very efficient and elegant. 🔸 643. Maximum Average Subarray I A straightforward calculation-based problem. First window → compute initial sum Then slide the window and update sum Track maximum sum Return maxSum / k Solved in O(n) with no extra space. 📌 Key Takeaway Today: Sliding Window helps simplify problems that involve continuous subarrays / substrings. ✔ Use two pointers ✔ Expand + shrink window ✔ Update result during each move ✔ Avoid nested loops — O(n) is always better Every day I’m getting better at recognizing patterns and choosing the right technique. On to Day 24! 🚀 #DSA #LeetCode #Java #SlidingWindow #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
Why did Java just skip my input? (The sc.nextLine() Trap) I was building a simple CLI tool today and hit a weird bug. I asked the user for their Age, then their Name. But as soon as I typed the age and hit Enter, the program finished. 𝐈𝐭 𝐝𝐢𝐝𝐧'𝐭 𝐞𝐯𝐞𝐧 𝐰𝐚𝐢𝐭 𝐟𝐨𝐫 𝐦𝐞 𝐭𝐨 𝐭𝐲𝐩𝐞 𝐦𝐲 𝐧𝐚𝐦𝐞! 𝐓𝐡𝐞 𝐌𝐲𝐬𝐭𝐞𝐫𝐲: I was using sc.nextInt() followed by sc.nextLine(). ▶️sc is the Scanner class object. 𝐓𝐡𝐞 𝐒𝐜𝐢𝐞𝐧𝐜𝐞: When you type 25 and hit Enter, nextInt() only reads the 25. It leaves the "𝐄𝐧𝐭𝐞𝐫" (𝐭𝐡𝐞 \𝐧 𝐧𝐞𝐰𝐥𝐢𝐧𝐞 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫) sitting there in the buffer. When the code hits the next nextLine(), it sees that leftover "Enter" and thinks: "Oh, the user just pressed Enter without typing anything!" So it returns an empty string and moves on. 𝐓𝐡𝐞 𝐅𝐢𝐱: We have to "consume" the ghost! I learned you need to call an extra 𝐬𝐜.𝐧𝐞𝐱𝐭𝐋𝐢𝐧𝐞() just to clear that leftover newline before taking the actual input. 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠 𝐢𝐧 𝐏𝐮𝐛𝐥𝐢𝐜: Coming from C++, I'm used to cin.ignore(), but seeing it happen in Java was a great reminder of how input buffers work under the hood. Have you ever been haunted by the nextLine() ghost? How did you first solve it? #Java #CodingBeginner #SoftwareEngineering #Scanner #LearningInPublic
To view or add a comment, sign in
-
-
Snakes & Ladders — Minimum Dice Throws (Board → Graph) 💡 Graph View Each cell = node From cell i → edges to i+1 … i+6 Snake / Ladder = edge jump BFS gives minimum dice throws. --- ✅ Java Code (with example) import java.util.*; public class SnakesAndLaddersExample { static int minDiceThrows(int[] board) { int n = board.length; boolean[] visited = new boolean[n]; Queue<int[]> q = new LinkedList<>(); q.add(new int[]{0, 0}); // {cell, moves} visited[0] = true; while (!q.isEmpty()) { int[] cur = q.remove(); int cell = cur[0], moves = cur[1]; if (cell == n - 1) return moves; for (int dice = 1; dice <= 6 && cell + dice < n; dice++) { int next = cell + dice; if (board[next] != -1) next = board[next]; // jump via snake/ladder if (!visited[next]) { visited[next] = true; q.add(new int[]{next, moves + 1}); } } } return -1; } public static void main(String[] args) { int[] board = new int[30]; Arrays.fill(board, -1); // ladder 2 → 21 board[2] = 21; // snake 26 → 0 board[26] = 0; System.out.println("Minimum Dice Throws = " + minDiceThrows(board)); } } 🧪 Output Minimum Dice Throws = 3 🧠 BFS Meaning Each level = 1 dice roll Shortest path → minimum throws #DSA #DataStructuresAndAlgorithms #Coding #Programmer #LeetCode #CodeEveryday #JavaDSA #CodingPractice #ProblemSolving #CP #CompetitiveProgramming #DailyCoding #TechJourney #CodingCommunity #DeveloperLife #100DaysOfCode #CodeWithMe #LearnToCode #GeekForGeeks #CodingMotivation
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development