Solved the Maximal Rectangle problem using a histogram + stack approach. The idea is to treat each row as the base of a histogram. For every row, we build a height array where each value represents consecutive 1’s vertically. Then, for each updated histogram, we apply the Largest Rectangle in Histogram algorithm using a monotonic stack. The stack stores indices of increasing heights. When a smaller height appears, we pop from the stack and calculate area using the popped height as the limiting height and width based on boundaries. This way, instead of checking all rectangles, we efficiently compute the maximum area row by row. Time Complexity: O(n * m) Space Complexity: O(m) #Java #DSA #Stack #LeetCode #Coding
Solving Maximal Rectangle problem with histogram and stack
More Relevant Posts
-
🚀 Day 78 of #100DaysOfCode Solved 443. String Compression on LeetCode 🔗 🧠 Key Insight: We compress the array in-place by: 👉 Replacing consecutive characters with: char + count (if count > 1) Example: ["a","a","b","b","c","c","c"] → ["a","2","b","2","c","3"] ⚙️ Approach (Two Pointers): 1️⃣ Use two pointers: 🔹 i → iterate through array 🔹 idx → position to write compressed result 2️⃣ For each character: 🔹 Count consecutive occurrences using a loop 3️⃣ Write character: 🔹 chars[idx++] = ch 4️⃣ If count > 1: 🔹 Convert count to string 🔹 Add each digit to array 5️⃣ Continue until end 6️⃣ Return idx (new length) ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #Strings #TwoPointers #Array #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Day 44 of Daily DSA 🚀 Solved LeetCode 1572: Matrix Diagonal Sum ✅ Problem: Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Approach: Used a two-pointer technique to traverse both diagonals in a single pass. Steps: Initialize two pointers → start = 0, end = n-1 Traverse each row: Add mat[i][start] (primary diagonal) Add mat[i][end] (secondary diagonal) Move pointers: start++, end-- If matrix size is odd → add center element once ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.53 MB Optimizing nested loops into a single pass can make your solution both cleaner and faster 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 557 of #750DaysOfCode 🚀 🔥 Solved: XOR After Range Multiplication Queries II (Hard) Today’s problem really pushed my understanding of optimization and patterns in arrays. At first glance, it looks like a simple simulation—but with constraints up to 10⁵, a brute-force approach quickly breaks down. 💡 Key Learnings: Handling range updates efficiently is crucial Observed how step-based traversal (k jumps) affects time complexity Importance of modular arithmetic in large computations XOR properties helped in deriving the final result efficiently ⚡ Challenge: Each query updates elements at intervals, making it tricky to optimize without directly iterating every time. 🧠 Takeaway: Hard problems are less about coding and more about recognizing patterns and optimizing smartly. Consistency is the real game 💯 #LeetCode #DataStructures #Algorithms #CodingJourney #ProblemSolving #Java #100DaysOfCode #KeepGrinding
To view or add a comment, sign in
-
-
✨ Day 41 of 90 – Pattern Mastery Journey 🧠 Pattern:Reverse Alphabet Hash Pattern 💡 Approach: ✔ Used reverse looping (n → 1) to build the pattern ✔ Printed alphabets using ASCII logic `(char)('A' + i - 1)` ✔ Printed alphabet `i` times in each row ✔ Filled remaining positions with `#` using `(n - i)` ✔ Maintained proper structure and alignment 🚀 This problem helped me understand how reversing loops can change the entire pattern structure and improve control over output formatting. #PatternMasteryJourney #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode — Problem 5 | Day 12 💡 Problem: Longest Palindromic Substring --- 🧠 Problem: Given a string "s", find the longest substring that is a palindrome. --- 🧠 Approach (Expand Around Center): - Treat each character as a center - Handle two cases: • Odd length → (i, i) • Even length → (i, i+1) - Expand outward while characters match - Track the maximum length substring 👉 Key idea: expand from center instead of checking all substrings --- ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(1) --- 🔍 Insight: A palindrome expands symmetrically from its center --- ⚖️ Edge Cases: - Empty string → return "" - Single character → same character - Even length palindrome (e.g., "bb") - Entire string is a palindrome --- 🔑 Key Learning: - Avoid brute force O(n³) - Efficient pattern: Expand Around Center #LeetCode #DSA #Java #Palindrome #CodingJourney
To view or add a comment, sign in
-
-
Video 5 of the RISC-V in SystemVerilog series is live! Previously, we built 14 Python modules to create a complete software model of the RV32I architecture. Now, we are converting those modules one by one into equivalent, synthesizable SystemVerilog. In this video, we are tackling our first hardware block: the Write-Back Multiplexer. We zoom in on the microarchitecture, translate our Python Golden Model into RTL, and look at 4-state logic types and vector ports. Most importantly, we cover the "Latch Trap"- why missing a default statement forces the synthesis tool to build unintentional sequential memory elements in your design. Link to the video is available in the comments. You don't need a channel membership to watch this one; dive right in :-)
To view or add a comment, sign in
-
-
🚀 Mastering Sliding Window Technique in DSA Recently, I worked on an important problem: Maximum Sum Subarray of Size K — a classic example that highlights the power of optimization in problem-solving. 🔍 Approach Breakdown: Started with the brute force approach (O(N × K)), recalculating sums for every subarray. Optimized it using the Sliding Window Technique, reducing the time complexity to O(N). Leveraged the idea of reusing previous computations instead of recalculating from scratch. 💡 Key Insight: Instead of recomputing the sum for every subarray, we subtract the outgoing element and add the incoming element: Efficient thinking leads to efficient coding. 📈 What I Learned: Importance of identifying patterns like fixed-size windows How small optimizations significantly improve performance Writing clean and efficient logic for real-world problem solving This problem strengthened my understanding of array manipulation and optimization techniques commonly asked in coding interviews. #DataStructures #Algorithms #Java #CodingInterview #LeetCode #ProblemSolving #SlidingWindow #100DaysOfCode
To view or add a comment, sign in
-
-
✨ Day 42 of 90 – Pattern Mastery Journey 🧠 Pattern : Alphabet Hash Pattern 💡 Approach: ✔ Created an n × n matrix using nested loops ✔ Printed alphabets only when row index equals column index (i == j) ✔ Filled all other positions with `#` ✔ Used ASCII logic `(char)('A' + i - 1)` to generate characters 🚀 This problem helped me understand how **diagonal conditions work in matrices** and how simple conditions can create clean structured patterns. #PatternMasteryJourney #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 72 ✅ — Longest Palindromic Substring (LC #5) This one looked simple. It wasn't. My first instinct was DP. Big table, fill diagonals, track the max. It works — but O(n²) space and honestly more code than needed. Then I remembered: every palindrome expands outward from a center. So instead of building a table, I just picked each character as a potential center and expanded left/right as long as the characters matched. Two cases to handle: → Odd length palindromes: center is one character (i, i) → Even length palindromes: center is between two characters (i, i+1) That's it. No DP. No extra space. Same time complexity, half the headache. Runtime: 0 ms 🔥 — The pattern that clicked for me: If you're thinking about palindromes and reach for DP first — pause. Ask yourself: can I just expand from each center? Nine times out of ten, that's the cleaner path. — Day 71 → Arrays done Day 72 → Strings in progress Slow and steady. 💪 #DSAChallenge #Day72of365 #LeetCode #Java #Strings #CodingJourney #BackendDeveloper
To view or add a comment, sign in
-
More from this author
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