🎉 Day 400 of #500DaysOfCode 🎉 Today I tackled an interesting problem from LeetCode — “703. Kth Largest Element in a Stream”. The task: Build a class that maintains a stream of scores (or numbers) and, for a given integer k, always returns the kth largest element after each insertion. Why this is cool: Real-world analogy: Think of a university admissions office tracking the kth highest test score dynamically as new applicants submit scores. Efficient solution involves a min-heap (priority queue) of size k — keep only the top k largest elements; the root is then the kth largest overall. Good practice for streaming data, heaps, and understanding dynamic order statistics. 🔧 My Java solution uses PriorityQueue<Integer>: Initialize with k and the initial array of scores. On each .add(val) call: insert value, if heap size > k then remove the smallest, then peek to get the kth largest. Time complexity: O(log k) per addition. Space: O(k). ✅ Key takeaways: Using a min-heap of fixed size is a neat way to get the kth largest in a stream. Make sure to prune the heap so it never grows beyond k. Good addition to my toolkit for streaming / dynamic order problem types. What’s next: On to Day 401 — I’ll be diving into [insert upcoming topic or type: e.g., “graph algorithms”, “dynamic programming advanced”, “system design mini challenge”]. #500DaysOfCode #CodingChallenge #LeetCode #Java #DataStructures #Algorithms #Heap #PriorityQueue #ProblemSolving #DeveloperJourney
Solved LeetCode 703 with Java PriorityQueue for kth largest element
More Relevant Posts
-
💻 Day 71 of #LeetCode100DaysChallenge Solved LeetCode 50: Pow(x, n) — a classic math-based problem that enhances recursion, divide and conquer, and optimization thinking. 🧩 Problem: Implement a function to calculate xⁿ (x raised to the power n). Handle both positive and negative exponents efficiently without using built-in library functions. 💡 Approach — Fast Exponentiation (Binary Exponentiation): 1️⃣ If n is 0 → return 1 (base case). 2️⃣ If n is negative → compute 1 / pow(x, -n). 3️⃣ For even n, compute pow(x * x, n / 2). 4️⃣ For odd n, multiply once more by x. 5️⃣ This recursive or iterative approach reduces repeated multiplications. ⚙️ Complexity: Time: O(log N) — each step halves the exponent. Space: O(1) (iterative) or O(log N) (recursive). ✨ Key Takeaways: ✅ Strengthened understanding of binary exponentiation and recursion optimization. ✅ Learned how to handle negative powers and edge cases gracefully. ✅ Practiced a pattern used widely in modular arithmetic and scientific computing. #LeetCode #100DaysOfCode #Java #Math #Recursion #BinaryExponentiation #Optimization #ProblemSolving #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
🚀 Day 49 of #100DaysOfCode — Leetcode + HackerRank Edition! Today’s challenge was a deep dive into efficient math logic — computing powers with binary magic ⚡🧠 🧩 myPow(x: float, n: int) -> float — Calculate x^n using fast exponentiation 📌 Challenge: → Implement a function that computes x^n → Handle negative exponents gracefully → Optimize for large n without brute force 🔍 Approach: → Use binary exponentiation to reduce time complexity from O(n) to O(log n) → Check each bit of n using n & 1 to decide whether to multiply → Square x and shift n right (n >>= 1) to walk through its binary form → Handle negative n by flipping x to 1/x and making n positive 💡 What made it click: → Realized that n & 1 checks the least significant bit — perfect for bitwise logic → Saw how x *= x builds powers of 2: x^1,x^2,x^4,x^8... → Practiced dry runs with x = 2, n = 13 → binary 1101 📚 What I learned: ✅ How bitwise operations can replace loops for power calculations ✅ Why binary exponentiation is a game-changer for performance ✅ How to handle negative powers cleanly Ever implemented exponentiation without using ** or pow()? Let’s swap bit tricks, dry runs, and math optimizations 💬 #Day49 #Leetcode #Python #BinaryExponentiation #BitwiseMagic #DryRun #LearnInPublic #CodeNewbie #TechJourney #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
🧮 Day 27 – 90 Days of Code Problem: Count Operations to Obtain Zero 🧠 Intuition This problem is conceptually similar to the Euclidean Algorithm for finding the GCD. At each step, we repeatedly subtract the smaller number from the larger one until one becomes zero. Instead of doing subtraction one by one, we can optimize using integer division — num1 / num2 tells us how many subtractions can be done in one go. So effectively, we’re simulating the Euclidean process while counting how many subtraction steps occur in total. ⚙️ Approach Initialize a counter count = 0. While both numbers are positive: Add num1 / num2 to the counter (number of subtractions possible in this step). Update num1 = num1 % num2 (reduce the larger number). Swap num1 and num2 to continue with the next iteration. Once either number becomes 0, stop and return the count. ⏱️ Complexity Time Complexity: O(log(min(num1, num2))) — similar to the Euclidean algorithm. Space Complexity: O(1) 💡 Key Learning Optimized repetitive subtraction problems using division-based reasoning — an elegant example of mathematical insight improving algorithmic efficiency. 🔖 Tags #Day27Of90 #90DaysOfCode #LeetCode #LeetCodeDaily #DSA #Maths #EuclideanAlgorithm #ProblemSolving #CodingJourney #KeepLearning #ConsistencyIsKey #Java #Programming
To view or add a comment, sign in
-
-
Title: From "What" to "How": Implementing My First Algorithm Hey LinkedIn fam! 👋 Today, my journey was all about understanding what an array is: a contiguous block of memory for storing elements of the same type. I took the logical next step: learning how to do something useful with it. My focus was on my very first searching algorithm: Linear Search. The task is simple, just like finding a specific dish on a menu: "Find the index of an element in a given array." The logic is exactly what you'd do in real life: Start at the beginning (index 0). Check each element, one by one. If you find what you're looking for (the key), you immediately stop and return its index. But the real "aha!" coding moment for me was handling the "Not Found" case. You can't just return 0, because 0 is a valid index! The elegant solution is to return a sentinel value—a number that's outside the possible range of indices. In this case: -1. Then, in the main code, you just check: if (index == -1) { ... print "Not Found" } It's so cool to see the theory (the diagram) and the practical, clean code come together. It feels great to connect these fundamental building blocks. One step at a time! What was the first algorithm you remember learning after arrays? #Java #Algorithms #LinearSearch #DataStructures #CodingJourney #LearnInPublic #SoftwareDevelopment #ProgrammingFundamentals
To view or add a comment, sign in
-
-
🔥 Day 113 of My DSA Challenge – Word Search 🔷 Problem : 79. Word Search 🔷 Goal : Check if a given word exists in a 2D grid by connecting sequentially adjacent letters (horizontally or vertically). Same cell cannot be used more than once. 🔷 Key Insight : This is a DFS + backtracking problem. Start from every cell matching the first character. Explore all 4 directions recursively. Track visited cells to avoid reusing letters. Backtrack when a path fails. This teaches how to explore grids efficiently using recursion and state tracking. 🔷 Approach : 1️⃣ Iterate over all cells to find starting points 2️⃣ DFS recursively for adjacent letters 3️⃣ Use a visited matrix to avoid reusing cells 4️⃣ Backtrack if the path does not lead to the word Time Complexity: O(m × n × 4^k) where k = length of word Space Complexity: O(m × n) for visited + recursion stack Word Search reinforces grid DFS + backtracking patterns. Explore all possibilities, track state carefully, backtrack on failure. This pattern is useful for : ✅ Maze solving ✅ Island counting problems ✅ Pathfinding & puzzle problems Every day, a new pattern becomes familiar. Step by step, the mind gets sharper. 🚀 #Day113 #DSA #100DaysOfCode #DFS #Backtracking #LeetCode #ProblemSolving #Java #CodingChallenge #Algorithms #DataStructures #DeveloperJourney
To view or add a comment, sign in
-
-
✨ Day 101 of My DSA Challenge – Magnetic Force Between Two Balls 🔷 Problem: 1552. Magnetic Force Between Two Balls 🔷 Goal: Place m balls into sorted basket positions such that the minimum magnetic force (i.e., minimum distance between any two balls) is as large as possible. 🔷 Key Insight: This is another brilliant Binary Search on the Answer problem. Instead of directly computing distances, we binary search for the maximum possible minimum distance that still allows placing all balls. Here’s how the logic works: 1️⃣ Sort all basket positions. 2️⃣ Use binary search on the range of possible distances (0 to max(position) - min(position)). 3️⃣ For each middle distance mid, check feasibility using a greedy approach — place balls while maintaining at least mid distance apart. 4️⃣ If it’s possible → try a larger distance. If not → reduce the distance. 🔷 My Java Approach: Implemented a helper function isPossible() to check if we can place all balls for a given minimum distance. Used Binary Search to maximize that minimum distance. 🔷 Complexity: Time → O(n × log(maxDist)) Space → O(1) This problem beautifully blends sorting, binary search, and greedy placement — showing how abstract concepts like “searching on the answer” translate into real algorithmic reasoning. Every new day strengthens my foundation in Binary Search patterns, sharpening both logic and implementation clarity. 🚀 #Day101 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #BinarySearch #GreedyAlgorithm #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #LearnToCode #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 2654. 𝐌𝐢𝐧𝐢𝐦𝐮𝐦 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐎𝐩𝐞𝐫𝐚𝐭𝐢𝐨𝐧𝐬 𝐭𝐨 𝐌𝐚𝐤𝐞 𝐀𝐥𝐥 𝐀𝐫𝐫𝐚𝐲 𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐬 𝐄𝐪𝐮𝐚𝐥 𝐭𝐨 1. This problem was an excellent application of mathematical reasoning through the Euclidean Algorithm (GCD). It helped me appreciate how fundamental math concepts can simplify complex algorithmic logic and lead to optimized solutions. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given an array of positive integers. In one operation, we can select an index i and replace either nums[i] or nums[i+1] with their GCD value. The task is to find the minimum number of operations required to make all elements equal to 1, or return -1 if it is impossible. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Checked if the array already contains any element equal to 1. If yes, the minimum operations equal the number of elements that are not 1. If not, used a nested loop to find the shortest subarray whose GCD becomes 1 using the Euclidean Algorithm. Once such a subarray is found, it can be made 1 in (subarray length - 1) operations. The total number of operations is calculated as (subarray length - 1) + (n - 1), representing the steps to convert the rest of the array to 1. Added an early break once GCD reaches 1 for better performance. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n² * log(max(nums))) Space Complexity: O(1) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Reinforced the use of the Euclidean Algorithm and recursion for GCD calculations. Understood the role of early exits in improving nested loop efficiency. Observed how mathematical insight directly enhances algorithmic problem-solving. This marks my first post in my LeetCode Daily Challenge journey. I plan to continue sharing my learnings and reasoning from each daily challenge to stay consistent and deepen my problem-solving approach. #LeetCode #DSA #Java #ProblemSolving #CodingPractice #LearningEveryday #Consistency #Algorithms #100DaysOfCode
To view or add a comment, sign in
-
-
💻 Day 54 of #LeetCode100DaysChallenge Solved LeetCode 202: Happy Number — a problem that beautifully combines mathematics and cycle detection concepts. 🧩 Problem: Determine if a number is a “happy number.” A number is happy if repeatedly replacing it with the sum of the squares of its digits eventually equals 1. If the process loops endlessly (without reaching 1), it’s not a happy number. Example: 19 → 1² + 9² = 82 82 → 8² + 2² = 68 68 → 6² + 8² = 100 100 → 1² + 0² + 0² = 1 ✅ (Happy Number) 💡 Approach — Floyd’s Cycle Detection: 1️⃣ Define a helper function to compute the sum of squares of digits. 2️⃣ Use two pointers (slow and fast): slow moves one step (sum of squares once). fast moves two steps (sum of squares twice). 3️⃣ If they meet at 1 → happy number. 4️⃣ If they meet at another number → cycle detected → not happy. ⚙️ Complexity: Time: O(log N) — each iteration reduces digits. Space: O(1) — constant extra space. ✨ Key Takeaways: ✅ Strengthened understanding of Floyd’s cycle detection beyond linked lists. ✅ Gained insight into mathematical pattern-based problems. ✅ Practiced writing clean helper functions for iterative digit operations. #LeetCode #100DaysOfCode #Java #Math #CycleDetection #Hashing #DSA #CodingJourney #WomenInTech #HappyNumber
To view or add a comment, sign in
-
-
🌸 Day 58 of #100DaysOfCode 🌸 💡 Problem: Alice and Bob Playing Flower Game ✨ Approach: Used a mathematical logic approach instead of simulation — counting even–odd combinations between Alice and Bob’s flowers 🌼 If one has an even number and the other an odd, the total number of valid pairs determines the winning outcomes. No loops. No extra space. Just pure math elegance! 🧮 ⚡ Complexity Analysis: Time Complexity: O(1) → direct formula-based computation Space Complexity: O(1) → constant space 📊 Performance: ✅ Runtime: 0 ms (Beats 💯%) ✅ Memory: 40.48 MB (Beats 93.79%) 🔑 Key Insight: Sometimes the smartest solutions don’t need iterations — just mathematical reasoning. Optimizing logic can turn complex problems into one-liners! ⚙️💫 #100DaysOfCode #LeetCode #Java #DSA #ProblemSolving #MathLogic #CodingChallenge #Algorithm #CodeOptimization #ProgrammingJourney
To view or add a comment, sign in
-
-
🌟 Day 24 of #100DaysOfCode. Today I come with one challenging problem which is related to the topic Binary Search. 🌟 ✔️ What I solved: *️⃣ Problem of the Day: Binary Search ✴️ Approach & Key Insights: 🔹 Binary Search divides the array into halves to efficiently search for a target in O(log n) time. 🔹 The sorted property is crucial — binary search only works on sorted arrays. ◾ Steps: 🔹 Initialize two pointers, left at the start and right at the end of the array. While left <= right: 🔹 Compute the middle index mid = left + (right - left) // 2. 🔹 If nums[mid] is the target, return mid. 🔹If nums[mid] < target, search right half (left = mid + 1). 🔹If nums [mid] > target, search left half (right = mid - 1). 🔹If you exit the loop, target is not present. Return -1. ✴️ Complexity: 🔹 Time Complexity: O(logn) 🔹 Space Complexity: O(1) ✴️ Key Takeaways: 🔹 Use binary search for efficient lookups in sorted arrays. Always check for overflow when computing mid: mid = left + (right - left) / 2. 🔹 The standard approach is iterative for minimal space, but recursive solutions work as well. 🚀For more information, Click here ⬇️ https://lnkd.in/gaQTpVtk 🪄 I am very thankful to my Mentor Mr.Rajesh Gupta Sir and KR Mangalam University for giving me the support throughout this week. #DSA #100DaysOfCode #KRMU #Competitive #Coding
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
“Legends aren’t born, they’re built — and you’re proof! 🏆” Abhijeet Sinha