✳️Day 39 of #100DaysOfCode✳️ Kth Smallest Element in a Sorted Matrix Here’s the step-by-step logic I followed to solve this efficiently: 1️⃣ Defining the Search Space Since the rows and columns are already sorted, we know the smallest element is at matrix[0][0] and the largest is at matrix[n-1][n-1]. Instead of searching through indices, I performed a Binary Search on the range of values between the low and high elements. 2️⃣ The "Count" Helper Function The core of this approach is a helper function that counts how many elements in the matrix are less than or equal to a specific mid value. In my current implementation, I used a nested loop approach. Optimization Tip: Since the matrix is sorted row-wise and column-wise, this count can actually be optimized to O(n) by starting from the bottom-left and moving toward the top-right! 3️⃣ Narrowing the Range Based on the count returned: If the number of elements \le mid is less than k, it means our target k^{th} element must be larger. So, I adjusted the low pointer to mid + 1. Otherwise, the target could be mid itself or something smaller, so I updated the high pointer and stored the potential answer. 4️⃣ Complexity Check By using Binary Search on the value range, we achieve a much better memory complexity than O(n^2), satisfying the problem's constraints and keeping the solution performant. Key Takeaway: Binary Search isn't just for sorted arrays; it’s a powerful tool for searching through any monotonic search space! #LeetCode #Java #DataStructures #Algorithms #CodingInterview #ContinuousLearning #SoftwareEngineering
Kth Smallest Element in a Sorted Matrix
More Relevant Posts
-
Solved LeetCode 110 – Balanced Binary Tree 🌳 Most people start with a brute-force approach (recomputing heights again and again), which leads to O(n²) in worst cases. Instead, I focused on an optimized bottom-up DFS (post-order traversal). 💡 Key idea: Each node returns its height if balanced Returns -1 as a sentinel if unbalanced Propagates early to avoid unnecessary computation class Solution { public boolean isBalanced(TreeNode root) { return checkHeight(root) != -1; } int checkHeight(TreeNode node){ if (node == null) return 0; int left = checkHeight(node.left); int right = checkHeight(node.right); if (left == -1 || right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } } 🚀 Complexity: Time: O(n) Space: O(h) (recursion stack) 📌 What I learned: Combining multiple computations (height + balance) into a single traversal Using sentinel values to simplify recursion Thinking in bottom-up patterns for tree problems This pattern is widely useful in tree-based problems and even shows up in backend systems where hierarchical data needs validation. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
-
✳️Day 40 of #100DaysOfCode✳️ 🚀 Cracking the Code: Solving "Ugly Number III" with Math & Binary Search 1️⃣ The Power of Binary Search Instead of counting up from 1, we treat the answer as a range. By using Binary Search on the search space (up to 2 \times 10^9), we can efficiently narrow down the n^{th} number. We check a candidate middle value to see if there are at least n ugly numbers below it. 2️⃣ Inclusion-Exclusion Principle (The Math Secret) To count how many numbers up to M are divisible by a, b, or c, we can't just add them up—that would double-count the multiples they share. I used the Inclusion-Exclusion Principle to get an accurate count: Add counts of numbers divisible by a, b, and c individually. Subtract the counts of numbers divisible by their pairs: lcm(a, b), lcm(b, c), and lcm(a, c). Add back the count of numbers divisible by all three: lcm(a, b, c). 3️⃣ Least Common Multiple (LCM) & GCD To find the LCM accurately, I implemented a helper function using the Greatest Common Divisor (GCD). This ensures that we correctly identify the overlapping multiples without overflow issues. Key Takeaway: Sometimes the most efficient way to "search" isn't to look at every item, but to use mathematical properties to "jump" to the right answer. #LeetCode #Java #Algorithms #CompetitiveProgramming #SoftwareEngineering #BinarySearch #MathInCode
To view or add a comment, sign in
-
-
First Missing Positive — Not as Simple as It Looks At first glance, this problem looks simple. A natural instinct is to solve it using a hashmap or a set to track elements. But that approach won’t work here. The problem strictly requires: O(n) Time Complexity O(1) Space Complexity So we need a different way of thinking. The key idea is to use the input array itself as a marker instead of extra space. Approach: Clean the array Replace all negative numbers, zeros, and values greater than n with n + 1 Because the answer will always lie in the range [1, n+1] Mark presence using indices For every number num, mark the index num - 1 as negative This indicates that the number exists in the array Identify the missing number The first index that has a positive value gives the answer (index + 1) Edge case If all indices are marked, then the answer is n + 1 Why this works: We reuse the given array, so no extra space is needed. Each element is processed a constant number of times, ensuring linear time. Insight: This problem shows how constraints change your approach. A hashmap solution is straightforward, but it violates the space requirement. Sometimes the optimal solution comes from rethinking how to use the existing data instead of adding new structures. #DataStructures #Algorithms #Java #CodingInterview #ProblemSolving
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 – 𝐃𝐞𝐜𝐨𝐝𝐞 𝐭𝐡𝐞 𝐒𝐥𝐚𝐧𝐭𝐞𝐝 𝐂𝐢𝐩𝐡𝐞𝐫𝐭𝐞𝐱𝐭 (𝐌𝐞𝐝𝐢𝐮𝐦) Today’s problem was a 𝐟𝐮𝐧 𝐦𝐚𝐭𝐫𝐢𝐱 𝐭𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥 + 𝐬𝐢𝐦𝐮𝐥𝐚𝐭𝐢𝐨𝐧 𝐜𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐋𝐢𝐧𝐤 : https://lnkd.in/gsSCrJbr 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐋𝐢𝐧𝐤 : https://lnkd.in/gMhqhD6M The idea behind the encoding process: The original text is written 𝐝𝐢𝐚𝐠𝐨𝐧𝐚𝐥𝐥𝐲 𝐢𝐧 𝐚 𝐦𝐚𝐭𝐫𝐢𝐱 with a fixed number of rows. The matrix is then read row by row to produce the encoded string. To decode it, we reverse the process: 🔹 𝐊𝐞𝐲 𝐎𝐛𝐬𝐞𝐫𝐯𝐚𝐭𝐢𝐨𝐧𝐬 If n = encodedText.length() and we know rows, then cols = n / rows Characters of the original text lie on diagonals starting from each column in the first row. Traverse diagonally (row++, col++) from each starting column. 🔹 𝐒𝐭𝐞𝐩𝐬 Compute the number of columns. For every column c, traverse diagonally down-right. Map the matrix index using r * cols + c. Build the result string. Remove trailing spaces at the end. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 Time: O(n) Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲: Whenever you see a matrix encoding problem, think about how the data was written and reverse the traversal pattern. #LeetCode #CodingInterview #DataStructures #Algorithms #Java #ProblemSolving #DailyCodingChallenge
To view or add a comment, sign in
-
-
The High Cost of the Wrong Initial Choice I have seen complex computation logic for over a million records take hours to run simply because of inefficient, row-by-row processing that is offered by database stored procedures and traditional java/python code. It is slow, impossible to scale, and eventually kills your product's edge in the market. By moving to vectorized logic with tools like NumPy or Polars, you can turn those hours of computation into milliseconds. This is not just about using newer tools, it is about leveraging modern execution like #SIMD (Single Instruction Multiple Data) and #multithreading to gain a massive competitive advantage. If your backend is computation heavy and you're still stuck in legacy loops, you are leaving performance, market edge and money on the table. References: https://lnkd.in/g8j3A5Bn https://lnkd.in/gaPnFUQm https://lnkd.in/gWt9WHnp #DataEngineering #SystemDesign #NumPy #PerformanceOptimization #Scalability #PythonProgramming #TechStrategy #Vectorization #TechToolChoice
To view or add a comment, sign in
-
Floyd's cycle detection algorithm finally clicked today — and the math had nothing to do with it. The problem: LeetCode 287, Find the Duplicate Number. Constraints rule out sorting, hash sets, and modifying the input. The trick is to read the array as a linked list and detect a cycle. I'd seen the textbook explanation before. The algebra (F = (k−1)C + b) made sense on paper but never gave me a mental picture I could rebuild from scratch. What unstuck me was an analogy: the lollipop. Here's the version that stuck: 1. Don't iterate the array as 0, 1, 2, 3, 4. Iterate by values — nextIndex = nums[currentIndex]. This turns the array into a chain. 2. Because there's a duplicate, two indices end up pointing to the same next index. That creates a cycle. The overall shape: a straight stick from index 0 to the cycle entrance, then a loop at the end. A lollipop. 3. Run two pointers from index 0 — slow (1 step) and fast (2 steps). Inside the loop, fast catches slow at some meeting point. 4. The non-obvious part: the distance from the meeting point forward around the loop back to the entrance matches the distance from the start to the entrance. (Whole laps cancel out — but the math is optional once you see the picture.) 5. Reset one pointer to the start. Leave the other at the meeting point. Move both one step at a time. They collide exactly at the entrance — and the entrance index is the duplicate. O(n) time, O(1) space, no input mutation. All three problem constraints satisfied. The bigger lesson, especially for senior interview prep: when an algorithm feels like memorization, you don't have the picture yet. Find the picture, and the proof becomes something you can rebuild on the fly instead of cram. The notation is just the picture wearing a tie. #Java #DataStructures #Algorithms #InterviewPrep #LeetCode
To view or add a comment, sign in
-
𝗜 𝗰𝘂𝘁 𝗮𝗻 𝗘𝗧𝗟 𝗽𝗶𝗽𝗲𝗹𝗶𝗻𝗲'𝘀 𝗽𝗿𝗲𝗽𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴 𝗹𝗮𝘁𝗲𝗻𝗰𝘆 𝗯𝘆 𝟳𝟬%. Three things worked. Only one of them was the one I expected. The context: we were processing 𝟱𝟬𝟬𝗞+ (𝗶𝗻𝘃𝗼𝗶𝗰𝗲𝘀) 𝗿𝗲𝗰𝗼𝗿𝗱𝘀 𝗮 𝘄𝗲𝗲𝗸. The pipeline was quietly becoming the bottleneck for every downstream dashboard. Management wanted more data ingested, not less — so optimization wasn't optional. 𝗛𝗲𝗿𝗲'𝘀 𝘄𝗵𝗮𝘁 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗺𝗼𝘃𝗲𝗱 𝘁𝗵𝗲 𝗻𝗲𝗲𝗱𝗹𝗲: 𝟭. 𝗣𝗿𝗼𝗳𝗶𝗹𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝘆𝗼𝘂 𝗼𝗽𝘁𝗶𝗺𝗶𝘇𝗲. My instinct was to parallelize first. The profiler told me 60% of the time was spent in a single nested loop doing membership checks against a list. Swapping the list for a set closed most of the gap before I wrote a single worker. 𝟮. 𝗜/𝗢-𝗯𝗼𝘂𝗻𝗱 𝘄𝗼𝗿𝗸 𝗱𝗼𝗲𝘀𝗻'𝘁 𝗰𝗮𝗿𝗲 𝗮𝗯𝗼𝘂𝘁 𝗰𝗼𝗿𝗲𝘀. I assumed multiprocessing would win. The CPU-bound transforms benefited less than expected. The biggest jump came from batching database writes and running them concurrently against the sink — not from parallelizing the Python code. 𝟯. 𝗕𝗼𝗿𝗶𝗻𝗴 𝗯𝗲𝗮𝘁𝘀 𝗰𝗹𝗲𝘃𝗲𝗿, 𝗮𝗹𝗺𝗼𝘀𝘁 𝗮𝗹𝘄𝗮𝘆𝘀. A weekly-batch analysis showed ~50% of our records didn't actually change week-over-week. A simple content-hash cache skipped all of that redundant work. Five lines of code. Bigger impact than the parallelism refactor. The takeaway I keep coming back to: measure first, then pick the cheapest fix that matches the real bottleneck. Engineers (me included) love the interesting solutions. The boring ones usually win. So tell me :— What's the most embarrassingly simple fix that ever saved you a week? #softwareengineering #python #backend #dataengineering #learninginpublic
To view or add a comment, sign in
-
📅 Date: April 25, 2026 Day 4 of my LeetCode Journey 🚀 ✅ Problem Solved: 9. Palindrome Number 🧠 Approach & Smart Solution: While it's easy to solve this by converting the integer to a string and reversing it, that takes extra memory! I opted for a highly optimized mathematical approach. I reversed the integer by peeling off its digits one by one using modulo and division, keeping the space complexity to an absolute minimum. • Pseudo-code: Handle edge cases: If the number is less than 0, it can't be a palindrome, so return false. Store the original number in a temporary variable for final comparison. Initialize a 'reverse' variable to 0. Loop while the number is greater than 0: Extract the last digit: digit = x % 10. Add it to the reversed number: reverse = (reverse * 10) + digit. Remove the last digit from the original number: x = x / 10. Finally, return true if the original number matches the reversed number. This math-based solution avoids expensive string conversions and runs instantly! ⏱️ Time Complexity: O(log₁₀(n)) (We only iterate through the digits of the number) 📦 Space Complexity: O(1) (Only using a few integer variables) 📊 Progress Update: • Streak: 3 Days 🔥 • Difficulty: Easy • Pattern: Math / Digit Extraction 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Choosing mathematical operations over string manipulations is a great way to optimize basic algorithms! 💡 #LeetCode #DSA #Math #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Problem :- Search Insert Position (LeetCode 35) Problem Statement :- Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Approach :- Binary Search i - Uses Binary Search to efficiently find the target or its position in a sorted array. ii - Compares nums[mid] with target and adjusts search range (start or end). iii - Loop ends when target is not found, and correct position is crossed. iv - If target > nums[mid] => mid + 1 Else => mid v - Time Complexity : O(log n) vi - Space Complexity : O(1) class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return (target > nums[mid]) ? mid + 1 : mid; } } Key Takeaway :- Binary Search efficiently finds the position (or insertion point) by repeatedly dividing the search space. How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #BinarySearch
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