📌 LeetCode Daily Challenge — Day 4 Problem: 1582. Special Positions in a Binary Matrix Topic: Array, Matrix 🧠 Approach (Simple Thinking): 🔹 A position is special only if it holds a 1 that is alone in its entire row AND its entire column 🔹 Checking row and column for every cell separately is slow and repetitive 🔹 So we pre-compute rowSum and colSum in one pass before making any decisions 🔹 rowSum[i] == 1 means no other 1 exists in that row 🔹 colSum[j] == 1 means no other 1 exists in that column 🔹 If mat[i][j] == 1 and both sums equal 1 — that's your special position 🔹 Preprocessing once and reusing is the real trick here ⏱️ Time Complexity: Two passes through the full matrix → O(m × n) Every cell is visited exactly twice, nothing more 📦 Space Complexity: Two small arrays for row and column sums → O(m + n) No recursion, no extra grid, just two lightweight arrays doing all the work I wrote a full breakdown with dry run, analogy and step by step code walkthrough here: https://lnkd.in/gFgQxQRP If you approached this differently or have a cleaner way to think about it, drop it in the comments — always curious to see different perspectives 💬 See you in the next problem 👋 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
LeetCode Day 4: Special Positions in Binary Matrix
More Relevant Posts
-
🚀 Day 30of LeetCode Odd Even Linked List — Clean Pointer Manipulation! Just solved a really interesting linked list problem that tests how well you understand pointer manipulation 👇 🔹 Problem: Rearrange a linked list such that all nodes at odd indices come first, followed by nodes at even indices — while maintaining their relative order. 👉 Example: Input: 1 → 2 → 3 → 4 → 5 Output: 1 → 3 → 5 → 2 → 4 💡 Key Insight: Instead of using extra space, we can split the list into: an odd-index list an even-index list Then simply connect them at the end! 🧠 Approach: Maintain two pointers: odd and even Keep track of evenHead Rearrange links in one traversal Attach even list after odd list ⚡ Complexity: Time: O(n) Space: O(1) (in-place) 🎯 What I learned: Mastering linked lists is all about pointer control Problems that look tricky often have simple in-place solutions Always think in terms of structure, not values #LeetCode #DataStructures #LinkedList #Java #CodingInterview #100DaysOfCode #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 78 / 100 – LeetCode Daily Challenge 🧠 Problem: Triconic Subarray Maximum Sum 📅 Date: March 7, 2026 🏆 Runtime: 3 ms | Beats 99.94% 📦 Memory: 95.28 MB | Beats 46.16% 📝 Problem Insight Today’s challenge was to find the maximum sum of a triconic subarray – a sequence that first decreases, then increases, and finally decreases again. It’s like a "mountain" with two peaks and one valley in between, but in a specific order: down → up → down. This is a more complex variant of the classic mountain or bitonic subarray problems. It requires careful scanning of the array to detect valid triconic patterns and compute their sums efficiently. 💡 My Approach I used a two-pointer expansion method: Iterate through the array and treat each index as a potential peak or valley. Expand left and right while the pattern matches the triconic property. Keep track of the maximum sum encountered. Although the code snippet is incomplete here, the full solution involves: Precomputing left and right decreasing/increasing trends. Validating the three-phase pattern for each possible center. Avoiding redundant computations to keep the time complexity close to O(n). 📊 Results ✅ 861 / 861 test cases passed ⚡ Runtime: 3 ms (beats 99.94% of Java submissions) 📈 Memory: 95.28 MB (beats 46.16%) 🧠 Key Takeaway Pattern recognition problems like this one are great for sharpening your array traversal logic and understanding how to break down complex patterns into manageable checks. The challenge is not just in finding the sum, but in ensuring the pattern holds throughout. 🔗 Let’s Connect! I’m documenting my #100DaysOfCode journey every day – follow along for more problem-solving insights, optimizations, and LeetCode grind! 💻⚡ #LeetCode #Java #CodingChallenge #100DaysOfCode #Day78 #TriconicArray #ProblemSolving #TechJourney #SoftwareEngineering #Algorithms #DataStructures #CodeNewbie #DevCommunity #Programming
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
-
-
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 32 of #75DaysofLeetCode 🚀 LeetCode 2130 – Maximum Twin Sum of a Linked List Another day, another clean Linked List trick 💡 🔍 Problem Insight: In a linked list of even length, each node has a twin: First ↔ Last Second ↔ Second Last …and so on We need to find the maximum twin sum. 🧠 Key Idea (Interview-Ready Approach): Instead of using extra space, we: 1️⃣ Find the middle of the list (slow & fast pointers) 2️⃣ Reverse the second half 3️⃣ Traverse both halves and compute the twin sums ⚡ Why this approach? ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) (No extra memory!) 💯 Clean and optimal solution 📌 Example: Input: 1 → 2 → 3 → 4 Twin sums: (1+4)=5, (2+3)=5 👉 Output: 5 🔥 Takeaway: This problem is a perfect example of combining: Two pointers In-place reversal Space optimization 💬 Have you solved this using a different approach? Let’s discuss below 👇 #LeetCode #DataStructures #LinkedList #Java #CodingInterview #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 25 of my #100DaysOfCode Journey Today, I solved the LeetCode problem Valid Perfect Square. Problem Insight: Given a positive integer, the task is to determine whether it is a perfect square without using built-in functions like sqrt(). Approach: Used Binary Search to efficiently find whether a number has an integer square root. Initialized search range from 0 to num Calculated mid and checked mid * mid If equal → return true If square is smaller → move right (low = mid + 1) If square is larger → move left (high = mid - 1) Used long for multiplication to avoid overflow issues. Time Complexity: O(log n) — efficient binary search approach Takeaway: Binary Search is not just for arrays — it can be applied to mathematical problems to optimize performance and avoid brute force. #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #BinarySearch
To view or add a comment, sign in
-
-
🚀 Daily LeetCode Challenge – Day 37 Today’s problem was Find All Possible Stable Binary Arrays I. Problem: We are given three integers zero, one, and limit. We need to count the number of stable binary arrays such that: The array contains exactly zero number of 0s. The array contains exactly one number of 1s. Any subarray with size greater than limit must contain both 0 and 1. In simpler terms, we cannot place more than limit consecutive 0s or 1s, otherwise the array becomes unstable. The brute force that came to mind: Generate all possible arrays using the given number of 0s and 1s and then check if they satisfy the limit condition. But this approach quickly becomes inefficient because the number of combinations grows rapidly. 💡 Better Idea – Dynamic Programming with Memoization First, we focus on the limit. The limit tells us the maximum number of identical elements that can appear consecutively. For example, if limit = 2, then sequences like [0,0,0] or [1,1,1] are not allowed because they contain more than two identical elements in a row, which would make the array unstable. To construct valid arrays, we add elements in blocks: ->If the last placed element was 1, the next block must contain 0s. ->If the last placed element was 0, the next block must contain 1s. ->The size of each block can range from 1 to min(remaining elements, limit). This ensures that: we never exceed the number of remaining 0s or 1s we never violate the limit constraint. We recursively explore all valid possibilities while keeping track of: ->remaining 0s ->remaining 1s ->the last placed element. To avoid recomputation, we store previously computed results in a DP table. ⚡ Time Complexity: O(zero × one × limit) ⚡ Space Complexity: O(zero × one) 🔍 Key Insight: Instead of generating all binary arrays, we construct them step by step while respecting the limit constraint and store intermediate results, which turns an exponential brute force solution into an efficient dynamic programming approach. #LeetCode #DailyCodingChallenge #Java #DynamicProgramming #Algorithms #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 26 Problem: 3548. Equal Sum Grid Partition II Topic: Array, Matrix, Prefix Sum, HashSet, Greedy 📌 Quick Problem Sense: You're given an m × n integer grid. Make one straight cut, horizontal or vertical to split it into two non-empty parts with equal sums. The twist? You're allowed to remove at most one border element (right at the cut edge) from either side to balance the sums. Return true if such a partition is possible! 🧠 Approach (Simple Thinking): 🔹 Compute the total sum of the grid upfront 🔹 Scan row by row, maintain a running top sum, derive bottom = total - top 🔹 The imbalance is diff = top - bottom 🔹 A cut is valid if: diff == 0 → already perfectly balanced ✅ diff equals a corner cell of the top section ✅ diff equals the left-border cell of the current bottom row ✅ diff exists in a HashSet of all values seen so far ✅ 🔹 Use a HashSet to track all border values already scanned, O(1) lookup to check if removing one element fixes the imbalance 🔹 For vertical cuts → simply transpose the matrix and reuse the same horizontal cut logic! 🔹 Also try reversed row order to cover cuts scanned from the opposite direction, 4 passes total, all reusing the same function 🔄 ⏱️ Time Complexity: 4 passes through the grid (original, reversed, transposed, transposed+reversed) → O(m × n) Single scan per pass, HashSet lookups in O(1) — clean and efficient! 📦 Space Complexity: HashSet of seen values → O(m × n) worst case Transpose grid → O(m × n) Overall → O(m × n) I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/g2FHaT4S If you solved it by explicitly enumerating only the border cells, or used a different balance-check trick, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving #Programming
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 546 of #750DaysOfCode🚀 🔥 Solved: Check if Strings Can be Made Equal With Operations I (LeetCode Easy) 💡 Problem Insight We are allowed to swap characters at indices where: 👉 j - i = 2 This means: Index 0 ↔ 2 (even positions) Index 1 ↔ 3 (odd positions) 🚫 But we cannot mix even and odd indices 🧠 Key Observation The string is divided into 2 independent groups: Even indices → (0, 2) Odd indices → (1, 3) 👉 We can rearrange within each group freely 👉 So both groups must match between s1 and s2 ⚡ Approach Extract characters: Even indices from both strings Odd indices from both strings Sort both groups Compare: Even parts must match Odd parts must match 📈 Complexity Time: O(1) Space: O(1) 💬 Key Takeaway Sometimes problems look like string manipulation, but the real trick is: 👉 Understanding constraints → grouping → independent transformations 🔁 Consistency check ✔️ Another day, another step forward 🚀 #LeetCode #DataStructures #Algorithms #Java #CodingChallenge #ProblemSolving #100DaysOfCode #Consistency
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