🗓 Day 7 / 100 – #100DaysOfLeetCode 🔢 Problem 2536: Increment Submatrices by One Today’s challenge involved processing multiple submatrix increment queries on an n x n matrix, initially filled with zeros. 🧠 My Approach Instead of updating every cell inside each submatrix (which would be too slow for up to 10⁴ queries), I used a row-wise difference array technique. For each query [r1, c1, r2, c2]: Increment prefix[row][c1] Decrement prefix[row][c2+1] (if within bounds) This allows efficient marking of increments. Later, prefix-summing each row reconstructs the final matrix. ⏱ Time Complexity O(q × n) where q = number of queries (We touch r2 - r1 + 1 rows per query) 💾 Space Complexity O(n²) for the prefix matrix #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
Increment Submatrices by One with Row-Wise Difference Array
More Relevant Posts
-
🗓 Day 3 / 100 – #100DaysOfLeetCode 📌 Problem 1252: Cells with Odd Values in a Matrix The task was to determine how many cells in a matrix have odd values after performing a series of row and column increment operations. 🧠 My Approach: Instead of updating the entire matrix (which would be inefficient), I tracked the number of increments for each row and column separately using two arrays. Then, for every cell, I checked if the sum of its corresponding row and column increments was odd — if yes, I counted it. 📈 Key Insight: No need to maintain the full matrix. Just track row and column increments — the sum determines parity. Time complexity: O(m × n) Space complexity: O(m + n) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
📌 Day 38/100 – Make array elements equal to zero (LeetCode 3354) 🔹 Problem: Given an integer array nums, each element can be a number or zero. You need to find how many zeros in the array can be replaced by either +1 or -1 such that the total sum on both sides of that zero (left and right) remains balanced or differs by 1. 🔹 Approach: First, calculate the total sum s of all elements. Maintain a prefix sum l as you iterate. For each zero: If l * 2 == s, both +1 and -1 replacements are valid → add 2 to ans. If |l * 2 - s| == 1, only one replacement is valid → add 1 to ans. Return the total count ans. 🔹 Key Learning: Prefix sums simplify balance-based problems. Comparing 2 * prefixSum with total sum helps quickly check left-right equilibrium. 🔹 Complexity: Time: O(n) — single pass through array Space: O(1) — no extra storage used 🔹 Hashtags: #Day38Of100 #LeetCode3354 #100DaysOfCode #Java #DSA #ProblemSolving #PrefixSum #CodingChallenge
To view or add a comment, sign in
-
-
Day 13: 50. Pow (x, n) Problem: Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Simply multiplying the numbers can increase time usage and even space. Hence the simpler one: In order to improve efficiency we will opt for Binary Exponentiation using which we can calculate xn using O log2(N) multiplications. Basic Idea is to divide the work using binary representation of exponents i.e. is to keep multiplying pow with x, if the bit is odd, and multiplying x with itself until we get 0. Time Complexity: O(log2(n)) Space Complexity: O(1) Approach name: Binary Exponentiation #Java #ProblemSolving #DSA #100DaysofDSA #dailychallenge #BinaryExponentiation #LeetCode
To view or add a comment, sign in
-
-
🚀 Just Solved LeetCode #124 — Binary Tree Maximum Path Sum 📘 Problem: Given the root of a binary tree, return the maximum path sum of any non-empty path. A path can start and end at any node, and it’s the sum of all node values along that path. Example: Input → [1,2,3] Output → 6 Explanation → The optimal path is 2 → 1 → 3 with a sum of 6. 🧠 My Approach: I used a recursive DFS (Depth First Search) to calculate the maximum gain from each node: 1️⃣ For each node, calculate the maximum path sum including its left and right subtrees. 2️⃣ Compare the sum of the current path with the global maximum (`maxSum`). 3️⃣ Return the max gain that can be extended to the parent node (node value + max of left/right gain). 4️⃣ Used `Math.max()` to ensure negative paths don’t reduce the result. 💡 What I Learned: ✅ Importance of returning gain vs total path sum in recursive tree problems ✅ How to handle global state (`maxSum`) in recursion ✅ Deepened understanding of DFS-based tree traversal and dynamic recursion logic #LeetCode #Java #DSA #BinaryTree #CodingJourney
To view or add a comment, sign in
-
-
🚀#PostLog34 🔹 LeetCode 1901: Find a Peak Element II Problem was focused on efficiently finding a peak element in a 2D grid — one that’s greater than all its adjacent cells (top, bottom, left, and right). 💡 Concept learned: Instead of scanning the entire grid, a binary search on columns helps reduce time complexity to O(m log n). For each middle column, find the global maximum element, then decide which side to move based on neighboring values — simple yet powerful divide-and-conquer logic. ✅ 58/58 test cases passed ⚡ Runtime: 0ms | Beats 100% of Java submissions Each problem reinforces how algorithmic thinking and optimization go hand-in-hand — step by step toward sharper logic and cleaner solutions. #LeetCode #Java #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🔹 Day 47: Find Pivot Index (LeetCode #724) 📌 Problem Statement: Given an array of integers nums, the pivot index is the index where the sum of all numbers to the left is equal to the sum of all numbers to the right. If no such index exists, return -1. If multiple exist, return the leftmost one. ✅ My Approach: I first calculated the total sum of the array, then iterated through each element keeping track of the left sum. At each index, I checked whether left sum == total sum - left sum - current element. If true, that index is the pivot index. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 0 ms (Beats 100%) Memory: 45.41 MB (Beats 66.27%) 💡 Reflection: This problem strengthened my understanding of prefix sums and efficient single-pass array traversal. A clean and optimized logic! 💪 #LeetCode #Java #Arrays #PrefixSum #100DaysOfCode #Day47
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 73 String Manipulation Problem: Valid Anagram (LeetCode #242) Task: Given two strings s and t, return true if t is an anagram of s, otherwise false. Example: Input: s = "anagram", t = "nagaram" → Output: true Input: s = "rat", t = "car" → Output: false My Approach:- Method 1 – Sorting Converted both strings into character arrays. Sorted them and compared if equal, they’re anagrams! Time Complexity: O(n log n) Method 2 – Frequency Count (Optimized) Counted occurrences of each character in s and t. If every count matches, it’s a valid anagram. Time Complexity: O(n) | Space: O(1) String problems may look simple, but optimizing from sorting to counting makes a huge difference. Small logic shifts often lead to big performance gains! #100DaysOfCode #Java #ProblemSolving #LeetCode #CodingJourney #takeUforward #DataStructures #Algorithms #StringManipulation #GeeksForGeeks #CodeNewbie
To view or add a comment, sign in
-
-
🚀Day 42/100 - Problem of the day :- Count the Number of Substrings With Dominant Ones. 🎯 Goal:- Solved another interesting LeetCode problem and improved my understanding of prefix-based logic for substring counting. 💡 Core Idea:- The approach uses a prefix tracking array to store the last seen index of '0'. Using this information, we efficiently compute the number of valid substrings ending at each position—without re-checking previous characters. 📌 Key Takeaway:- Efficient solutions come from observing patterns in the input string and leveraging previously computed states. This helps reduce repetitive work and significantly improves performance. 🧠 Time Complexity:- O(n) — We traverse the string once and compute results in a single pass. 💾 Space Complexity:- O(n) — For storing prefix array to track last valid index. #100DaysChallenge #Java #DSA #Day42 #CodingJourney #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 77 Delete in a Doubly Linked List Problem: Given a doubly linked list and an integer x, remove the node at position x (1-indexed) and return the head of the updated list. Example: Input: 1 <-> 2 <-> 3 <-> 4, x = 3 Output: 1 <-> 2 <-> 4 My Approach: 1️⃣ Handled edge cases deleting the head or an empty list. 2️⃣ Traversed to the node at position x. 3️⃣ Updated both prev and next pointers to unlink the node cleanly. Time Complexity: O(N) Space Complexity: O(1) Understanding pointer manipulation in linked lists builds the foundation for mastering advanced data structures. Every prev and next link matters! #100DaysOfCode #Java #ProblemSolving #DSA #GeeksforGeeks #LinkedList #Pointers #TakeUForward #CodeNewbie #CodingJourney
To view or add a comment, sign in
-
-
🚀Day 41/100 - Problem of the day :- Increment Submatrices by one. 🚀 Goal Solved the Range Add Queries problem efficiently using the 2D Difference Array technique to ensure optimal performance for large inputs. 💡 Core Idea Instead of updating every cell in each query (which is costly), I used a difference matrix to mark only the boundaries of updates. After processing all queries, applying prefix sums row-wise and column-wise gives the final updated grid in O(n²) time. 📘 Key Takeaway Difference Array drastically reduces computation for range updates •Efficient approach matters more than brute force •Precise boundary handling → clean & optimal solution •Understanding prefix sums is a game changer in matrix problems 🧮 Time Complexity •Building difference matrix: O(Q) •Final prefix sum construction: O(n²) 👉 Total: O(n² + Q) 📦 Space Complexity Used an additional n × n difference matrix 👉 O(n²) #100DaysChallenge #Java #DSA #Day41 #Leetcode #ProblemSolving #CodingJourney
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