Solved LeetCode Medium – 1536. Minimum Swaps to Arrange a Binary Grid today! 💻 Instead of actually swapping rows in the grid, I optimized the solution by tracking trailing zero counts per row and performing swaps on that array. This significantly simplifies the implementation and improves readability. Approach I Followed 1. Count Trailing Zeroes in Each Row For each row in the grid, traverse from the rightmost column. Count how many continuous zeroes appear at the end of that row. Store these counts in an array zeroes[i]. Example: Row: [1,0,0,0] → trailing zeroes = 3 Row: [1,1,0,0] → trailing zeroes = 2 2. Determine Required Zeroes per Row For row i, we need at least: requiredZeroes = n - i - 1 Because every row above must have enough zeros so that all elements above the main diagonal are zero. 3. Find a Suitable Row Search for the first row j ≥ i that has enough trailing zeroes. If no such row exists → return -1 (arrangement impossible). 4. Bring That Row Up Using Adjacent Swaps Swap row j upward until it reaches position i. Each adjacent swap increases the swap count. Instead of swapping rows in the grid, swap values in the zeroes array. This simulates the required row movement efficiently. 5. Continue Until Grid is Valid Repeat for every row until all constraints are satisfied. ✅ Time Complexity: O(n²) ✅ Space Complexity: O(n) It was a great exercise in greedy thinking, array manipulation, and edge-case handling. Always satisfying to break down a tricky grid problem into a simpler representation! 🚀 #LeetCode #DSA #Java #CodingPractice #GreedyAlgorithm #ProblemSolving #SoftwareEngineering
Optimize LeetCode 1536: Minimum Swaps for Binary Grid
More Relevant Posts
-
🚀 Day 17 — Valid Parentheses Continuing the Stack pattern. 🧩 Problem solved: Valid Parentheses 💻 Platform: LeetCode (#20) Given a string containing only '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example: Input: s = "()[]{}" Output: true Input: s = "([)]" Output: false --- 🧠 First Thought (Brute Force) Repeatedly remove adjacent matching pairs like "()", "[]", "{}" until no more removals are possible. If the string becomes empty → valid. But this leads to O(n²) complexity. Clearly inefficient. --- ⚡ Optimal Approach — Stack (via StringBuilder) Key Insight: A closing bracket must always match the most recently seen opening bracket. That’s exactly what a Stack is built for — LIFO. Twist: Instead of Stack<Character>, I used StringBuilder as the stack. Same logic, lighter overhead. Steps: • Iterate through each character • If top of StringBuilder matches current closing bracket → pop (deleteCharAt) • Otherwise → push (append) • If StringBuilder is empty at end → valid Time Complexity: O(n) Space Complexity: O(n) 🔍 What this problem reinforced: ✔ Stack is the go-to structure when order + matching matters ✔ LIFO logic maps perfectly to nested bracket structures ✔ StringBuilder can simulate a stack — not just for string building! This problem made the Stack pattern click in a new way. Solutions are available here: 🔗https://lnkd.in/gW8atfqw Day-17 complete. ✅ #DSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
Day 30/30 – LeetCode streak Problem: Get Biggest Three Rhombus Sums in a Grid You need the three largest distinct border sums of all rhombuses in the grid, in descending order. Core idea * A rhombus is defined by a center '(i, j)' and a radius or edge length 'k'. * If 'k = 0', the rhombus is just the single cell itself. * For 'k ≥ 1', the rhombus must stay within the grid so that all four corners exist. Approach * For every cell in the grid, treat it as the top vertex of a rhombus, and for each possible edge length k such that all four corners stay in bounds, walk its border and accumulate the sum. * Compute the maximum possible radius that still keeps the rhombus inside the grid. * For each valid radius, walk along the four edges of the rhombus border and accumulate the sum of those cells. * Because the grid size is small (at most 50 × 50), directly enumerating all rhombuses is efficient enough. Tracking the top three * Maintain a sorted set that keeps only distinct sums. * Every time a rhombus sum is computed, insert it into the set. * If the set size becomes greater than three, remove the smallest value. * At the end, the set contains the three largest distinct sums, which can be returned in descending order. Day 30 takeaway: This problem shows that sometimes a direct enumeration works perfectly when constraints are small. Instead of over-optimizing, you can simply generate all valid shapes and maintain the best results with a small ordered set. #leetcode #dsa #java #matrix #consistency
To view or add a comment, sign in
-
-
Day 15 of my #30DayCodeChallenge: Swapping Nodes in Pairs! The Problem: Swap Nodes in Pairs. Given a linked list, the goal is to swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (only nodes themselves may be changed). The Logic: This problem is a classic exercise in Pointer Manipulation and maintaining structural integrity in a Linked List: 1. Dummy Node Strategy: I initialized a dummy node pointing to the head. This acts as a fixed anchor, ensuring I can easily return the new head of the list even after the original head has been swapped. 2. The Three-Pointer Dance: To swap two nodes (cur and t), I need ✓ nage three specific connections for every pair: **-Point the previous node (pre) to the second node of the pair (t). **- Point the first node (cur) to the node following the pair (t. next). **- Point the second node (t) back to the first node (cur). 3. Iterative Traversal: The loop continues as long as there is a full pair remaining (cur ! = nul1 && cur.next ! = null). After each swap, the pre and cur pointers shift forward to prepare for the next pair. Another step closer to mastery. Onward to Day 16! #Java #Algorithms #DataStructures #LinkedList #ProblemSolving #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 54 of #100DaysOfCode 🌱 Topic: Stack / Two Pointers ✅ Problem Solved: LeetCode 42 – Trapping Rain Water 🛠 Approach: Used a Monotonic Stack to calculate trapped water. Traversed the array and maintained a stack of indices. When current height is greater than stack top: Popped the top → this forms a “valley”. If stack becomes empty → break (no left boundary). Calculated: Height = min(left boundary, right boundary) − current height Width = distance between boundaries Added height × width to total water. Pushed current index into stack. This effectively finds water trapped between bars. #100DaysOfCode #Day54 #DSA #Stack #TwoPointers #LeetCode #HardProblems #Java #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
💡 Day 36 of LeetCode Problem Solved! 🔧 🌟11. Container With Most Water🌟 Task : You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Example 1: GInput: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: Input: height = [1,1] Output: 1 #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfChallenge #CodingJourney #KeepGrowing
To view or add a comment, sign in
-
-
Day 29/30 – LeetCode streak Problem: Fancy Sequence You need to support 'append', 'addAll', 'multAll', and 'getIndex' under modulo '(10^9 + 7)' in 'O(1)' per operation. Core idea Keep the logical sequence implicitly via a global affine transform: * Store an internal array 'vals[]'. * Maintain global coefficients 'mul = a' and 'add = b' so that for every index 'i': 'real_i ≡ a · vals[i] + b (mod M)' * Initially, 'a = 1' and 'b = 0', so the stored value equals the real value. Operations * 'append(val)' We want to store a value 'x' such that: 'a · x + b ≡ val (mod M)' Rearranging gives: 'x ≡ (val − b) · a⁻¹ (mod M)' Since 'M' is prime and 'a ≠ 0', the modular inverse 'a⁻¹' exists and can be computed using Fermat’s little theorem. * 'addAll(inc)' Adding a constant to every element changes the transform: 'a · x + b → a · x + (b + inc)' So we simply update: 'add = (add + inc) % MOD'. * 'multAll(m)' Multiplying every element scales both coefficients: 'a · x + b → (a · m) · x + (b · m)' So update: 'mul = (mul * m) % MOD' 'add = (add * m) % MOD'. * 'getIndex(idx)' If the index is out of range return '-1'. Otherwise compute the real value using the stored transform: 'real = (mul * vals[idx] + add) % MOD'. Day 29 takeaway: Instead of updating every element on each operation, using a lazy affine transformation 'a · x + b' lets you represent the entire sequence with just two parameters, turning what would normally be 'O(n)' updates into constant-time operations. #leetcode #dsa #java #math #design #consistency
To view or add a comment, sign in
-
-
🚀 Day 13/100 – LeetCode DSA Challenge 🔹 Problem Solved: 238. Product of Array Except Self Today’s problem was a great exercise in array manipulation and optimization. 📌 Problem Summary: Given an array nums, return a new array where each element is the product of all elements except itself. 📊 Example: Input: [1,2,3,4] Output: [24,12,8,6] 💡 What I Learned: How to handle edge cases like zeros in an array Importance of time complexity O(n) Why some solutions (like division) are not always valid Concept of prefix & suffix products (optimal approach) ⚠️ Challenge: Cannot use division Must solve in linear time 🧠 My Approach: First tried using total product and division Faced issues with zero values (division by zero error) Improved the logic by handling zero cases carefully 🔥 Key Insight: If there is: More than 1 zero → all outputs = 0 Exactly 1 zero → only that index gets product No zero → normal calculation works 📈 Next Goal: Learn and implement the optimal solution without division (prefix + suffix method) #Day13 #100DaysOfCode #LeetCode #DSA #Java #CodingJourney #ProblemSolving #FutureDeveloper
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 82 - LeetCode Journey 🚀 Solved LeetCode 92: Reverse Linked List II (Medium) — a powerful problem that takes basic reversal to the next level. We already know how to reverse an entire linked list. But here, the challenge is to reverse only a specific portion — between positions left and right — while keeping the rest intact. 💡 Core Idea (Partial Reversal + Pointer Rewiring): Use a dummy node to simplify edge cases Move a pointer (prev) to the node just before position left Start reversing nodes one by one within the given range Reconnect the reversed sublist back to the original list This is done using in-place pointer manipulation. 🤯 Why it works? Because instead of reversing the entire list, we carefully rewire only the required segment, preserving connections before and after the range. ⚡ Key Learning Points: • Partial reversal of linked list • Advanced pointer manipulation • Importance of dummy node in edge cases • In-place modification without extra space • Maintaining O(n) time and O(1) space This problem is a big step up from basic linked list reversal. Also, this pattern connects with: Reverse Linked List (full reversal) Reverse Nodes in k-Group Reorder List Palindrome Linked List ✅ Better control over pointer operations ✅ Strong understanding of in-place transformations ✅ Confidence with medium-level linked list problems From full reversal to selective reversal — this is real progress 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
LeetCode 2130 — Maximum Twin Sum of a Linked List This problem gives the head of a linked list with even length. For a list of size n, the iᵗʰ node and the (n−1−i)ᵗʰ node are considered twin nodes. The twin sum is defined as the sum of the values of these two nodes. The task is to return the maximum twin sum in the linked list. Example : Input : 5 → 4 → 2 → 1 Twin pairs : (5,1) → sum = 6 (4,2) → sum = 6 Output : 6 Approach used — Reverse Second Half + Twin Traversal Because twin nodes lie symmetrically from the start and end, the list can be processed efficiently by reversing half of it. Two main steps are used during traversal. • First, fast and slow pointers are used to locate the middle of the linked list. - slow moves one step at a time. - fast moves two steps at a time. When fast reaches the end, slow will be positioned at the start of the second half. • The second half of the list is then reversed so that twin nodes align during traversal. After reversing : - One pointer starts from the beginning of the list. - Another pointer starts from the reversed second half. At each step : - The twin sum is calculated. - The maximum twin sum is updated. This approach works in O(n) time and O(1) extra space. #leetcode #datastructures #linkedlist #java #problemSolving
To view or add a comment, sign in
-
Explore related topics
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