Day 68: Search in 2D Sorted Matrix (Search Space Reduction) 🔎 I'm continuing the streak on Day 68 of #100DaysOfCode with a challenging matrix search problem! The task is to find a target value in an $m \times n$ matrix where both rows and columns are sorted in ascending order. The key to solving this efficiently is Search Space Reduction. Instead of performing a standard search, my solution uses a smart traversal technique: Starting Point: I begin the search at the top-right corner of the matrix. Decision Logic: If the current value equals the target, we stop. If the current value is greater than the target, the entire current column can be eliminated, so we move left. If the current value is less than the target, the entire current row can be eliminated, so we move down. This strategy eliminates one row or one column in every step, guaranteeing an optimal O(m + n) time complexity and O(1) extra space. #Python #DSA #Algorithms #Matrix #Search #100DaysOfCode #ProblemSolving
How to Search in a 2D Sorted Matrix Efficiently
More Relevant Posts
-
🚀 Day 3 of #100DaysofDSA Today’s focus was on the “Set Matrix Zeroes” problem — a classic array-matrix question that tests both logic and optimization thinking It began with the brute-force idea: storing all zero positions and then marking corresponding rows and columns later. It works but takes O(m × n) time and O(m + n) extra space. Next, then explored a better approach using two auxiliary arrays to track which rows and columns should be zeroed. This improved the clarity but still consumed additional memory and space. Finally, then to reduce the complexity I tackled the optimal solution, which achieves O(1) extra space by using the first row and first column of the matrix itself as markers. A small Boolean flag handles the edge case when the first row contains a zero. This subtle observation transforms the logic completely — turning a memory-heavy method into a clean in-place algorithm. It was a good reminder that optimization isn’t just about speed — it’s about finding elegance in constraints. #100DaysOfDSA #MatrixProblems #Optimization #SpaceComplexity #Python #ProblemSolving
To view or add a comment, sign in
-
-
Day 70: Largest Rectangle in Histogram (Monotonic Stack) I've hit Day 70 of #100DaysOfCode by solving one of the toughest array problems: "Largest Rectangle in Histogram." The challenge is to find the maximum area that can be formed by any bar acting as the minimum height. My solution uses the Monotonic Stack technique: The Goal: For every bar, we need to find the nearest shorter bar to its left and right. This range defines the maximum width for that bar's height. Monotonic Stack: I use a stack that stores indices of heights in strictly increasing order . Calculation: When a new, shorter bar is encountered, it acts as the right boundary for all taller bars currently in the stack. I pop the taller bar, calculate its maximum possible area (using the new stack top as the left boundary), and update the global maximum. This clever method ensures that every bar is pushed and popped exactly once, leading to an optimal O(n) time complexity. #Python #DSA #Algorithms #MonotonicStack #Stack #100DaysOfCode #HardChallenge #ProblemSolving
To view or add a comment, sign in
-
-
✅ Learned to solve “Remove Duplicates from Sorted Array” (in-place, O(n) time, O(1) space)! Sorted input means every duplicate sits next to its twin—perfect setup for the two-pointer pattern: scan once, write uniques forward, and return the count k while keeping the first k positions clean and ordered. What clicked: - Two pointers: one scans, one writes uniques forward - Skip repeats deterministically thanks to sorting - Edge cases covered: empty array, all duplicates, negatives, mixed ranges Level-ups next: “Remove Duplicates II” (allow at most twice) and “Remove Element” to deepen the pattern muscle. What’s your favorite twist on this technique? 🚀 #LeetCode #TwoPointers #Arrays #InPlace #DSA #Algorithms #InterviewPrep #ProblemSolving #TimeComplexity #CodingChallenge #Python #SoftwareEngineering
To view or add a comment, sign in
-
-
✅ LeetCode 3446 – Sort Matrix by Diagonals Successfully solved another interesting matrix manipulation problem! 🧩 Problem Summary: Given an n × n matrix, the task is to sort: The bottom-left diagonals (including the main diagonal) in non-increasing order. The top-right diagonals in non-decreasing order. 💡 Approach: Use a dictionary to group elements by diagonal index (j - i). Sort each diagonal individually based on its position (top or bottom triangle). Reconstruct the matrix by placing back the sorted values. ⚙️ Key Concepts: Matrix traversal Diagonal indexing (j - i) Sorting and reconstruction 📊 Result: ✅ Accepted with 0 ms runtime 💪 Optimized, clean, and easy-to-read solution #LeetCode #Python #ProblemSolving #CodingChallenge #DataStructures #Algorithms #Matrix #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 LeetCode #1625: Lexicographically Smallest String After Applying Operations Today’s problem was about transforming a numeric string using two operations: adding a value to digits at odd indices and rotating the string, to get the lexicographically smallest result possible. The challenge was to handle infinite possibilities smartly. I used a Breadth First Search (BFS) approach to systematically explore all reachable string states while keeping track of visited ones. 💡 Key Takeaways: - Some problems don’t need a direct formula, they need systematic exploration. - BFS is not just for graphs; it’s a powerful tool for exploring state transitions too. - Modular arithmetic and rotation logic often come together in string manipulation problems. This one was a great reminder that clean logic and state tracking can solve even the most “infinite looking” problems efficiently. #LeetCode #ProblemSolving #Python #DSA #CodingChallenge #Algorithms #BFS #StringManipulation #LearningEveryday
To view or add a comment, sign in
-
-
Day 16 of #100DaysOfLeetCode Today’s problem focused on substring counting within binary strings and required an efficient approach to handle potentially large input sizes without generating every substring explicitly. 1. Number of Substrings With Only 1s The task was to count the total number of substrings that consist entirely of the character '1', with the final result taken modulo (10^9 + 7). Instead of constructing the substrings, the key insight is that each continuous block of 1s contributes a predictable number of valid substrings. 🔹 My Approach: Iterated through the string while tracking the current streak length of consecutive 1s. Each time a block ended, computed the number of substrings from that block using the formula: k*(k+1)/2 where k is the length of the streak. Added the total from each block to the final answer, applying the modulo constraint throughout. Completed the process with a final update for any trailing block of 1s. What I Learned: This problem reinforces how recognizing mathematical patterns within sequences can transform a brute-force solution into a simple linear scan. Efficient substring counting often comes down to understanding structure rather than enumerating possibilities. 📊 Complexity Analysis: Time Complexity: O(n) — single pass over the string. Space Complexity: O(1) — constant space approach. #day16 #100daysofleetcode #leetcode #DSA #python #leetcodes #striver
To view or add a comment, sign in
-
-
DAY-1:CODING CHALLENGE 1.Longest common Prefix substring from given string as input 2.3SUM problem Started with BRUTE-FORCE → checked every triplet. 😀 Worked 😇 but SLOW for big arrays (O(n³)) → TIME LIMIT EXCEEDED. Faced errors along the way: 'int object not iterable' → I wrote sorted(a,b,c) instead of sorted([a,b,c]). 'unhashable type: list' → Tried adding list to set. Fixed by converting to tuple. LOGICAL BUG → Return inside the loop returned early. Fixed by moving return outside. Finally moved to OPTIMAL TWO-POINTER APPROACH: Sort array first. Use two pointers to find pairs for target -nums[i]. Skip duplicates carefully. Complexity reduced to O(n²). 💡 Lessons learned: small syntax mistakes can cause big errors, immutable types are key for sets, and proper pointer logic makes code efficient. #Python #Algorithms #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🔍 Day 44 DSA Challenge – Problem #33: Search in Rotated Sorted Array 📌 Problem Statement: Given a sorted array nums that may have been rotated at an unknown pivot, find the index of a target value. Return -1 if the target doesn’t exist. The solution must run in O(log n) time. ⚙️ How I Solved It: Applied a modified binary search: Identify which half (left or right) is sorted. Narrow the search to the half where the target could exist. Repeat until the target is found or search space is exhausted. 📊 Performance Stats: ⏱ Runtime: 0 ms (⚡ beats 100%) 💾 Memory: 12.65 MB (beats 42.49%) ✅ Testcases Passed: 196 / 196 🧠 Key Takeaway: Understanding array properties like rotation and leveraging binary search ensures optimal search performance in logarithmic time. #LeetCode #BinarySearch #RotatedArray #Problem33 #Python #DSA #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
Today I worked on a classic string problem: Finding the length of the longest substring that contains no repeated characters. 🧠 What the problem asks: Given a string, identify the longest continuous sequence where all characters are unique, and return its length. 📌 Key Observations: A substring must be continuous (not scattered like a subsequence) As soon as a character repeats, the current window becomes invalid The goal is to maintain a window of unique characters only 🔍 How I approached it: I used the Sliding Window technique with two pointers. This helped me: Expand the window when characters are unique Shrink it when duplicates appear Track the maximum length efficiently This approach avoids rechecking characters repeatedly and keeps the solution optimal. ✔ Example Insights: "abcabcbb" → longest substring: "abc" → length 3 "bbbbb" → "b" → length 1 "pwwkew" → "wke" → length 3 💡 Takeaway: This problem reinforces how powerful sliding window techniques are for real-world string and array challenges. Great practice for improving logic, efficiency, and pattern recognition. #LeetCode #CodingPractice #Python #Algorithms #100DaysOfCode #SlidingWindow #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
Day 67: Sliding Window Maximum (Deque) 🧠 I'm continuing my journey through complex array problems on Day 67 of #100DaysOfCode with "Sliding Window Maximum." The challenge is to efficiently find the maximum element within a sliding window of size k as it moves across an array. My solution uses a Monotonically Decreasing Deque (Double-Ended Queue), the optimal structure for this problem: Window Management: As the window slides to the right, I first remove elements from the left of the deque that are now out of the window's bounds (line 20). Maintaining Maximum: Before adding the new element (nums[i]), I remove elements from the right of the deque that are smaller than nums[i]. This ensures the deque always stores indices in decreasing order of their corresponding values, with the largest element always at the front. Result: The maximum element in the current window is simply the value at the index located at the front of the deque (nums[dq[0]]), which is appended to the result after the window is fully formed. This strategy processes each element exactly twice (once pushed, once popped), resulting in an optimal O(n) time complexity. #Python #DSA #Algorithms #SlidingWindow #Deque #100DaysOfCode #ProblemSolving #Arrays
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