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
Solved "Largest Rectangle in Histogram" with Monotonic Stack in Python
More Relevant Posts
-
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
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
-
-
🧩 Day 42 — Add Digits (LeetCode 258) 📝 Problem Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. 🔁 Approach -Continuously sum the digits of the number until a single-digit result remains. -Alternatively, use the digital root formula: -If num == 0, return 0. -Else, return 1 + (num - 1) % 9. 📊 Complexity -Time Complexity: O(1) -Space Complexity: O(1) 🔑 Concepts Practiced -Mathematical optimization -Modulo operation -Digital root pattern #Leetcode #python #DSA #ProblemSolving #Math #Optimization
To view or add a comment, sign in
-
-
🚀 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 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
-
-
✅ 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 96 of My #100DaysOfCode Challenge Today’s problem: LeetCode 3432 – Count Partitions with Even Sum Difference ⚙️ 📘 Problem Statement: Given an integer array nums, we need to count the number of ways to partition it into two non-empty parts such that the difference between their sums is even. ✅ Approach: Calculate the total sum of the array. Traverse the array while maintaining a running left sum. At each partition index, compute the right sum = totalSum - leftSum. Check if (leftSum - rightSum) is even → if yes, increase the count. 💻 Time Complexity: O(n) 🧠 Space Complexity: O(1) 🔥 Key Learnings: Strengthened understanding of prefix sums Practiced modular arithmetic in array partitions Improved analytical thinking on even-odd relationships #LeetCode #Python #CodingChallenge #100DaysOfCode #ProblemSolving #DataStructures #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
Day 36 / 100 – Longest Palindromic Substring (LeetCode #5) Today’s challenge focused on String Manipulation — finding the longest palindromic substring within a given string. At first, it felt tricky to handle all the possible substrings, but then I learned to expand around the center, checking for symmetry on both sides. This approach makes the solution both logical and efficient. This problem reinforced how clarity in logic often comes from recognizing patterns, and that even complex problems can be broken into smaller, mirror-like checks. 🔍 Key Learnings Expanding around the center efficiently checks for palindromes in O(n²) time. Always consider both even and odd length palindromes. String problems often rely on clear thinking more than heavy algorithms. 💭 Thought of the Day Problem-solving isn’t about rushing for the answer — it’s about exploring the structure of the challenge. Palindromes taught me patience, symmetry, and the art of looking for balance in both logic and code. 🔗 Problem Link: https://lnkd.in/gSe-ygD8 #100DaysOfCode #Day36 #LeetCode #Python #StringManipulation #ProblemSolving #Algorithms #CodingChallenge #CleanCode #CodeEveryday #LearningJourney #DataStructures #Optimization
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
-
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
consistency at its peak ! Great 👏