Leetcode POTD: Delete Columns to Make Sorted III So this is part 3 of the “delete columns to make it sorted” series, but with a different twist. Here, we need to delete columns in such a way that each individual string becomes sorted. It sounds easy at first, but it’s really not 😅 I initially tried a greedy approach and failed, and after a few trials, I finally reached the correct intuition. Thought process: I started by iterating over the columns, checking where the order breaks and incrementing a counter. But this greedy approach eventually failed, because there are test cases where, say, column 3 is bad (it violates the condition) with column 2, so I decide to delete it. However, that same column 3 might actually be valid with column 1, so deleting it is not optimal ❌ Also, we need to preserve the sorted order, which clearly hints towards using DP. We cannot choose a local minimum because it can negatively impact the global solution. This starts to resemble the LIS (Longest Increasing Subsequence) pattern 📈 So, using DP makes the solution feasible ✅ Overall, it’s a hard question, because identifying this intuition is difficult unless you’ve solved a lot of problems, especially string-based ones 🧠✨ 📌 Attaching my notes below, which walk through the step-by-step intuition, explain why the greedy approach fails, and how the DP (LIS-style) solution works. #coding #programming #potd #leetcode
Leetcode POTD: Delete Columns to Make Sorted III with DP
More Relevant Posts
-
🧩 LeetCode POTD: Delete Columns to Make Sorted II So, what is this problem actually asking? 🤔 We’re given a few strings, all of the same length. We’re allowed to delete columns (meaning: remove the same index from every string). After deleting, the strings as a whole should be in dictionary (lexicographic) order 📖 Our goal is to delete the minimum number of columns. 💡 Intuition When we compare two strings, we go left to right. The first character where they differ decides the order. So if at some column we find: strs[i] < strs[i+1] 👉 That pair is sorted forever ✅ No later column can change this. Because of this: We should remember which adjacent string pairs are already sorted and stop checking them again and again. ⚡ Optimization : Instead of rebuilding strings every time: Go column by column (left to right) Keep a sorted[] array sorted[i] = true → strs[i] and strs[i+1] are already in the correct order 😊 If a column breaks order for any unsorted pair......delete that column Otherwise okay, use this column to mark more pairs as sorted #leetcode #potd #problem_solving #optimization #coding
To view or add a comment, sign in
-
-
Compiler Construction sounded cool. Then I actually tried building one. I started with the first stage: a Lexical Analyzer built from scratch using C and Flex, with a Harry Potter–inspired syntax (numspell, truthcharm, beginmagic). At first, matching tokens with regular expressions felt straightforward. Then the problems started. Valid-looking code broke. Invalid code slipped through. That’s when I realized: a lexer that isn’t strict is useless. So I focused heavily on error detection and reporting, making the lexer explicitly catch: • Digit-prefixed identifiers (5abc) • Unterminated strings and comments • Invalid number formats It doesn’t just tokenize the magic — it rejects broken spells. This was my first real lesson in compilers: being precise matters more than being permissive. 🔗 GitHub Repo: https://lnkd.in/dBeeViyZ #ComputerScience #CompilerConstruction #Flex #CProgramming #CSStudent #CodingJourney
To view or add a comment, sign in
-
-
When a LeetCode "Hard" is just a classic algorithm in disguise. I just hit a 60-day streak on LeetCode! To celebrate, I tackled problem 960. Delete Columns to Make Sorted III. . . . . . . . . . . At first glance, it asks for the minimum number of columns to delete to ensure every row in a grid is sorted. It sounds complicated, but this is a perfect example of why pattern recognition is key in competitive programming. The shift in perspective: Instead of thinking about what to delete, I flipped the problem: What is the maximum number of columns I can keep? The Algorithm: This reduces perfectly to the Longest Increasing Subsequence (LIS) pattern. Standard LIS: We check if nums[j] <= nums[i] to extend a subsequence. The Modification: Here, we treat each column as an element. For column i to follow column j, the character at j must be $\le$ the character at i for every single row. Once you apply that constraint to the standard $O(N^2)$ DP approach, the solution becomes clear.Result = Total Columns - Length of LIS. It’s satisfying when a "Hard" problem turns "Easy" just by recognizing the underlying structure. Consistency pays off! #LeetCode #Algorithms #CPlusPlus #DynamicProgramming #Consistency #ProblemSolving #TCS
To view or add a comment, sign in
-
-
Leetcode POTD : Minimum ASCII Delete Sum of Two Strings Here, we need to delete minimum ASCII valued characters to make two strings equal. Intuition : 🤔 We want both strings to become the same, so we start with two pointers. If characters at both indices are equal → no deletion needed, just move ahead ✅ If characters are different, then we must delete, but the confusion is 🤯 👉 should we delete from s1 or from s2 to get the minimum cost? So we can try both options: delete from s1 delete from s2 This clearly points towards recursion 🔁 While solving recursively till the end of both strings, if you draw the recursion tree (yes, I did ✍️), you’ll notice overlapping subproblems. So why recompute? 🤷♂️ That’s where DP + memoization comes in We store results and optimize the solution efficiently. Attaching my thought process diagram below 👇 #Leetcode #POTD #DynamicProgramming #Recursion #DP #CodingJourney #programming
To view or add a comment, sign in
-
-
Day 8: Roman to Integer (Cracking the Subtractive Rule) Consistency is key! Today, I tackled the Roman to Integer challenge on LeetCode. While it looks like a simple mapping task, the real challenge lies in handling the subtractive instances (like IV = 4, not 6). 🧠 The Logic: Look-Ahead Strategy The standard rule for Roman numerals is addition. However, when a smaller numeral precedes a larger one, you subtract it. I implemented a look-ahead check: Iterate through the string character by character. If the current value is less than the next value (e.g., 'I' before 'V'), subtract the current value from the total. Otherwise, add it to the total. ⚡ Performance Results I’m thrilled with the efficiency of this solution: Runtime: 1 ms (Beats 99.77% of C# submissions!) 🚀 Memory: 49.07 MB (Beats 93.46% of C# submissions!) Time Complexity: $O(N)$ Space Complexity: $O(1)$ Sharing these daily updates keeps me accountable and hopefully helps others on their DSA journey. If you’re also practicing for interviews, let’s connect! #DSA #LeetCode #CSharp #CodingLife #Programming #ProblemSolving #SoftwareEngineer
To view or add a comment, sign in
-
In Competitive Programming, speed isn’t about typing fast ⌨️ —it’s about thinking smart 🧠⚡ Understanding time complexity vs constraints is what separates ❌ solutions that “work” from ✅ solutions that actually PASS 🏁 Because no matter how clean or elegant your code looks ✨ if it crosses the 10⁸ ops/sec limit ⏱️ 👉 TLE. Game over. 🚫💀 From O(1) 🟢 to O(n!) 🔴, knowing what’s feasible and what’s risky helps you: ✔️ Pick the right algorithm before coding ✔️ Avoid TLEs before they happen ✔️ Start thinking like a true competitive programmer 💻🔥 💡 Golden Rule of CP: 👉 Constraints decide the algorithm. 👉 Intuition comes second. 🚀 Smart thinking > brute force. Always. #CompetitiveProgramming #TimeComplexity #DSA #ProblemSolving #CP #CodingMindset #ThinkBeforeYouCode #Algorithms 🚀
To view or add a comment, sign in
-
The C "if" expression can do anything — assignments, comma-separated sequences, even multiple side effects — and the compiler quietly uses only the last value to decide the condition. It works, but it’s subtle, confusing, and can hide bugs. Rust takes a safer approach: it uses block expressions to evaluate statements left-to-right, preserves side effects, but forces the last expression to be a boolean. Flexible vs safe — the choice is clear. #CProgramming #RustLang #ProgrammingTips #CodeSafety #SystemsProgramming #SoftwareEngineering #CodeOptimization #ProgrammingLanguages #DeveloperInsights #TechTips
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Practice – Day 33 Problem: Distinct Subsequences (Dynamic Programming) Today’s problem focused on counting how many distinct ways we can form one string as a subsequence of another. Unlike normal subsequence problems, here we are not just checking existence — we are counting every valid possibility. 🎯 Core Idea We build a DP table where each state represents how many ways a prefix of one string can form a prefix of the target string. If the current characters match, we have two choices: use this character or skip it. If they don’t match, we can only skip from the larger string. This allows the count to accumulate naturally across all possible combinations. 🔍 Why This Problem Is Interesting It shows the power of DP in counting structured choices, not just finding optimal values. Brute force backtracking would explode in complexity, but DP captures all outcomes efficiently. 🧠 Key Insight Every matched character branches into multiple future possibilities. Dynamic programming helps ensure none of those paths are double-counted or missed. ⏱ Time Complexity → O(m × n) 🧠 Space Complexity → O(m × n) or O(n) with optimization 🌱 Daily Learning Takeaway Sometimes the challenge isn’t finding one answer — it’s accounting for every valid answer. DP gives a structured framework to explore them all. #leetcode #dsa #dynamicprogramming #strings #coding #learningeveryday #growthmindset #developer #problemsolving
To view or add a comment, sign in
-
Why do people find Dynamic Programming (DP) so hard? Is it the complexity? The math? The recursive depth? No. It’s because you’ve been taught to memorize "patterns" instead of understanding first principles. 🚩 DP was never meant to be learned through viral sheets and "top 50 questions." Those are just shortcuts that fail the moment the interviewer tweaks a single constraint. To me, DP = Intelligent Brute Force. That’s it. My personal style for any DP problem is dead simple: 1. Ignore the hype and figure out the correct equation of state. 2. Ensure the right order of computation to reuse what's already done. If you get those two right, the "difficulty" of the problem disappears. At the end of the day, you’re just computing states—the "magic" is just not doing the same work twice. Think of it like an IIT-standard Physics problem. Even if you haven’t opened a textbook in 6 years, you know that almost everything in mechanics boils down to F=ma. If your fundamentals are solid, you don't need to memorize a thousand scenarios—you just derive the solution from the root. When you learn ground-up, you don't fear the "Hard" tag on LeetCode. You just look for the state equation. If you’re the type of person who hates rote learning and prefers arriving at the apex naturally—I’ve found my cult. 🤝 I’m starting a DP series on YouTube to officially demystify the hype and show you how to solve these "beasts" using pure logic, not memorization. I’m also stress-testing a new platform that doubles down on this "fundamentals-first" methodology. If it actually holds up to my standards, I’ll reveal it soon. Go beyond coding, master the art of the fundamentals. CTA: What’s the one DP problem that still gives you nightmares? Let’s see if we can break it down to "Intelligent Brute Force" in the comments. 👇 ps: gen alpha in the frame, the 4 year old know to take his Papa's office mac, go to his site of interest and play games!!! #SoftwareEngineering #DynamicProgramming #DSA #CodingInterview #IIT #MasterTheArt #TechEducation
To view or add a comment, sign in
-
-
Unification: Runtime Value (Erlang) vs. Compile-Time Type (Rust) How do you ensure two separate parts of your system "agree" with each other? It comes down to what you are unifying and when you do it. 🟢 Erlang: Unification by Value (Runtime) In Erlang, unification is a dynamic check performed at the moment of execution. By reusing the same variable name (Message) in the function head, the VM enforces value equality. The function will only execute if the incoming message is identical to the one already stored in the state. This allows the system to unify actual data points on the fly at the call site. 🦀 Rust: Unification by Type (Compile-Time) In Rust, unification is a structural constraint handled during the build. By using Associated Types, you prove to the compiler that the Message and the Store share a compatible identity. You aren't checking if the IDs are the same value; you are proving they are the same type. If you try to use a "UUID-based Message" with an "Integer-based Store," the code won't even compile. #Programming #RustLang #Erlang #Haskell #ComputerScience #SoftwareArchitecture #Backend #Types
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