🚀 LeetCode Challenge Complete! Just solved "Increment Submatrices by One" - a perfect demonstration of the difference array technique for efficient range updates! 💡 Solution Approach: ✅ Phase 1 - Mark boundaries: For each query, add +1 at start column, -1 after end column ✅ Phase 2 - Prefix sum: Accumulate row-wise to get final values ✅ Optimization: Instead of updating entire submatrix, just mark endpoints! The key insight: This is the classic difference array pattern! Instead of incrementing every cell in a range, we mark the boundaries: - Add +1 at the start of the range - Add -1 just after the end of the range - Then do prefix sum to "materialize" the actual values Why it works: Without optimization: Update every cell in [c1, c2] for rows [r1, r2] → O(rows × cols) per query With difference array: Mark 2 positions per row → O(rows) per query Final prefix sum: O(n²) once at the end Example: Range [1,2] in row 0 - Before prefix: [0, +1, 0, -1, 0] - After prefix: [0, 1, 1, 0, 0] ✓ Time: O(q×n×n) → O(q×n + n²) | Space: O(n²) #LeetCode #DifferenceArray #CPlusPlus #Algorithms #SoftwareEngineering #ProblemSolving #RangeUpdate #Optimization
Solved "Increment Submatrices by One" with difference array technique
More Relevant Posts
-
🚀 Day 93 of My #100DaysOfCode Challenge! Today, I explored one of the most fundamental and elegant problems in Binary Trees — the Diameter of a Binary Tree 🌳 using C++. The goal of this problem is to find the longest path between any two nodes in a binary tree. This path may or may not pass through the root. To solve it efficiently, I used recursion and the concept of tree height. 💡 What I Learned: 🔹 Height Function: The height of a node is 1 + max(height(left), height(right)). I built a recursive function height(TreeNode* root) that returns the height of any subtree. 🔹 Diameter Function: For each node, I calculated three possible diameters: Diameter of the left subtree Diameter of the right subtree Diameter passing through the current node (left height + right height) The maximum of these three gives the current diameter. 🔹 Key Insight: This approach uses recursion twice (once for height and once for diameter), which makes it O(N²) — a good starting point for understanding the logic before optimizing it to O(N) with a single traversal. 🧠 Concepts Strengthened: Recursive Tree Traversal Depth & Height calculation Problem decomposition using subproblems Understanding tree structure visualization 🌱 Slowly mastering trees — one recursive function at a time! Next step: Optimize the diameter function for O(N) time complexity using a single DFS call. #Day93 #100DaysOfCode #CPlusPlus #DSA #BinaryTree #Recursion #ProblemSolving #CodingJourney #LeetCode
To view or add a comment, sign in
-
-
Solved LeetCode Problem #22: Generate Parentheses, a classic example of using backtracking and recursion to generate valid combinations. The problem reinforced how powerful state tracking can be — deciding when to add an opening or closing parenthesis based on previous choices ensures every combination remains valid. What I really enjoyed about this problem is how it visually represents the beauty of recursion — every path explores a new possibility, but only valid paths make it to the final answer. 🔍 Key Takeaways: Backtracking is not about brute force, but smart exploration. Maintaining the right balance between open and close parentheses is the core idea. Visualizing recursion as a decision tree really helps in understanding the flow. It’s one of those problems that looks simple on the surface but beautifully demonstrates how clean logic can solve complex combinations. #LeetCode #Cplusplus #Backtracking #Recursion #ProblemSolving #DSA #CodingJourney #LogicBuilding
To view or add a comment, sign in
-
-
🔢 Day 69 of #100DaysOfCode 🔢 🔹 Problem: Maximum Count of Positive and Negative Integers – LeetCode ✨ Approach: A simple yet powerful one-pass solution! Iterated through the array, counting positives and negatives separately — and returned whichever count was greater. Clean, direct, and efficient. ⚡ 📊 Complexity Analysis: Time Complexity: O(n) — single traversal of the array Space Complexity: O(1) — no extra data structures used ✅ Runtime: 1 ms (Beats 12.27%) ✅ Memory: 46.89 MB 🔑 Key Insight: Sometimes, simplicity wins — clarity in logic often outperforms complex tricks. Counting right leads to coding right! 💡 #LeetCode #100DaysOfCode #ProblemSolving #DSA #Array #AlgorithmDesign #LogicBuilding #CodeJourney #ProgrammingChallenge #CodingDaily #Efficiency
To view or add a comment, sign in
-
-
🚀 Day 18 of my 120 Days of LeetCode Challenge 📘 Problem 18: 4Sum Difficulty: Medium 🧩 Problem Statement: Given an integer array nums of length n, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n a, b, c, and d are distinct nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order. Example: Input: nums = [1, 0, -1, 0, -2, 2], target = 0 Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] 💡 Approach Used: To solve this problem efficiently, I used a combination of sorting and the two-pointer technique (an optimized version of the 3Sum approach): Sort the array to handle duplicates and simplify traversal. Fix two numbers using two nested loops. For the remaining two numbers, apply the two-pointer approach (left and right) to find pairs that make up the target sum. Skip duplicates for all four numbers to ensure only unique quadruplets are added to the result. Use long long to avoid integer overflow when numbers are large. This structured and optimized method ensures that all valid quadruplets are found without redundancy. ⏱️ Time Complexity: O(n³) → Sorting takes O(n log n), and the nested loops with two-pointers make it cubic overall. 💾 Space Complexity: O(1) (excluding the result storage) since only pointers and a few variables are used. ✨ Key Takeaway: This problem builds upon the logic of 3Sum and extends it to a higher combination level, helping improve understanding of multi-pointer techniques and nested search optimizations. #LeetCode #Day18 #4Sum #C++ #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #TwoPointer #Sorting #Programming
To view or add a comment, sign in
-
-
Day 22 of #100DaysOfCode Today I solved the “Permutation in String” problem on LeetCode — a tricky one that really sharpens your understanding of sliding window and frequency mapping in strings. 🧩 Problem in short: Given two strings s1 and s2, the task is to check if any permutation of s1 exists as a substring in s2. At first glance, it feels like a brute-force problem — generate all permutations of s1 and check each in s2. But that’s computational suicide for longer strings. So the challenge was to find a smarter, optimized approach. ⚙️ Intuitive Approach: Instead of generating permutations, I focused on character frequencies. Maintain two frequency arrays — one for s1 and one for the current window of s2. Slide the window across s2, adding and removing characters as you move. Whenever both frequency arrays match, it means that substring of s2 is a permutation of s1. This approach reduces the complexity drastically and relies on pattern recognition through frequency matching, not brute force. Every day in this challenge is a reminder that optimization isn’t about doing less work — it’s about doing the right work. #LeetCode #C++ #ProblemSolving #DSA #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
💻 #2DayOf150 — Remove Duplicates from Sorted Array II (LeetCode #80) Day 2 and still going strong 💪 Today was all about keeping things clean and minimal — both in code and logic. After a solid dry run session, the entire idea just clicked. The two-pointer trick felt like magic once I saw how it limits duplicates perfectly in place ✨ 🧩 Approach Use one pointer to place valid elements Allow only up to 2 occurrences of each number In one pass, the array gets compressed beautifully ✅ Time: O(n) ✅ Space: O(1) ✅ Elegant, minimal, and efficient Dry run tested. Logic locked. Consistency on track 🔥 #DSA #LeetCode #CodingJourney #ProblemSolving #Cplusplus #100DaysOfCode #2DayOf150
To view or add a comment, sign in
-
-
🎯 Day 81 of #100DaysOfCode 🎯 🔹 Problem: Reverse Only Letters – LeetCode ✨ Approach: Used a two-pointer strategy to reverse only the alphabetic characters while keeping all non-letter characters in their original positions. By moving pointers inward and swapping only when both characters are letters, the solution stays efficient and elegant! 🔄✨ 📊 Complexity Analysis: ⏱ Time Complexity: O(n) — each character visited at most once 💾 Space Complexity: O(n) — due to character array construction ✅ Runtime: 0 ms (Beats 100% 🚀) ✅ Memory: 42.96 MB 🔑 Key Insight: Sometimes, all you need is smart pointer movement — not everything needs to be reversed, only the right pieces. #LeetCode #100DaysOfCode #DSA #TwoPointers #StringManipulation #ProblemSolving #CleanCode #AlgorithmDesign #CodingChallenge
To view or add a comment, sign in
-
-
🚀 How I Solved LeetCode’s Word Search Problem Without DFS or Recursion When I came across Word Search (LeetCode 79), I noticed that almost every solution used DFS and backtracking. But I wanted to solve it my own way — using index tracking and adjacency logic instead of recursion. My intuition was simple: If a word exists in the grid, every next letter must lie right next to the previous one — either up, down, left, or right. That means their coordinate difference should satisfy: abs(x1 - x2) + abs(y1 - y2) == 1. This small observation became the foundation of my entire approach. 💡 My Thought Process 1️⃣ I mapped every letter in the grid to its coordinates. 2️⃣ I started from all positions of the first letter in the word. 3️⃣ For every next letter, I checked which positions are adjacent and not already used. 4️⃣ I extended paths step by step — no recursion, only iteration. 5️⃣ If any path reached the last letter → the word exists. ⚙️ My Implementation I used a BFS-style iterative search, where each state holds: the current cell (x, y) the current index in the word and a bitmask representing already-used cells. This replaced recursion and heavy visited[][][] arrays with a compact integer mask. Each move just extended to adjacent cells if the next character matched. It handled tricky cases like "ABCB" perfectly → returned false, which even some DFS implementations fail on. ✅ Why It Worked ✔️ No recursion = no stack overflow. ✔️ Bitmask = minimal memory use. ✔️ Adjacency rule = exactly matches grid movement. ✔️ Iterative BFS = simple, efficient, and logical. 🎯 What I Learned You don’t always need to follow the standard algorithms. Sometimes, just trusting your intuition and building around your idea leads to something even better. This problem taught me that creativity and logic go hand in hand. And when you believe in your approach — it truly works. 💪 #Coding #LeetCode #ProblemSolving #Cplusplus #Innovation #DSA #Learning #DeveloperJourney
To view or add a comment, sign in
-
-
✅ Day 4/75 🌟 Today’s Progress 1️⃣ Longest Consecutive Sequence — LeetCode Medium Problem: Given an unsorted array of integers, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. 🔹Approaches: 1️⃣ Sorting Approach (Brute Force) Sorted the array and count the consecutive elements. Time Complexity: O(N log N). 2️⃣ Optimal – HashSet Stored all the numbers in a HashSet. For each number, checked if it’s the start of a sequence (i.e., num - 1 not in set). Then counted how long the consecutive sequence continues. ✅ Time: O(N) | Space: O(N) 2️⃣ Product of Array Except Self — LeetCode Medium Problem: Given an array nums, return an array answer such that answer[i] equals the product of all elements except nums[i], without using division, in O(n) time. 🔹Approaches: 1️⃣ Brute Force: Multiplied all elements except self for each index. ⏱️ Time: O(N²) 2️⃣ Optimal – Prefix & Suffix Product First pass: calculated the prefix products (product of all elements to the left). Second pass: multiplied each element by the suffix product (product of all elements to the right). ✅ Time: O(N) | Space: O(1) (excluding output array) On to Day 5 tomorrow! ✨ #NeetCode #Blind75 #DSA #LeetCode #CodingChallenge #ProblemSolving
To view or add a comment, sign in
More from this author
-
Elevating Programming Education: How Gamification Amplifies Learning Through Game Design Principles
Sajeeb Das Shuvo 2y -
Ethical Coding: Navigating Moral Dilemmas in Tech Development
Sajeeb Das Shuvo 2y -
From Side Project to Side Income: A Full Stack Developer's Guide to Passive Income Streams
Sajeeb Das Shuvo 2y
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
problem: https://leetcode.com/problems/increment-submatrices-by-one/description/?envType=daily-question&envId=2025-11-14 solution: https://github.com/sajeeb-me/leetcode-daily/blob/main/2025/november/Increment%20Submatrices%20by%20One%20%7C%20leetcode%202536