šĀ #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
Kth Largest Element in a Stream with Min Heap
More Relevant Posts
-
š 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
-
-
š Day 571 of #750DaysOfCode š š Problem Solved: Sum of Distances Todayās problem looked like a classic brute-force trap š At first glance, comparing every pair gives an O(n²) solution ā but with constraints up to 10āµ, thatās not going to work. š” Key Insight: Instead of comparing all pairs, we can: š Group indices of the same value š Use prefix sums to efficiently calculate distances š§ Approach: Group indices by value (using HashMap) For each group: Build prefix sum of indices For each index: Left contribution ā i * count - sum Right contribution ā sum - i * count Combine both to get final result š Complexity: Time: O(n) Space: O(n) ⨠Takeaway: When you see distance-based problems: š Think in terms of contributions instead of pair comparisons š Prefix sums can turn expensive computations into linear time Another strong pattern added to the toolkit šŖ #LeetCode #DSA #Java #CodingJourney #ProblemSolving #PrefixSum #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
š Day 4 of My LeetCode Journey Solved todayās POTD (Problem of The Day): Closest Equal Element Queries (Medium) š Problem Summary Given a circular array, for each query index, find the minimum distance to another index having the same value. If no such index exists, return -1. š§ Intuition Instead of checking every index for each query (brute force), I realized we only need to focus on positions where the same value occurs. š” Approach āļø Used a HashMap to store: value ā list of indices āļø For each query: Found the index position using binary search Checked only left and right neighbors (closest possible matches) āļø Calculated distance using circular logic: min(|i - j|, n - |i - j|) š Key Learning Smart preprocessing can reduce time complexity significantly In circular arrays, always consider wrap-around distance Nearest element problems often reduce to adjacent comparisons #LeetCode #Day4 #DSA #ProblemOfTheDay #Java #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
-
š 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
-
-
š LeetCode Challenge 30/50 š” Approach: HashSet (Sequence Start Detection) Sorting would give O(n log n) ā but the problem demands O(n)! The trick? Use a HashSet and only start counting from the BEGINNING of each sequence! š Key Insight: ā Add all numbers to a HashSet (O(1) lookup) ā For each number, check if (num - 1) exists in set ā If NOT ā it's the start of a new sequence! ā Count upward (num+1, num+2...) while consecutive numbers exist ā Update maxLength at each sequence end š Complexity: ā Sorting approach ā O(n log n) Time ā HashSet approach ā O(n) Time, O(n) Space Each number is visited at most twice across all sequences! š Day 30/50 ā 60% done and still going strong! The best optimizations come from asking: āWhat information can I precompute?ā A HashSet turned O(n log n) into O(n)! š„ #LeetCode #DSA #HashSet #Java #ADA #PBL2 #LeetCodeChallenge #Day30of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #LongestConsecutiveSequence
To view or add a comment, sign in
-
-
Day 19 of #100DaysOfCode Solved āBase 7ā problem today ā a simple yet insightful exercise on number systems. š” Approach: Convert the integer into base 7 by repeatedly dividing by 7 and storing remainders. Handle negative numbers separately and reverse the result at the end. ā” Key Learning: Even easy problems strengthen fundamentals like loops, math logic, and edge case handling. Consistency > Complexity. #LeetCode #DSA #CodingJourney #Java #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
š Day 16 of LeetCode Problem Solving Solved todayās problem ā LeetCode #26: Remove Duplicates from Sorted Array š»š„ ā Approach: Two Pointers ā” Time Complexity: O(n) š Space Complexity: O(1) The task was to remove duplicates in-place from a sorted array and return the count of unique elements. š I used the Two Pointer technique: One pointer to track unique elements Another to traverse the array š” Key Idea: Since the array is sorted, duplicates will be adjacent ā making it easier to skip them. š Core Logic: Compare nums[i] with nums[j] If different ā move pointer and update value Maintain unique elements at the beginning š” Key Learning: Two Pointer is a very powerful technique for array problems ā especially when data is sorted. Consistency is the key ā getting better every day š #Day16 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #100DaysOfCode
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 47of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Mirror Distance of an Integer Problem Insight: Given a number, the task is to find the absolute difference between the original number and its reversed form. Approach: ⢠Stored the original number in a temporary variable ⢠Reversed the number using digit extraction (modulo and division) ⢠Calculated the absolute difference between the original and reversed number Time Complexity: O(d), where d = number of digits Space Complexity: O(1) Key Learnings: ⢠Digit manipulation using modulo and division is a powerful technique ⢠Always store the original value before modifying the input ⢠Reversing numbers is a fundamental pattern in many DSA problems Takeaway: Breaking the problem into simple steps makes even tricky-looking logic easy to solve. #DSA #Java #LeetCode #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
ā LeetCode Top Interview 150 ā Day 100 šÆ Today I solved Course Schedule II Key Idea : Use Topological Sort (BFS - Kahnās Algorithm) Build graph and track indegree of each node Add nodes with indegree 0 to queue Process nodes and reduce indegree of neighbors If all courses are processed ā valid order exists Else ā cycle detected (not possible) This approach helps find a valid course order efficiently #DSA #Java #Leetcode #Day100
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