"Oh, Kth Largest Element... Easy!" My first, naive attempt: Make a list. Add the new number. Sort the entire list. Return the k-th element. ...aaaand [Time Limit Exceeded] 💀 This is the "N-aive" solution. It works perfectly until you have a stream of 10,000 numbers and your add() function takes 5 seconds. The problem isn't the concept. It's the stream. You're adding one new number, but you're re-sorting everything, every single time. It's like re-organizing your entire bookshelf every time you buy one new book. The real "Aha!" moment comes when you ask the right question: "Do I really care about the 1,000th or 1,000,000th largest number?" No. You only care about the Top K. So, how do you find the Kth Largest element? You use... a Min-Heap. (Wait, what? 🤯) Yes! This is the counter-intuitive trick that makes you look like a genius. You build a min-heap (a "priority queue") that only holds k items. The smallest item in this heap (the root) is always your Kth largest element. A new number arrives. Is it smaller than the root? Ignore it. It's not in the Top K. Is it bigger? Kick out the root (the smallest of the Top K) and push the new number. Return the new root. Boom. O(log k) for every add, not O(N log N). This isn't just a LeetCode problem. This is the core logic for any real-time "Top K" system: Live video game leaderboards 🎮 Monitoring the "Top 10" slowest server response times 📈 Finding the most popular items in a streaming feed What's your favorite "counter-intuitive" algorithm? Let me know! #leetcode #datastructures #algorithms #computerscience #programming #coding #softwareengineering #developer #python #heaps #priorityqueue #techeducation
More Relevant Posts
-
Build a daily tracking page for the latest research papers about「AI agent」, it only took less than 10 minutes! In the past, I also built similar systems, which took me more than two weeks. I needed to spend time learning the arXiv API, Python asynchronous requests, and then started building. But now, that is no longer necessary! If you want to get notified about newest research papers in your field, you can quickly build one using Cursor. details: 1.Cursor Composer1 + Plan Mode, Composer1 is truly super efficient! 2. open-source project —— arxiv-sanity-preserver from kapathy
To view or add a comment, sign in
-
-
🚀 Solved a Classic String-Search Problem! I recently worked on the problem “Find the index of the first occurrence of a string in another string” (LeetCode 28 — strStr()), and it was a great exercise in understanding string manipulation and efficient search techniques. 🔍 Problem Summary Given two strings, haystack and needle, the goal is to return the index of the first occurrence of needle within haystack, or -1 if it doesn’t exist. 🔧 My Approach I implemented two solutions: 1️⃣ Basic Sliding Window Approach Iterate through haystack Compare each substring with needle Return the index when a match is found 2️⃣ Optimized Thought Process (KMP-ready) Explored how KMP can reduce time complexity from O(n*m) to O(n) Understood prefix functions and pattern matching fundamentals 🧠 What I Learned Strengthened understanding of string traversal Learned how to optimize search operations Practiced writing clean and readable code Got a deeper understanding of how real search algorithms (like KMP) work behind the scenes Happy to connect with others exploring DSA, algorithms, and problem-solving! 🚀 #️⃣ #dsa #leetcode #coding #programming #python #softwaredevelopment #algorithms #computerscience
To view or add a comment, sign in
-
-
On Day 298 of my #300daysofcode challenge, I'm sharing my solution to LeetCode Problem 74, "Search a 2D Matrix." This problem is a classic demonstration of adapting the Binary Search algorithm to a 2D structure. My video provides a clear walkthrough of the key optimization: mapping $(row, col)$ indices to a single linear index to perform a fast, $O(\log(M \cdot N))$ search. This is a valuable skill for technical interviews and efficient matrix manipulation. #DataStructures #Algorithms #LeetCode #CodingInterview #Programming #BinarySearch #300daysofcode
To view or add a comment, sign in
-
🚀 Solved LeetCode 3234: Count Substrings with Dominant Ones! 🧠 Just tackled a challenging substring problem: 3234. Count the Number of Substrings With Dominant Ones. The goal is to find all substrings where the count of '1's is greater than or equal to the square of the count of '0's. A simple O(N²) approach is too slow, so a more optimized strategy is needed. My Approach: Key Insight: The condition ones >= zeros² means the number of zeros in any valid substring is small (at most √N). This is the key to optimization. Fix the Endpoint: I iterate through the string, fixing the end of the potential substring. "Zero-Hopping" Technique: From the end, I iterate backward, but instead of going one by one, I "hop" from each '0' to the previous '0'. A precomputed array makes this hop O(1). Efficient Counting: At each hop, I calculate the number of valid start positions in the segment between the two zeros, bringing the total time complexity down to O(N√N). This was a great puzzle in finding the bottleneck and building an algorithm around it! 🔗 Problem Link: https://lnkd.in/gpmZdskg #LeetCode #Coding #Algorithm #Python #ProblemSolving #SoftwareEngineering #Optimization #LeetCode #Coding #Algorithm #Python #Programming #InterviewPrep
To view or add a comment, sign in
-
-
💡 Day 17 of 30 – LeetCode Challenge: Word Search (Backtracking) Today’s problem tested my understanding of DFS (Depth-First Search) and Backtracking — a key algorithmic concept used in exploring possible paths or configurations in grids, trees, and graphs. 🧩 Problem Summary We are given an m x n character grid (board) and a string word. We must determine if the word exists in the grid by moving horizontally or vertically through adjacent cells. Each cell can be used only once per word construction. ⚙️ Example Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]] word = "ABCCED" Output: true 📖 Explanation: The path A → B → C → C → E → D forms the word “ABCCED” through valid adjacent cells. 🧠 Approach 1. Traverse every cell in the grid. 2. If the character matches the first letter of word, start a DFS. 3. Explore all 4 directions — up, down, left, right — recursively. 4. Mark cells as visited (temporarily) to prevent reuse. 5. Backtrack after exploring each path (restore cell value). 6. Return True as soon as the word is found. ⏱ Complexity Analysis Time Complexity O(m * n * 4^L) → where L = length of word Space Complexity O(L) (Recursion stack) 🧩 Key Learnings ✨ Learned how DFS + Backtracking can explore all potential paths efficiently. ✨ Importance of restoring state (backtracking) after recursive exploration. ✨ Strengthened my problem-solving in grid-based traversal problems. Backtracking is like exploring a maze — you move forward when possible and step back when you hit a dead end. #Day17 #LeetCode #Backtracking #DFS #WordSearch #CodingChallenge #Python #DSA #WomenWhoCode #ProblemSolving #MTech #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 19/30 – 30DaysOfDSAChallenge 🚀 🧠 Topic: Subarray Sum Equals K 📘 Concepts Covered: Prefix Sum | HashMap | Cumulative Sum | Subarray Counting Today’s challenge was about finding the number of continuous subarrays whose sum equals a given value K. It was a great exercise in understanding how prefix sums can optimize brute-force solutions! ⚡ 🔹 Approach – Prefix Sum + HashMap 💡 Logic: Compute prefix sums to store cumulative totals. Use a HashMap to keep track of how many times a particular prefix sum appears. For each prefix sum, check if (currentSum - K) exists in the map — if yes, those subarrays contribute to the answer. Update the map as you iterate to maintain frequency counts. ⚙️ Time Complexity: O(N) ⚙️ Space Complexity: O(N) ✅ Efficient one-pass solution using extra space for quick lookups. ✨ Key Takeaway: Prefix sum with HashMap is a powerful combo — it transforms nested loop logic into a clean, linear-time approach. These concepts often appear in tricky subarray or range sum problems, so mastering them pays off big time! 💪 #Day19 #30DaysOfDSAChallenge #LeetCode #PrefixSum #HashMap #Array #Subarray #DSA #CPlusPlus #CodingChallenge #ProblemSolving #CodingJourney #LearnDSA #CodeEveryday #Algorithms #Programming
To view or add a comment, sign in
-
-
🗓 Day 9 / 100 – #100DaysOfLeetCode 📌 Problem 2654: Minimum Number of Operations to Make All Array Elements Equal to 1 The goal was to determine the minimum number of operations required to make every element in the array equal to 1, where in one operation, you can replace any element with the GCD of two chosen elements. 🧠 My Approach: Checked if there was already a 1 in the array — since each existing 1 helps reduce operations directly. If not, iterated through the array to find a subarray whose GCD = 1. Once found, calculated how many steps are required to propagate this 1 throughout the entire array. Applied GCD (Greatest Common Divisor) properties to minimize redundant operations. ⏱ Time Complexity: O(n²) 💾 Space Complexity: O(1) 💡 Key Learning: This problem beautifully connects number theory with array transformations. Understanding how the GCD operation interacts across array elements can dramatically reduce the number of steps — turning a brute-force idea into an efficient solution. Every problem solved is one more step toward thinking more analytically and coding more efficiently 🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #MathInCoding #GCD #NumberTheory #Algorithms #DataStructures #DSA #CodingJourney #CompetitiveProgramming #SoftwareEngineering #LearningInPublic #CodeEveryday #DeveloperJourney #TechStudent #LogicBuilding #CodingCommunity #CareerGrowth #Optimization #KeepLearning
To view or add a comment, sign in
-
-
"Day 3 is a massive win for efficiency! I dedicated the morning to mastering the Two-Pointer technique, a critical step in optimizing array algorithms. I successfully tackled two key problems, including the famous Remove Duplicates (#26), which confirmed the absolute necessity of O(1) auxiliary space optimization. Key Technical Insight: O(1) Space is King I compared different approaches for removing duplicates and confirmed the core DSA lesson: 1. The Slow/Fast Pointer method is the correct, efficient approach, achieving O(1) space and O(n) time by manipulating the array in-place. 2. Brute-force solutions using helper data structures violate the memory constraint and often lead to slow O(n^2) time complexity. The lesson is clear: Master the mechanism, don't just rely on the wrapper. Understanding this difference is essential for building scalable applications. All progress is documented and pushed. Now, the plan pivots to laying the foundation for my Python OOP skills and project architecture. #DSA #TwoPointers #Python #LeetCode #SoftwareEngineering #Consistency #O1Space"
To view or add a comment, sign in
-
LeetCode #33 - Search in Rotated Sorted Array This is the classic variation of Binary Search, where the sorted array is rotated at some pivot point. Even tough it looks unsorted at first glance, one half of the array is always sorted and that's the key insight to solving this problem efficiently. Problem Summery: We are given an array that was initially sorted but then rotated at an unknown index. We need to find the index of the target element in O(log n) time. It it doesn't exist, return -1. Approach: Use Modified Binary Search At each step: - Determine which side (left or right) is sorted - Check if the target lies within that sorted half - Narrow the search range accordingly This ensures that every iteration halves the search space - keeping it logarithmic in complexity. Key Insights: - One of the two halves is always sorted in a rotated sorted array - Comparing nums[start], nums[mid], and nums[end] helps identify the sorted side - Efficiently narrows down to the correct segment without linear scanning Complexity Analysis: - Time Complexity: O(log n) - Space Complexity: O(1) Example: Input : nums = [4,5,6,7,0,1,2], target = 6 Output: 2 The algorithm quickly identifies that 6 lies in the sorted left half and returns its index. #LeetCode #DSA #CPP #C++ #ProblemSolving #BinarySearch #Coding #InterviewPreparation #TechLearning #Coding #Programming #DataStructure
To view or add a comment, sign in
-
-
Day 9: Understanding Recursion through Factorials Today’s challenge was all about mastering one of the most elegant concepts in computer science — Recursion. I implemented a recursive function to calculate the factorial of a number — a foundational problem that helps build deeper understanding of how function calls work in a stack-like manner. 📘 Concept Recap: Recursion is when a function calls itself until it reaches a base condition. For factorial, the mathematical definition is: n! = n × (n-1)! with the base case being 1! = 1. 💻 Code Example (Python): def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) n = int(input()) print(factorial(n)) 📊 Sample Input: 3 📈 Sample Output: 6 ✨ Key Takeaway: Recursion simplifies complex problems by breaking them down into smaller subproblems. Understanding base cases and recursive calls is essential to avoid infinite loops and stack overflows. Every recursive problem teaches patience and logical thinking — both vital for becoming a strong problem solver. #Day9 #100DaysOfCode #Recursion #ProblemSolving #Algorithms #Python #CodingJourney #Developer #Learning
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