🧩 𝗦𝘁𝗼𝗽 𝗦𝗲𝗮𝗿𝗰𝗵𝗶𝗻𝗴 𝗥𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲𝘀: 𝗧𝗵𝗲 𝗛𝗶𝘀𝘁𝗼𝗴𝗿𝗮𝗺 𝗠𝗶𝗻𝗱𝘀𝗲𝘁 𝗧𝗵𝗮𝘁 𝗦𝗼𝗹𝘃𝗲𝘀 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝗿𝗶𝘅 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Solved an interesting problem today on 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲: 𝗙𝗶𝗻𝗱 𝘁𝗵𝗲 𝗮𝗿𝗲𝗮 𝗼𝗳 𝘁𝗵𝗲 𝗹𝗮𝗿𝗴𝗲𝘀𝘁 𝗿𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲 𝗰𝗼𝗻𝘁𝗮𝗶𝗻𝗶𝗻𝗴 𝗼𝗻𝗹𝘆 𝟭’𝘀 𝗶𝗻 𝗮 𝗯𝗶𝗻𝗮𝗿𝘆 𝗺𝗮𝘁𝗿𝗶𝘅. At first glance, this looks like a classic 𝟮𝗗 𝗿𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲 𝘀𝗲𝗮𝗿𝗰𝗵. But the elegant solution doesn’t search rectangles at all. It 𝗯𝘂𝗶𝗹𝗱𝘀 𝘁𝗵𝗲𝗺 𝘃𝗲𝗿𝘁𝗶𝗰𝗮𝗹𝗹𝘆. 🔄 𝗥𝗼𝘄 𝗯𝘆 𝗥𝗼𝘄 𝗧𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺𝗮𝘁𝗶𝗼𝗻 For each row, treat the matrix like this: 1. ‘1’ → increase the column height 2. ‘0’ → reset the column height to 0 After processing a row, you don’t see a matrix anymore. You see a histogram. And now the question becomes: What’s the largest rectangle in this histogram? 🧠 𝗧𝗵𝗲 𝗖𝗹𝗲𝘃𝗲𝗿 𝗧𝘄𝗶𝘀𝘁 Instead of the usual stack approach, maintain three arrays: heights[] → current bar heights leftBoundaries[] → how far left this bar can extend rightBoundaries[] → how far right this bar can extend Two linear scans per row set these boundaries precisely. 📐 𝗔𝗿𝗲𝗮 𝗖𝗼𝗺𝗽𝘂𝘁𝗮𝘁𝗶𝗼𝗻 For every column: width = rightBoundaries[j] - leftBoundaries[j] area = heights[j] * width Update the maximum. Move to the next row. Repeat. 💡 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝘄𝗼𝗿𝗸𝘀 𝗯𝗲𝗮𝘂𝘁𝗶𝗳𝘂𝗹𝗹𝘆 Because for every row, we already know: 1. Continuous height of 1’s above 2. Maximum width possible at that height So we compute the best rectangle in constant time per column. ⚙️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 Time: O(rows × cols) Space: O(cols) Optimal. Clean. Elegant. ✨ 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Sometimes the best way to solve a 2D problem is to 𝘀𝘁𝗼𝗽 𝘁𝗵𝗶𝗻𝗸𝗶𝗻𝗴 𝗶𝗻 𝟮𝗗. #Algorithms #DataStructures #LeetCode #Java #CodingInterview #InterviewPrep #DSA #ProblemSolving #CodingLife #Developers #SoftwareEngineer #TechInterview #Programming #LearnToCode #CodeNewbie #CompetitiveProgramming #100DaysOfCode #Debugging #Optimization #LogicBuilding #STEM
Solving the Maximum Rectangle Problem with Elegant Algorithm
More Relevant Posts
-
🧱 𝗜 𝗦𝗼𝗹𝘃𝗲𝗱 𝗮 “𝗩𝗶𝘀𝘂𝗮𝗹” 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗨𝘀𝗶𝗻𝗴 𝗢𝗻𝗹𝘆 𝗮 𝗦𝘁𝗮𝗰𝗸 — 𝗡𝗼 𝗚𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗡𝗲𝗲𝗱𝗲𝗱 Today’s problem looked visual and innocent: 𝗚𝗶𝘃𝗲𝗻 𝗯𝗮𝗿 𝗵𝗲𝗶𝗴𝗵𝘁𝘀 𝗼𝗳 𝗮 𝗵𝗶𝘀𝘁𝗼𝗴𝗿𝗮𝗺 (𝘄𝗶𝗱𝘁𝗵 = 𝟭), 𝗳𝗶𝗻𝗱 𝘁𝗵𝗲 𝗹𝗮𝗿𝗴𝗲𝘀𝘁 𝗿𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲 𝗮𝗿𝗲𝗮. This is the classic problem from 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 — and it’s a beautiful lesson in how 𝗺𝗼𝗻𝗼𝘁𝗼𝗻𝗶𝗰 𝘀𝘁𝗮𝗰𝗸𝘀 𝗰𝗼𝗻𝘃𝗲𝗿𝘁 𝗴𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗶𝗻𝘁𝗼 𝗶𝗻𝗱𝗶𝗰𝗲𝘀. 🧠 𝗧𝗵𝗲 𝗡𝗮𝗶𝘃𝗲 𝗧𝗵𝗼𝘂𝗴𝗵𝘁 (𝗮𝗻𝗱 𝘄𝗵𝘆 𝗶𝘁 𝗳𝗮𝗶𝗹𝘀) For every bar i, try expanding left and right until you hit a smaller bar. That’s O(n) per index -> O(n²). Too slow for n=10^5. So the real question becomes: For each bar, how far can it extend without hitting a smaller height? That is the entire problem. 💡 𝗞𝗲𝘆 𝗜𝗱𝗲𝗮 — 𝗡𝗲𝗮𝗿𝗲𝘀𝘁 𝗦𝗺𝗮𝗹𝗹𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 For every index i: 1. Find the first smaller bar on the left 2. Find the first smaller bar on the right A monotonic increasing stack gives both in linear time. ▶️ 𝗟𝗲𝗳𝘁 𝗦𝗰𝗮𝗻 (𝗟 -> 𝗥) Pop until the top is strictly smaller. That index defines the left boundary. ◀️ 𝗥𝗶𝗴𝗵𝘁 𝗦𝗰𝗮𝗻 (𝗥 -> 𝗟) Same logic to get the right boundary. Now each bar knows the exact range where it is the minimum. ⏱️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 Each index pushed/popped once → O(n) Space → O(n) ✨ 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 1. “Nearest smaller element” is a powerful pattern 2. Monotonic stacks turn nested loops into linear scans 3. Think: If this bar is the minimum, how wide can the rectangle be? A visual problem, solved with clean stack discipline. #DataStructures #Algorithms #MonotonicStack #Java #ProblemSolving #CodingInterview #Stack #DSA #LeetCode #Coding #Programmer #SoftwareEngineer #InterviewPrep #CompetitiveProgramming #100DaysOfCode #Tech #Learning #ProblemSolvingSkills
To view or add a comment, sign in
-
-
💡 If your code works, that's good. 🚀 If your code works fast, that's great. 🧠 If your code works fast while using less memory, that's engineering. That's why Time Complexity and Space Complexity are so important in DSA. ⏱️ Time Complexity It tells us how the running time grows as input size increases. 💾 Space Complexity It tells us how much extra memory an algorithm needs. 📌 Common Complexities: ⚡ O(1) → Constant Time 🔍 O(log n) → Binary Search 📈 O(n) → Linear Search ⚙️ O(n log n) → Merge Sort 🔥 O(n²) → Nested Loops Whenever I solve a problem, I always ask: ✅ Can it run faster? ✅ Can it use less memory? ✅ Will it scale for large inputs? Because coding isn't just about making it work. It's about making it efficient. And that's what separates programmers from engineers. #DSA #Algorithms #Java #CodingInterview #TimeComplexity #SpaceComplexity #Programming #SoftwareEngineering #Tech
To view or add a comment, sign in
-
Day 73 on LeetCode Find First and Last Position of Element in Sorted Array 🎯🔍✅ Today’s problem focused on a classic and very important Binary Search variation. 🔹 Approach Used in My Solution The goal was to find the first and last occurrence of a target in a sorted array. Key idea in the solution: • Use two separate binary searches 🔸 Find First Occurrence: • When nums[mid] >= target, move left • If nums[mid] == target, store index and continue searching left 🔸 Find Last Occurrence: • When nums[mid] <= target, move right • If nums[mid] == target, store index and continue searching right • Combine both results to get final answer This ensures we don’t just find a match, but the complete range of the target. ⚡ Complexity: • Time Complexity: O(log n) • Space Complexity: O(1) 💡 Key Takeaways: • Learned how to modify binary search to find boundaries instead of single elements • Strengthened understanding of first/last occurrence patterns • Realized how small logic changes turn binary search into powerful variants 🔥 This pattern is extremely common in interview problems! #LeetCode #DSA #Algorithms #DataStructures #BinarySearch #Arrays #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 🚀 Day 76/100 — Tracking Recursive Loops in 2D Space! Today’s Problem: 1559. Detect Cycles in 2D Grid 🔹 The Goal: Given a grid of characters, find if there exists a cycle of length 4 or more consisting of the same value. A cycle is a path that starts and ends at the same cell without moving back to the immediate previous cell. 🔹 The Insight: This is a classic Graph Theory problem applied to a Matrix. To find a cycle, we need to distinguish between "moving forward" and "moving backward." While a standard DFS can find connected components, we need Parent Tracking to identify when we've circled back to a visited node through a different path. 🔹 The Logic: Component Traversal: I used DFS to explore islands of identical characters. Parental Guidance: By passing the (pr, pc) coordinates of the previous cell into the recursion, I ensured the algorithm ignores the immediate backtrack. Cycle Invariant: If we hit a cell that is already visited but is NOT our parent, we've found a loop! In a grid graph, such a loop is guaranteed to have a length of at least 4. ✨ Achievement: Day 76! Moving from coordinate geometry back into graph-based grid traversals. Mastering the "Visited vs. Parent" logic is essential for avoiding infinite loops in complex search algorithms and is a fundamental skill for pathfinding optimizations. 🔍 Steps followed: ✔ Global Visited State: Prevented redundant searches across the $M \times N$ grid. ✔ Directional Vectors: Managed 4-way movement using concise offset arrays. ✔ Recursive Validation: Successfully separated valid cycles from simple path backtracking. 🔧 Complexity Analysis: Time Complexity: $O(M \times N)$ Space Complexity: $O(M \times N)$ (Visited array + Recursion stack) 76 days down! The logic is scaling, the patterns are repeating, and the finish line is getting closer. Let's keep the momentum! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #DFS #GraphTheory #CycleDetection #Algorithms #Day76
To view or add a comment, sign in
-
-
🚀 Day 573 of #750DaysOfCode 🚀 🔍 Problem Solved: Maximize the Distance Between Points on a Square Today’s problem was 🔥 — a mix of geometry + greedy + binary search, and definitely one of those “think differently” questions. 💡 Key Insight: All points lie on the boundary of a square. 👉 Instead of treating this as 2D, we can convert it into a 1D problem by mapping each point to its position along the square’s perimeter. This simplifies the problem dramatically! 🧠 Approach: 1️⃣ Map 2D → 1D (Perimeter Mapping) Traverse square boundary in order Convert each point to a single number 2️⃣ Sort the mapped values 3️⃣ Binary Search on Answer Guess minimum distance d Check if we can pick k points such that each pair is ≥ d apart 4️⃣ Greedy Check Always pick next valid point using binary search Validate circular constraint (since square is a loop) 📈 Complexity: Time: O(n log n + log(side) × k log n) Space: O(n) ✨ Takeaway: 👉 Transform complex geometry into a linear problem 👉 Combine binary search on answer + greedy validation 👉 Think in terms of structure simplification This is the kind of problem that really sharpens problem-solving skills 💪 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #BinarySearch #Algorithms #LearningEveryday #HardProblems
To view or add a comment, sign in
-
-
Salam all! I build reusable systems. Not scripts that work once. Templates that save teams hours. Every customer has different rules. Free days. Charge rates. Thresholds. Engineers rewrite the same logic from scratch. I step back. Find the common core. Build templates. Copy it. Plug in the rules. Done. Other engineers start using it. New hires get up to speed faster. That's what I love. Finding patterns. Building once. Helping the next person. #DataEngineering #Python #ReusableCode #EngineeringMindset
To view or add a comment, sign in
-
🚀 Day 7 of My LeetCode Journey — Sorting Fundamentals Today I focused on two classic sorting algorithms: 🔹 Bubble Sort 🔹 Selection Sort 💡 Bubble Sort The idea is simple: 👉 Compare adjacent elements 👉 Swap if they are in the wrong order 👉 Repeat until the array is sorted It’s easy to understand, but not efficient for large datasets. ⏱️ Time Complexity: O(n²) 💡 Selection Sort A slightly different approach: 👉 Find the minimum element 👉 Place it at the correct position 👉 Repeat for the rest of the array Also simple, but still not optimal for big inputs. ⏱️ Time Complexity: O(n²) 🔥 Key Takeaways: These algorithms may not be optimal, but they build strong fundamentals Understanding how sorting works internally is more important than memorizing Optimization comes later — basics come first Big thanks to Namaste DSA and Akshay Saini 🚀 for guiding this journey Consistency is the real win — Day 8 loading 💪 #LeetCode #DataStructures #Algorithms #CodingJourney #100DaysOfCode #SoftwareEngineering #Programming #InterviewPrep #JavaScript #CodingLife #TechGrowth #ProblemSolving #Developers #LearnToCode #Sorting #BubbleSort #SelectionSort #NamasteDSA
To view or add a comment, sign in
-
Day 72 on LeetCode Search a 2D Matrix 🔍📊✅ Today’s problem was a great application of Binary Search in 2D, breaking it down into two efficient steps. 🔹 Approach Used in My Solution The goal was to determine whether a target exists in a sorted 2D matrix. Key idea in the solution: • First, apply binary search on rows to find the potential row where the target could exist – Check if target lies between matrix[mid][0] and matrix[mid][cols-1] • Once the correct row is found, apply binary search within that row • Return true if found, otherwise false This avoids scanning the entire matrix and ensures efficiency. 🔹 Why This Works Because: • Each row is sorted • The first element of each row is greater than the last of the previous row So we can treat it like a two-level binary search problem. ⚡ Complexity: • Time Complexity: O(log m + log n) • Space Complexity: O(1) 💡 Key Takeaways: • Learned how to extend binary search to 2D structures • Practiced breaking problems into smaller searchable spaces • Reinforced thinking in terms of hierarchical searching 🔥 Another solid step in mastering binary search patterns! #LeetCode #DSA #Algorithms #DataStructures #BinarySearch #Matrix #2DArray #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
🚀 Jetpack Compose — What actually happens inside @Composable? (Deep Dive) @Composable is not just an annotation. It's a promise to the compiler: 👉 "please transform me." Think of the Compose compiler like a secret assistant that rewrites your code before the JVM sees it. Step 1 — You write this @Composable fun Greeting(name: String) { Text("Hello, $name") } Step 2 — Compiler transformation The compiler secretly adds two hidden parameters: fun Greeting( name: String, $composer: Composer, $changed: Int ) • $composer → Tracks position in UI tree (SlotTable) • $changed → Bitmask → tells if inputs changed 👉 This is how Compose decides whether to skip execution Step 3 — Restart group (Recomposition scope) $composer.startRestartGroup(KEY) // UI code $composer.endRestartGroup()?.updateScope { c, _ -> Greeting(name, c, 1) } 👉 Registers a stored lambda 👉 Allows recomposition of ONLY this scope (not whole UI) Step 4 — Smart skipping At runtime, Compose checks: 👉 “Did anything change?” • If NO → entire function is skipped (zero work) • If YES → function re-executes 👉 This is the core performance optimization Step 5 — remember {} becomes SlotTable read val count = remember { mutableStateOf(0) } ➡️ Transforms into: val count = $composer.cache(false) { mutableStateOf(0) } 👉 Stored in SlotTable 👉 Retrieved by position 👉 Survives recomposition 🧠 Interview Summary "@Composable is a compiler transformation where functions are converted into restartable groups tracked by a Composer. A bitmask enables skipping, and stored lambdas allow recomposition of only affected scopes." ❓ Why can't @Composable be called from normal function? 👉 Because normal functions don’t have $composer ✔ Compile-time restriction 💬 This is a commonly asked deep-dive question in Android interviews #AndroidDevelopment #JetpackCompose #Kotlin #ComposeInternals #Recomposition #StateManagement #CleanArchitecture #MVVM #MVI #AndroidInterview #InterviewPreparation #SoftwareEngineer #MobileDeveloper #DeveloperLife #Programming #Coding #DevCommunity
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗣𝗲𝗼𝗽𝗹𝗲 𝗨𝘀𝗲 𝗔𝗜. 𝗙𝗲𝘄 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗧𝗵𝗲 𝗖𝗼𝗱𝗲 𝗔𝗜 𝗰𝗮𝗻 𝗴𝗲𝗻𝗲𝗿𝗮𝘁𝗲 𝗰𝗼𝗱𝗲. 𝗕𝘂𝘁 𝗶𝗳 𝘆𝗼𝘂 𝗱𝗼𝗻’𝘁 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗣𝘆𝘁𝗵𝗼𝗻 𝗱𝗲𝗲𝗽𝗹𝘆, 𝘆𝗼𝘂 𝘄𝗼𝗻’𝘁 𝗸𝗻𝗼𝘄 𝘄𝗵𝗮𝘁 𝗶𝘁’𝘀 𝗱𝗼𝗶𝗻𝗴, 𝘄𝗵𝘆 𝗶𝘁 𝗯𝗿𝗲𝗮𝗸𝘀, 𝗼𝗿 𝗵𝗼𝘄 𝘁𝗼 𝘀𝗰𝗮𝗹𝗲 𝗶𝘁. 𝗧𝗵𝗮𝘁’𝘀 𝘄𝗵𝗲𝗿𝗲 𝗿𝗲𝗮𝗹 𝗲𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴 𝘀𝘁𝗮𝗿𝘁𝘀. 𝗕𝗲𝗹𝗼𝘄 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗰𝗼𝗿𝗲 𝘁𝗼𝗽𝗶𝗰𝘀 𝘆𝗼𝘂 𝘀𝗵𝗼𝘂𝗹𝗱 𝗸𝗻𝗼𝘄: 1. Object-Oriented Programming (OOP) 2. Decorators 3. Generators & Iterators 4. Context Managers 5. Async Programming (async/await) 6. Multithreading & Multiprocessing 7. WebSockets 8. Data Structures & Algorithms 9. Memory Management & Garbage Collection 10. File Handling & Serialization 11. List/Dict/Set Comprehensions 12. Exception Handling (advanced patterns) 13. Functional Programming (map, filter, lambda) 14. Modules & Packaging 15. Virtual Environments & Dependency Management 16. Type Hinting & Static Typing 17. Testing (unit tests, mocking, pytest) 18. Logging & Debugging 19. API Development (FastAPI/Flask) 20. Database Handling (SQL/ORMs) Master these, and you’re not just using AI you’re actually building with it. #Python #AI #SoftwareEngineering #Developers #Coding #MachineLearning #Programming #Tech #LearnToCode
To view or add a comment, sign in
Explore related topics
- Java Coding Interview Best Practices
- Approaches to Array Problem Solving for Coding Interviews
- LeetCode Array Problem Solving Techniques
- Common Algorithms for Coding Interviews
- Strategies for Solving Algorithmic Problems
- How to Approach Full-Stack Code Reviews
- Ways to Improve Coding Logic for Free
- Clean Code Practices For Data Science Projects
- How to Refactor Code Thoroughly
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