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
LeetCode 1572: Matrix Diagonal Sum Optimization
More Relevant Posts
-
Day 48 of Daily DSA 🚀 Solved LeetCode 48: Rotate Image ✅ Problem: Given an n x n matrix, rotate the image by 90° clockwise — in-place (without using extra space). Approach: Used a two-step transformation: Transpose the matrix Reverse each row Steps: Traverse upper triangle and swap → matrix[i][j] ↔ matrix[j][i] For each row: Use two pointers (left, right) Swap elements to reverse the row Matrix gets rotated in-place ⏱ Complexity: • Time: O(n²) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.56 MB In-place transformations are powerful — no extra space, just smart manipulation 💡 #DSA #LeetCode #Java #Matrix #Arrays #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 45 of Daily DSA 🚀 Solved LeetCode 867: Transpose Matrix ✅ Problem: Given a 2D matrix, return its transpose (rows become columns and columns become rows). Approach: Created a new matrix and swapped indices while traversing. Steps: Get number of rows and columns Create a new matrix of size cols x rows Traverse original matrix Assign: trans[j][i] = matrix[i][j] Return the new matrix ⏱ Complexity: • Time: O(n × m) • Space: O(n × m) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.46 MB Simple transformations like transpose build strong fundamentals for matrix-based problems 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 12 of #100DaysOfCode — Sliding Window Today, I worked on the problem “Max Consecutive Ones III” LeetCode. Problem Summary Given a binary array, the goal is to find the maximum number of consecutive 1s if you can flip at most k zeros. Approach At first glance, this problem looks like a brute-force or restart-based problem, but the optimal solution lies in the Sliding Window technique. The key idea is to maintain a window [i, j] such that: The number of zeros in the window does not exceed k Expand the window by moving j Shrink the window by moving i whenever the constraint is violated Instead of restarting the window when the condition breaks, we dynamically adjust it. Key Logic Traverse the array using pointer j Count the number of zeros in the current window If zeros exceed k, move pointer i forward until the window becomes valid again At every step, update the maximum window size Why This Works This approach ensures: Each element is processed at most twice Time Complexity: O(n) Space Complexity: O(1) The most important learning here is understanding how to dynamically adjust the window instead of resetting it, which is a common mistake while applying sliding window techniques. In sliding window problems, always focus on expanding and shrinking the window efficiently rather than restarting the computation. #100DaysOfCode #DSA #SlidingWindow #LeetCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
Some problems break the standard sliding window pattern — especially when negative numbers are involved. 🚀 Day 104/365 — DSA Challenge Solved: Shortest Subarray with Sum at Least K Problem idea: We need to find the length of the shortest subarray whose sum is at least k. The challenge is that the array can contain negative numbers, so normal sliding window won't work. Efficient approach: Use Prefix Sum + Monotonic Deque. Steps: 1. Build a prefix sum array 2. Use a deque to store indices of useful prefix sums 3. While current sum − smallest prefix ≥ k → update answer 4. Maintain increasing order in deque by removing larger prefix sums from the back 5. This ensures we always get the shortest valid subarray This approach efficiently handles negative numbers while keeping optimal time complexity. ⏱ Time: O(n) 📦 Space: O(n) Day 104/365 complete. 💻 261 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #Deque #PrefixSum #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 78 of #100DaysOfCode Solved 443. String Compression on LeetCode 🔗 🧠 Key Insight: We compress the array in-place by: 👉 Replacing consecutive characters with: char + count (if count > 1) Example: ["a","a","b","b","c","c","c"] → ["a","2","b","2","c","3"] ⚙️ Approach (Two Pointers): 1️⃣ Use two pointers: 🔹 i → iterate through array 🔹 idx → position to write compressed result 2️⃣ For each character: 🔹 Count consecutive occurrences using a loop 3️⃣ Write character: 🔹 chars[idx++] = ch 4️⃣ If count > 1: 🔹 Convert count to string 🔹 Add each digit to array 5️⃣ Continue until end 6️⃣ Return idx (new length) ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #Strings #TwoPointers #Array #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Day 46/75 — Frequency of the Most Frequent Element Today’s problem was about maximizing the frequency of an element using at most k increments. Approach: • Sort the array • Use sliding window • Maintain sum of current window • Expand right pointer • Shrink window when operations exceed k Key logic: while ((long) nums[right] * (right - left + 1) - total > k) { total -= nums[left]; left++; } maxFreq = Math.max(maxFreq, right - left + 1); Time Complexity: O(n log n) (sorting) Space Complexity: O(1) Key Insight: Make all elements in window equal to the largest element — check if cost ≤ k. 46/75 🚀 #Day46 #DSA #SlidingWindow #TwoPointers #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
Day 48/75 — Max Consecutive Ones III Today’s problem was about finding the maximum consecutive 1s after flipping at most k zeros. Approach: • Use sliding window • Expand right pointer • Count zeros in window • Shrink window when zeros > k Key logic: if (nums[right] == 0) zeroCount++; while (zeroCount > k) { if (nums[left] == 0) zeroCount--; left++; } maxLength = Math.max(maxLength, right - left + 1); Time Complexity: O(n) Space Complexity: O(1) Key Insight: Keep the window valid by ensuring at most k zeros, and maximize its size. 48/75 🚀 #Day48 #DSA #SlidingWindow #TwoPointers #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
Day 3 / 75 – DSA Challenge Solved “Longest Substring Without Repeating Characters” using the Sliding Window technique. Optimized the solution to achieve: • Time Complexity: O(n) • Space Complexity: O(1) (fixed-size frequency array) Focused on improving window management logic and reducing unnecessary computations. The solution was accepted with strong runtime and memory performance. Consistent progress, one problem at a time. #75DaysOfDSA #DataStructures #Algorithms #Java #ProblemSolving #LeetCode
To view or add a comment, sign in
-
-
Day 47 of Daily DSA 🚀 Solved LeetCode 74: Search a 2D Matrix ✅ Problem: Given a sorted 2D matrix where: • Each row is sorted • First element of each row > last element of previous row Find whether a target exists in the matrix. Approach: Used an optimized staircase search (top-right traversal). Steps: Start from top-right corner If element == target → return true If element > target → move left If element < target → move down Continue until found or out of bounds ⏱ Complexity: • Time: O(n + m) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.84 MB Sometimes choosing the right starting point (top-right) makes the search super efficient 💡 #DSA #LeetCode #Java #Matrix #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 49/75 — Rearrange Array Elements by Sign Today’s problem focused on rearranging an array such that positive and negative numbers alternate, while preserving their original order. Approach: • Use two pointers (even index for positive, odd index for negative) • Traverse the array once • Place elements in correct positions directly Key logic: if (num >= 0) { result[posIdx] = num; posIdx += 2; } else { result[negIdx] = num; negIdx += 2; } Time Complexity: O(n) Space Complexity: O(n) A clean problem that reinforces index placement and pattern-based traversal. 49/75 🚀 #Day49 #DSA #Arrays #Java #Algorithms #LeetCode
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