🚀 DSA Journey Day 8 — LeetCode :Finding Duplicates in an Array Today’s problem looked simple at first… but the approach made all the difference 👀 🔍 Problem Understanding Given an integer array nums, return all elements that appear exactly twice. ⚡ Brute Force Approach For every element, traverse the entire array Count occurrences Time Complexity: O(n²) ❌ (Not efficient) 🚀 Optimized Approach (Using HashMap) Used a HashMap to store frequency of each element First pass → store counts Second pass → collect elements with frequency = 2 👉 Steps: Traverse the array Store frequency using map.getOrDefault() Iterate over the map If value == 2 → add to result list 🧠 Example Walkthrough Input: [4,3,2,7,8,2,3,1] Map: {1=1, 2=2, 3=2, 4=1, 7=1, 8=1} Output: [2,3] ⏱️ Complexity Analysis Time: O(n) ✅ Space: O(n) 💡 Key Learning Sometimes the problem isn’t hard… choosing the right data structure is what makes it efficient 🔥 ✅ Result ✔️ Accepted (29/29 test cases) ⚡ Runtime: 30 ms 🙏 Staying consistent and improving every day 📌 Consistency beats motivation #DSA #Java #CodingJourney #LeetCode #ProblemSolving #HashMap #100DaysOfCode #PlacementPreparation
Finding Duplicates in Array with HashMap
More Relevant Posts
-
🚀 Day 88 of DSA Problem Solving 💡 Problem Solved: Two Sum II – Input Array Is Sorted 🔍 Problem Idea: Given a sorted array, find two numbers such that they add up to a target. Return their indices (1-based). 🧠 Key Learning: Instead of using HashMap (like in classic Two Sum), we can optimize using the **Two Pointer Approach** because the array is already sorted. ⚡ Concepts Practiced: * Two Pointer Technique * Array Traversal * Greedy Decision Making ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Approach: * Start with two pointers: one at the beginning and one at the end * If sum is too small → move left pointer forward * If sum is too large → move right pointer backward * If sum matches target → return indices 🔥 Real Journey Behind Solution: Initially, I thought of using HashMap (habit from Two Sum 😅), but then realized the sorted property is a huge advantage. Switching mindset to use **two pointers** made the solution cleaner and more optimal. This problem reminded me: 👉 Always look for constraints like “sorted” — they often unlock better solutions. 📌 Takeaway: Smart observation > brute force #Day88 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #TechGrowth #TwoPointers
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 26 Today’s focus: Binary Search fundamentals. Problems solved: • Binary Search (LeetCode 704) • Search a 2D Matrix (LeetCode 74) Concepts used: • Binary Search • Search space reduction • Index mapping in 2D arrays Key takeaway: In Binary Search, the idea is to repeatedly divide the search space in half. By comparing the target with the middle element, we eliminate half of the array each time, achieving O(log n) time complexity. In Search a 2D Matrix, the matrix can be treated as a flattened sorted array. Using index mapping: row = mid / cols col = mid % cols we can apply binary search directly on the matrix without extra space. These problems highlight how binary search is not limited to 1D arrays—it can be extended to structured data with proper transformations. Continuing to strengthen fundamentals and consistency in DSA problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 126/360 🚀 📌 Topic: Array + Backtracking (Recursion) 🧩 Problem: Combination Sum II Problem Statement: Find all unique combinations in an array where numbers sum up to a target. Each number can be used only once, and duplicate combinations are not allowed. 🔍 Example: Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6], [1,2,5], [1,7], [2,6]] 💡 Approach: Backtracking + Pruning 1️⃣ Step 1 – Sort the array to handle duplicates easily 2️⃣ Step 2 – Use recursion to pick elements and reduce target 3️⃣ Step 3 – Skip duplicates & backtrack after each recursive call 👉 Use condition to skip duplicates: if(i > ind && arr[i] == arr[i-1]) continue; 👉 Stop early if element exceeds target (pruning) ⏱ Complexity: Time: O(2^n) Space: O(k * x) (for storing combinations) 📚 Key Learning: Sorting + duplicate skipping is the key trick to avoid repeated combinations in backtracking problems. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode
To view or add a comment, sign in
-
-
Day 1 of becoming DSA consistent (no excuses) Problem name : Minimum Distance Between Three Equal Elements II Difficulty : Medium Topic : Hash Table Most people would brute-force this problem… but there’s a smarter way using grouping. 🧠 Approach : 👉 Instead of comparing all triplets (which is slow), we optimize using a HashMap. Step 1: Store indices Traverse the array For each number, store all its indices in a map number → list of positions Step 2: Filter useful candidates Only consider numbers that appear at least 3 times Others cannot form a valid triplet Step 3: Check consecutive triplets For each list of indices: Pick 3 consecutive indices → (i, i+1, i+2) Since indices are sorted, this ensures minimum distance. Step 4: Compute distance, Distance is calculated between the 3 positions. Simplifies to: 2 × (last index − first index); Step 5: Track minimum. Keep updating the smallest distance found. If no valid triplet → return -1; Key Learning : When dealing with repeated elements: Use HashMap for grouping, Work on indices instead of values, Look for patterns (like consecutive grouping) to reduce complexity. IF YOU GUYS USED DIFFERENT LOGIC , Drop your logic below 👇... #leetcode #dsa #coding #softwareengineering #programming #interviewprep #java #grow #innovation #LetsConnect
To view or add a comment, sign in
-
-
🚀 DSA Preparation 💪 Solved an interesting Array + HashMap problem involving number reversal. Focused on identifying mirror pairs efficiently , minimizing index distance🔥 Great practice for combining hashing with logic building 🚀 🧠 Problem 🔎 Minimum Distance Between Mirror Pairs Given an array nums, a mirror pair is defined as indices (i, j) such that: 👉 i < j 👉 reverse(nums[i]) == nums[j] Return the minimum absolute distance |i - j| among all mirror pairs. 👉 If no such pair exists, return -1. Example Input: nums = [12,21,45,33,54] Output: 1 Input: nums = [120,21] Output: 1 Input: nums = [21,120] Output: -1 ⚡ Key Learning 📌 Use HashMap to store reversed values and their indices 📌 Check for matches while traversing the array 📌 Efficiently minimize distance during traversal 📌 Time Complexity: O(n * d) → n elements, d digits for reversal 📌 Space Complexity: O(n) → storing elements in map Improving DSA with smart hashing techniques 🚀 #DSA #LeetCode #HashMap #Arrays #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 19 of Consistency – Optimized “Intersection of Two Arrays II” (LeetCode) Today I pushed one step further and solved a variation where duplicates also matter — making it slightly more challenging and interesting. 🔍 Problem Understanding Given two arrays, return their intersection including duplicates. Each element should appear as many times as it shows in both arrays. 🧠 Initial Thought (Brute Force) Compare each element of one array with another Track used elements manually ⛔ Inefficient due to nested loops → O(n × m) ⚡ Optimized Approach (HashMap – Frequency Count) 👉 This time, I used a smarter strategy: Store frequency of elements from nums1 in a HashMap Traverse nums2 If element exists in map and count > 0: Add to result Decrease frequency 💡 Example nums1 = [1,2,2,1] nums2 = [2,2] Output → [2,2] ⏱ Complexity Analysis Time Complexity: O(n + m) Space Complexity: O(n) 📊 Result ✔️ All test cases passed (61/61) ⚡ Runtime: 3 ms 🔥 Beats 95.42% submissions 🧩 Key Learning HashMap is extremely useful for frequency-based problems Handling duplicates = tracking counts properly Small optimization can drastically improve performance 🙏 Grateful for the journey and learning every single day 🔥 Consistency + Optimization = Growth mindset #DSA #Java #LeetCode #CodingJourney #HashMap #ProblemSolving #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🧠 LeetCode POTD — The Bug Wasn’t Logic… It Was Leading Zeros 3761. Minimum Absolute Distance Between Mirror Pairs At first glance, this problem looked simple. Find two indices (i, j) such that: 👉 reverse(nums[i]) == nums[j] and return the minimum distance. My first instinct was straightforward: 👉 Store all numbers in a map 👉 Reverse the current number 👉 Check if it already exists Simple enough. 💥 But then one small edge case caused issues: Leading zeros Example: 120 → 21 Not 021 So if you think in strings, it’s easy to make mistakes. 💡 The cleaner approach: Instead of storing original numbers first, 👉 Reverse each number mathematically 👉 Store the reversed value with its latest index 👉 If current number already exists in map, we found a mirror pair Why this works: If we process: 120 We store: 21 Later when 21 appears, we instantly know it matches. 📌 Best part: Mathematical reversal automatically handles leading zeros. 120 → 21 300 → 3 101 → 101 No extra checks needed. 💡 What I liked about this problem: The challenge wasn’t data structures. It was noticing that a small representation detail changes the whole solution. Sometimes bugs are not in algorithms. They’re hidden inside edge cases. Curious — did anyone else first think of using strings here? 👀 #LeetCode #ProblemSolving #HashMap #SoftwareEngineering #DSA #SDE #Java #C++
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 35 Today’s focus: Binary Search with index patterns. Problem solved: • Single Element in a Sorted Array (LeetCode 540) Concepts used: • Binary Search • Index parity (even/odd pattern) • Search space reduction Key takeaway: The array is sorted and every element appears twice except one. A key observation: Before the single element, pairs start at even indices After the single element, this pattern breaks. Using binary search: • If mid is even and nums[mid] == nums[mid + 1], the single element lies on the right side • Else, it lies on the left side (including mid) By leveraging this pattern, we can find the answer in O(log n) time and O(1) space. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 125/360 🚀 📌 Topic: Recursion 🧩 Problem: Combination Sum Problem Statement: Given an array of distinct integers and a target, return all unique combinations where numbers sum up to the target. Same element can be used multiple times. 🔍 Example: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] 💡 Approach: Backtracking 1️⃣ Step 1 – Start from index 0 and try picking each element 2️⃣ Step 2 – If element ≤ target, include it and reduce target 3️⃣ Step 3 – Backtrack (remove element) and move to next index ✔ Use recursion to explore all possibilities ✔ Reuse same element (stay on same index) ✔ Stop when target becomes 0 (valid answer) ✔ Skip when index reaches end ⏱ Complexity: Time: O(2^n * k) (k = avg length of combination) Space: O(k * x) (x = number of combinations) 📚 Key Learning: Backtracking is all about making choices, exploring, and undoing them efficiently. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode #Backtracking 🚀
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