🚀 #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
Kth Largest Element in Array with Min Heap
More Relevant Posts
-
🚀 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 70/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Reverse Linked List II A neat variation of linked list reversal where only a specific portion of the list is reversed. Problem idea: Reverse a linked list from position left to right, keeping the rest of the list unchanged. Key idea: In-place reversal using pointer manipulation. Why? • We don’t reverse the whole list, only a segment • Need to reconnect the reversed part correctly • Must carefully track boundaries (left and right) How it works: • Use a dummy node to handle edge cases • Move a pointer to the node just before left • Start reversing nodes one by one within the range • Adjust links to insert nodes at the front of the sublist • Reconnect the reversed portion with remaining list Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Partial reversal in linked lists requires precise pointer updates, not extra space. This builds strong intuition for advanced linked list problems. 🔥 Day 70 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #LinkedList #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 #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
To view or add a comment, sign in
-
Problem :- Plus One (LeetCode 66) Problem Statement :- You are given a large integer represented as an integer array digits, where each digits[i] is a digit of the integer. The digits are ordered from most significant to least significant. Increment the integer by one and return the resulting array of digits. Approach :- Carry Handling i - Traverse from the last digit ii - If digit < 9 → increment and return iii - If digit == 9 → make it 0 and carry forward iv - If all digits are 9 → create new array v - Time Complexity : O(n) vi - Space Complexity : O(1) class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[n + 1]; result[0] = 1; return result; } } How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #Arrays
To view or add a comment, sign in
-
-
🚀 Day 75 of 365 – Triangular Sum of an Array 🔺 One of those problems that looks harmless… until it quietly tests your fundamentals. My approach? Recursive reduction. Keep building the next array using adjacent sums until only one element remains. [1,2,3,4,5] [3,5,7,9] [8,2,6] [0,8] [8] ⚠️ Where I went wrong I initially messed up the base case and recursion flow. Returned from the wrong place Tried accessing values that didn’t exist Didn’t fully trust the recursion chain Classic case of: “Logic sahi tha, execution hil gaya.” ✅ Fix Correct base case → when size == 1, return it Build next array properly Pass result through recursion cleanly That’s it. No overthinking. 💡 What I learned Recursion is simple… until you break the base case Most bugs are not in logic, but in boundaries Clean recursion = clean thinking Day 75 done ✅ Still showing up. Still sharpening. #Day75 #365DaysOfDSAChallenge #LeetCode #DSA #Java #CodingJourney
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 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
-
Day 50 of My DSA Journey Today I reached a major milestone—Day 50! To celebrate, I tackled "Design Linked List" on LeetCode using Java. This was a great exercise in understanding the fundamental mechanics of data structures. Problem Summary The task is to manually implement a Singly or Doubly Linked List from scratch. This includes creating functions to: Get the value of a node at a specific index. Add a node at the head and tail. Add a node before a specific index. Delete a node at a specific index. 🛠️ My Approach I chose to implement a Singly Linked List using a Sentinel (Dummy) Node. Sentinel Node: Used a dummy head to simplify edge cases (like adding or deleting at the very beginning of the list). Pointer Management: Carefully tracked the next references to ensure the chain remains intact during insertions and deletions. Size Tracking: Maintained a size variable to perform quick bounds checking for index-based operations. Complexity Analysis Time Complexity: * $O(1)$ for addAtHead. $O(n)$ for get, addAtIndex, and deleteAtIndex (where $n$ is the length of the list). Space Complexity: $O(n)$ to store the $n$ nodes of the linked list. Result Accepted! Successfully handled the zero-indexing and edge cases for an efficient implementation. Key Learning Manual Memory Logic: Implementing your own data structure builds a much deeper intuition than just using ArrayList. Sentinel Power: Using a dummy node is a "pro-tip" that eliminates many if (head == null) checks, making the code much cleaner and less error-prone. Index Precision: Off-by-one errors are the biggest challenge in Linked Lists; tracing the "previous" node is the key to success. #DSA #LeetCode #Java #DataStructures #CodingJourney #100DaysOfCode #Day50
To view or add a comment, sign in
-
-
🚀 Day 44 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Find the Least Frequent Digit Problem Insight: Find the digit (0–9) that appears the least number of times in a given number. Approach: • Used a frequency array of size 10 to store digit counts • Extracted digits using modulo and division • Traversed the frequency array to find the minimum occurring digit • Returned the smallest digit in case of tie Time Complexity: • O(n) Space Complexity: • O(1) (fixed size array of 10) Key Learnings: • Arrays are more efficient than HashMap when range is limited • Digit extraction using % 10 is very useful in number problems • Keeping track of minimum efficiently avoids extra passes Takeaway: Simple logic + right data structure = clean and optimal solution #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving
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
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