🚀 LeetCode + DSA — Day 20 Today I solved LeetCode 75: Sort Colors, a classic problem that strengthens in-place sorting and comparison-based logic. 🔹 Problem Overview You’re given an array containing only 0, 1, and 2, representing three different colors. The task is to sort the array in-place so that elements of the same color are adjacent and ordered as 0 → 1 → 2, without using the built-in sort function. 🔹 Approach Used ✔ Used a comparison-based in-place sorting strategy ✔ Iterated through the array and tracked the smallest element index ✔ Swapped elements to position them correctly ✔ Ensured no extra space was used 🔹 Why This Works In-place swapping avoids additional memory usage Controlled iteration guarantees correct ordering Simple logic, yet fully compliant with problem constraints 📊 Performance ✅ All test cases passed ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: Efficient in-place solution 💡 Key Takeaway Problems with strict constraints push you to think beyond library functions. Mastering in-place operations builds strong fundamentals for real-world systems where space efficiency matters. Consistent practice > complex solutions 💪 #LeetCode #DSA #Python #Arrays #Sorting #InPlaceAlgorithm #ProblemSolving #DailyCoding #CodingPractice #SoftwareDeveloperJourney #LearningByDoing
LeetCode 75: Sort Colors In-Place
More Relevant Posts
-
🚀 LeetCode + DSA — Day 22 Today I solved LeetCode 48: Rotate Image, a classic matrix manipulation problem that tests your understanding of in-place transformations. 🔹 Problem Overview Given an n x n 2D matrix, rotate the image by 90 degrees clockwise. The key constraint: the rotation must be done in-place, without using extra memory. 🔹 Approach Used ✔ First, transpose the matrix (swap matrix[i][j] with matrix[j][i]) ✔ Then, reverse each row to achieve the 90° clockwise rotation ✔ No additional matrix used — space-efficient solution 🔹 Why This Works Transposing converts rows into columns Reversing rows aligns elements in rotated order Clean logic with optimal time and space efficiency 📊 Performance ✅ All test cases passed ⚡ Time Complexity: O(n²) 💾 Space Complexity: O(1) (in-place) 💡 Key Takeaway Understanding matrix patterns can turn a seemingly complex problem into a simple two-step solution. In-place algorithms are powerful and interview-favorite concepts. Consistency > Intensity 💪 #LeetCode #DSA #Python #Matrix #InPlaceAlgorithm #ProblemSolving #DailyCoding #CodingJourney #SoftwareEngineer #TechInterview #LearningEveryday #Consistency
To view or add a comment, sign in
-
-
Day 57 of LeetCode Grind ⚡🔥 Problem: Minimum Cost to Convert String II (2977) Convert source string to target using substring replacement operations with associated costs. Find the minimum total cost. 💡 Core Insight: * This problem is a beast that combines Graph Shortest Path with Dynamic Programming and Tries. * Graph Modeling: Treat every unique substring in original and changed arrays as a node in a graph. The cost to change one substring to another is a directed edge weight. * Floyd-Warshall: Since A -> B and B -> C implies A -> C, we need the shortest path between all pairs of substrings. The number of unique substrings is small (≤ 200), so O(V³) is perfectly fine. * DP + Trie: We solve for dp[i]: the min cost to convert suffix source[i:]. At each index i, we can: > Skip if source[i] == target[i]. > Try to match longer substrings source[i:j] and target[i:j] using a Trie to quickly check if they exist in our graph. If they do, add the precomputed conversion cost + dp[j+1]. Complexity: * Graph: O(V³) where V is unique substrings count. * DP: O(N²) worst case (checking all substrings), but practically much faster due to Trie pruning. ✨ Reflection: This problem teaches us to decouple the "cost calculation" from the "string parsing." By precomputing all substring-to-substring costs first, the final DP becomes a straightforward knapsack-style problem. The Trie is the glue that makes the O(N²) substring checks efficient! #LeetCode #Day57 #GraphTheory #FloydWarshall #DynamicProgramming #Trie #Python #HardProblem #100DaysOfCode #Tech
To view or add a comment, sign in
-
-
Day 10/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 844 – Backspace String Compare (Easy) 🧠 Approach: Simulate typing using stacks and compare final strings. 💻 Solution: class Solution: def build(self, s): stack = [] for i in s: if i=="#": if stack: stack.pop() else: stack.append(i) return stack def backspaceCompare(self, s: str, t: str) -> bool: return self . build(s)==self . build(t) ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Stack-based simulation is an effective way to model real-time text editing behavior. #leetcode #dsa #python #stack #codingchallenge
To view or add a comment, sign in
-
-
hi connections I just moved from Maximum Subarrays to LeetCode 167: Two Sum II. The challenge? Find two numbers that hit a target sum. The "cheat code"? The input array is already sorted. When you see "Sorted Array," your mind should immediately go to Two Pointers. The Strategy: Left Pointer: Starts at the beginning (smallest values). Right Pointer: Starts at the end (largest values). The Logic: If the sum is too low, nudge the left pointer up. If it’s too high, slide the right pointer down. Why I love this approach: Zero Extra Space: Unlike the original Two Sum, you don’t need a Hash Map. O(1) space. Speed: You only pass through the data once. O(n) time. Simplicity: It’s clean, readable, and highly optimized. Programming isn't just about solving the problem; it's about finding the most elegant way to do it by leveraging the constraints you're given. #Coding #DataStructures #Algorithms #TwoSum #Python #LeetCode #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
hi connections Today I tackled LeetCode 485: Max Consecutive Ones. It’s a classic "Easy" problem that perfectly illustrates a fundamental concept in algorithm design: State Management. The Problem: Given a binary array, find the maximum number of consecutive 1s. The Approach: Instead of nested loops or complex data structures, this is best solved with a simple Linear Scan. Maintain a current_streak counter. Iterate through the array once—O(n) time complexity. Update a max_streak variable whenever the current streak surpasses it. Reset the counter when you hit a 0. The Engineering Takeaway: This problem is a reminder that efficiency often comes from minimizing passes. Why sort or store data when you can solve the problem in a single, elegant sweep? It’s about keeping the "state" of your application lean and only tracking what is absolutely necessary. Whether you're processing a stream of binary data or managing user session streaks in a real-world app, the logic remains the same: Stay focused on the current window, but never lose sight of the record. #LeetCode #SoftwareEngineering #CleanCode #Algorithms #DataStructures #Python #CodingInterview #ProblemSolving
To view or add a comment, sign in
-
-
Today’s focus was a LeetCode Easy problem that tests real logical discipline, not tricks. 🔹 LeetCode #9 – Palindrome Number At first glance, this looks trivial. It isn’t. The task is simple: Check whether a number reads the same forward and backward. What actually matters while solving it: Negative numbers must be rejected immediately The original value must be preserved before mutation Digits must be extracted and rebuilt correctly Loop termination has to be precise The approach I used: Reverse the number digit by digit using modulo and integer division Compare the reversed value with the original number The logic is straightforward, but any missed condition silently breaks the solution. Key takeaway: Easy problems don’t fail because of complexity. They fail because of careless edge-case handling. Alongside this, I’m also solving smaller logic-building problems focused on: Conditional branching Boundary validation Correct ordering of conditions These reinforce the same thinking from a different angle. 🔗 GitHub Repository (all solutions): 👉https://lnkd.in/d5J4MA8q #LeetCode #Python #ProblemSolving #LogicBuilding #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 LeetCode Daily Challenge – Day 10 Problem #712: Minimum ASCII Delete Sum for Two Strings (Medium) This was a really interesting Dynamic Programming + Strings problem that made me think beyond the usual edit-distance pattern. 🧭 How I Approached the Question: Instead of directly minimizing the delete cost, I flipped the perspective. 👉 If I can maximize the ASCII sum of the common subsequence between the two strings, then: The characters not in this subsequence are the ones that must be deleted The minimum delete cost = (total ASCII of s1 + total ASCII of s2) − 2 × (ASCII sum of common subsequence) So the problem becomes: ➡️ Find the maximum ASCII sum common subsequence (a weighted LCS). 🧠 Core Insight: I used a 2D DP table where: dp[i][j] represents the maximum ASCII sum of a common subsequence between s1[:i] and s2[:j] Transition: If characters match → add their ASCII value Else → carry forward the best result by skipping one character 🛠️ Why This Works: By maximizing what we keep, we automatically minimize what we delete. This reframing made the solution much cleaner and intuitive. ⏱ Time Complexity: O(n × m) 📦 Space Complexity: O(n × m) #LeetCode #DailyCoding #DynamicProgramming #Strings #ProblemSolving #DSA #Python #CodingJourney
To view or add a comment, sign in
-
-
🚀 Deep Dive into Dynamic Programming — Max Dot Product of Two Subsequences Today I worked on solving LeetCode 1458: Max Dot Product of Two Subsequences, and it turned out to be a great exercise in DP mindset + edge-case handling. What made this problem interesting wasn’t just writing the code — it was understanding why certain choices matter . Key learnings: - Dynamic Programming isn’t about memorizing formulas — it’s about defining the right state - When negatives are involved, returning 0 can be wrong — sometimes a large negative sentinel is necessary - At every step, think in terms of choices: . take both elements . skip from either array . or start fresh with the current pair - Memoization drastically reduces repeated work and improves performance 📌 The final solution uses Top-Down DP with recursion + memoization, handling all edge cases correctly and running in O(m × n) time. More than getting an accepted solution, this problem strengthened my understanding of: ✅ DP transitions ✅ Handling negative values safely ✅ Translating logic cleanly into Python Step by step, problem by problem — getting better at thinking, not just coding 💪 #DynamicProgramming #LeetCode #Python #DSA #ProblemSolving #SoftwareEngineering #LearningJourney
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