🚀 #100DaysOfCode – Day 19 Today’s challenge: Kth Distinct String in an Array 🔤 You’re given an array of strings and an integer k. Your task is to return the kth distinct string — a string that appears exactly once, while also respecting the original order. 🔴 Brute Force Approach For every string, count its occurrences by scanning the entire array Track distinct elements in order ⛔ Time Complexity: O(n²) 👉 Repeated counting makes it inefficient 🟢 Optimized Approach (HashMap + Order Preservation) 💡 Idea: First, count frequency of each string using a HashMap Then, iterate again to maintain original order Decrease k when a distinct string is found ✅ Code: class Solution { public String kthDistinct(String[] arr, int k) { Map<String, Integer> mp = new HashMap<>(); // Count frequency for (var s : arr) { mp.put(s, mp.getOrDefault(s, 0) + 1); } // Find kth distinct for (var s : arr) { if (mp.get(s) == 1) { k--; } if (k == 0) { return s; } } return ""; } } 🧠 Key Insight 👉 Use HashMap for frequency counting 👉 Use array traversal to preserve order This combination ensures: Efficient lookup Correct ordering ⚡ Complexity Time: O(n) Space: O(n) 🔍 Example arr = ["a","b","a","c","d","c"], k = 2 Distinct elements → ["b", "d"] 👉 Output = "d" 💡 Learning of the Day Efficiency is not just about speed — it’s about combining the right data structures with the right traversal strategy. #Day19 #100DaysOfCode #DSA #Java #HashMap #CodingJourney #LeetCode #ProblemSolving
Kth Distinct String in Array with HashMap and Order Preservation
More Relevant Posts
-
🚀 Day 38 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Maximum Product of Two Elements in an Array. Problem Insight: Given an integer array, the goal is to find two elements such that: (nums[i] - 1) * (nums[j] - 1) is maximized Approach: • First, sort the array using Arrays.sort() • Use two nested loops to check all possible pairs • For each pair, calculate → (nums[i] - 1) * (nums[j] - 1) • Keep track of the maximum product Time Complexity: • O(n²) — due to nested loops Space Complexity: • O(1) — no extra space used Key Learnings: • Understanding operator precedence is very important in expressions • Sorting helps in simplifying many problems • Even simple problems can have optimized solutions beyond brute force Takeaway: Brute force helps in understanding the problem deeply, but optimization (like using the two largest elements directly) makes the solution efficient 🚀 #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving #Arrays
To view or add a comment, sign in
-
-
🚀 Day 43 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Sum of Unique Elements Problem Insight: Find elements in an array that appear exactly once and calculate their total sum. Approach: • Used a frequency array to count occurrences of each number • Traversed the array to build frequency • Added only those elements to sum whose frequency is exactly 1 Time Complexity: • O(n) Space Complexity: • O(1) (fixed size array used for constraints) Key Learnings: • Frequency array is faster than HashMap when range is fixed • Two-pass approach makes logic clear and simple • Always check constraints before choosing data structure Takeaway: Right data structure makes the solution simple and efficient 🚀 #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 49 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Set Mismatch Problem Insight: Given an array containing numbers from 1 to n, one number is duplicated and one number is missing. The goal is to find both of them. Approach: • Used a frequency array to count occurrences of each number • Traversed the input array and updated frequency • Iterated from 1 to n: – If frequency is 2 → duplicate element – If frequency is 0 → missing element • Returned both values as the final result Time Complexity: O(n) Space Complexity: O(n) Key Learnings: • Frequency array is a simple and powerful technique for counting problems • Helps quickly identify missing and repeating elements • Clean and easy-to-understand approach for beginners Takeaway: Sometimes the simplest approach is the most effective. Mastering basic patterns like counting can solve many problems efficiently! #DSA #Java #LeetCode #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 18 Today’s problem: Kth Largest Element in a Stream 📊 We need to continuously track the kth largest element as new numbers keep coming in. 🔴 Brute Force Approach Store all elements in a list Sort the list every time a new element is added Return the kth largest ⛔ Time Complexity: O(n log n) per insertion 👉 Not efficient for continuous streams 🟢 Optimized Approach (Min Heap) Use a Min Heap of size k 💡 Idea: Keep only the k largest elements in the heap The top (peek) will always be the kth largest ✅ Code: class KthLargest { PriorityQueue<Integer> pq = new PriorityQueue<>(); private int k; public KthLargest(int k, int[] nums) { this.k = k; pq = new PriorityQueue<>(k); for (int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } 🧠 Key Insight 👉 Instead of storing all elements, just maintain the top k largest elements If heap size > k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(log k) per insertion Space: O(k) 🔍 Example k = 3 Stream: [4, 5, 8, 2] After processing → Heap = [4,5,8] Add(3) → [4,5,8] Add(10) → [5,8,10] 👉 kth largest always at the top of heap 💡 Learning of the Day When dealing with continuous data streams, don’t store everything — store only what matters. #Day18 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode
To view or add a comment, sign in
-
🚀 Day 39 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Concatenation of Array Problem Insight: Given an integer array nums, the goal is to create a new array by concatenating the array with itself. Approach: • Created a new array of size 2 * nums.length • Used a single loop to iterate through the array • Stored elements at two positions: - result[i] = nums[i] - result[i + nums.length] = nums[i] • This avoids using extra loops and keeps the solution efficient Time Complexity: • O(n) — only one traversal required Space Complexity: • O(n) — new array is created Key Learnings: • Efficient index handling can simplify problems • Avoid unnecessary loops for better performance • Strong fundamentals make simple problems powerful Takeaway: Smart thinking beats brute force — even simple problems can be solved in an optimal and elegant way . #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving #Arrays
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 20 Today’s problem: Kth Largest Element in an Array 📊 Given an integer array nums and an integer k, return the kth largest element in the array (not necessarily distinct). 🔴 Brute Force Approach Sort the array in descending order Return the element at index k-1 ⛔ Time Complexity: O(n log n) 👉 Sorting the entire array is unnecessary when we only need one element 🟢 Optimized Approach (Min Heap) 💡 Idea: Use a Min Heap of size k Keep only the k largest elements The top of the heap will always be the kth largest ✅ Code: class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } } 🧠 Key Insight 👉 Instead of sorting everything, maintain only the k largest elements If heap size exceeds k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(n log k) Space: O(k) 🔍 Example nums = [3,2,1,5,6,4], k = 2 Step-by-step heap: Add → maintain size k 👉 Final heap → [5,6] 👉 Answer = 5 💡 Learning of the Day When solving problems: 👉 Don’t process everything — process only what’s required #Day20 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode #ProblemSolving
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
-
#Day53 of #100DaysDSAChallenge 🚀 Solved #LeetCode328: Odd Even Linked List The problem asks us to rearrange the nodes of a singly linked list such that all odd indexed nodes come first, followed by even indexed nodes, while preserving their relative order. 🔹 Approach: Brute Force Approach First traverse the linked list and store odd and even indexed values separately using an ArrayList. Then rewrite these values back into the linked list in required order. Time Complexity: O(n) Space Complexity: O(n) 🔹 Optimal Approach (Two Pointer Technique) Use two pointers: odd and even. Keep track of the head of even list (evenHead). Traverse the list and rearrange the next pointers such that: odd nodes are linked together even nodes are linked together Finally, connect the odd list with evenHead. Time Complexity: O(n) Space Complexity: O(1) 💡 Key Learning Instead of modifying values, focus on re-linking nodes for better space optimization. 🧠 Example Input: 1 → 2 → 3 → 4 → 5 Output: 1 → 3 → 5 → 2 → 4 Github repo: https://lnkd.in/g_rSFCh8 #100DaysOfDSA #DSA #LeetCode #Java #Algorithms #DataStructures #KunalKushwaha #Striver #GeeksForGeeks #ProblemSolving #CodingJourney #LearningInPublic #InterviewPrep #PlacementPreparation 🚀
To view or add a comment, sign in
-
-
🚀 Day 21/100 – DSA Challenge Today’s problem: Daily Temperatures 🌡️ The task is to find how many days you have to wait for a warmer temperature. If no such day exists, return 0. 🔴 Brute Force Approach (O(n²)) 👉 For each day, check all future days until you find a warmer temperature. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { result[i] = j - i; break; } } } return result; } } 🟢 Optimized Approach: Monotonic Stack (O(n)) 👉 Instead of checking every future day, use a stack to store indices and resolve them when a warmer day appears. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && temperatures[i] > temperatures[st.peek()]) { int prevPos = st.pop(); result[prevPos] = i - prevPos; } st.push(i); } return result; } } ⚡ Complexity Comparison: Brute Force → O(n²) Optimized (Stack) → O(n) 🎯 Key Learning: Whenever you see “next greater element” type problems, think monotonic stack 🔥 📈 Day 21 done—consistency is the real win! #100DaysOfCode #DSA #Java #CodingChallenge #LearningJourney
To view or add a comment, sign in
-
🚀 Day 15 of LeetCode Problem Solving Solved today’s problem — LeetCode #49: Group Anagrams 💻🔥 ✅ Approach: HashMap + Sorting ⚡ Time Complexity: O(n * k log k) 📊 Space Complexity: O(n * k) The task was to group strings that are anagrams of each other. 👉 I used a HashMap where: Key = sorted version of string Value = list of anagrams 💡 Key Idea: If two strings are anagrams, their sorted form will be the same. 👉 Core Logic: Convert string → char array Sort the array Use sorted string as key Store original string in map 💡 Key Learning: Transforming data (like sorting strings) can help in identifying patterns and grouping efficiently. Consistency is the key — learning something new every day 🚀 #Day15 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
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