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
Muhammad Anas Qadri’s Post
More Relevant Posts
-
Not all sliding window problems are about sums — sometimes the constraint is on the product, but the pattern still applies. 🚀 Day 103/365 — DSA Challenge Solved: Subarray Product Less Than K Problem idea: We need to count the number of subarrays where the product of all elements is strictly less than k. Efficient approach: Use a sliding window that maintains a valid product. Steps: 1. Expand the window by multiplying the current element 2. If product becomes ≥ k, shrink the window from the left 3. Keep dividing until product < k 4. Count all valid subarrays ending at each index This works because all numbers are positive, so the window can be adjusted greedily. ⏱ Time: O(n) 📦 Space: O(1) Day 103/365 complete. 💻 262 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Many subarray problems follow the same hidden pattern — once you recognize it, they become much easier. 🚀 Day 102/365 — DSA Challenge Solved: Count Number of Nice Subarrays Problem idea: We need to count the number of subarrays that contain exactly k odd numbers. Efficient approach: Use the same trick as previous problem: subarrays with exactly k odds = subarrays with ≤ k odds − subarrays with ≤ (k − 1) odds Steps: 1. Use a sliding window to count subarrays with at most k odd numbers 2. Expand window by moving right pointer 3. If odd count exceeds k, shrink window from left 4. Add valid subarrays ending at each index 5. Subtract results to get exact count This pattern works beautifully for binary-like conditions. ⏱ Time: O(n) 📦 Space: O(1) Day 102/365 complete. 💻 263 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Some problems become much easier when you reframe the question. 🚀 Day 107/365 — DSA Challenge Solved: Minimum Operations to Reduce X to Zero Problem idea: We need to remove elements from the left or right so that their sum equals x, with minimum operations. Efficient approach: Instead of removing elements, think in reverse: 👉 Find the longest subarray with sum = totalSum − x Steps: 1. Calculate total sum of the array 2. Set target = totalSum − x 3. Find the longest subarray with sum = target using sliding window 4. Result = total length − longest subarray length This converts the problem into a familiar sliding window problem. ⏱ Time: O(n) 📦 Space: O(1) Day 107/365 complete. 💻 258 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Some subarray counting problems become much easier when we transform them into “at most” problems. 🚀 Day 101/365 — DSA Challenge Solved: Binary Subarrays With Sum Problem idea: We need to count the number of subarrays whose sum equals a given goal in a binary array. Efficient approach: Instead of directly counting subarrays with exact sum, we use a trick: subarrays with sum = goal = subarrays with sum ≤ goal − subarrays with sum ≤ (goal − 1) Steps: 1. Create a helper function to count subarrays with sum at most k 2. Use a sliding window to maintain a valid window where sum ≤ k 3. Add the number of valid subarrays ending at each index 4. Subtract results to get the exact count for the goal This converts the problem into an efficient sliding window solution. ⏱ Time: O(n) 📦 Space: O(1) Day 101/365 complete. 💻 264 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Most substring problems can be solved efficiently using the sliding window technique. 🚀 Day 97/365 — DSA Challenge Solved: Longest Substring Without Repeating Characters Problem idea: We need to find the length of the longest substring that contains no duplicate characters. Efficient approach: Use a sliding window with two pointers. Steps: 1. Keep track of the last seen index of each character 2. Expand the window by moving the right pointer 3. If a character repeats inside the window, move the left pointer to the position after its last occurrence 4. Update the maximum window length This ensures the window always contains unique characters. ⏱ Time: O(n) 📦 Space: O(1) Day 97/365 complete. 💻 268 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #SlidingWindow #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
Linked list problems often test how well you can manipulate pointers without losing track. 🚀 Day 114/365 — DSA Challenge Solved: Swap Nodes in Pairs Problem idea: We need to swap every two adjacent nodes in a linked list without changing values, only pointers. Efficient approach: Use a dummy node and carefully adjust pointers in pairs. Steps: 1. Use a dummy node pointing to head 2. Maintain a pointer prev before the current pair 3. Identify two nodes: first and second 4. Swap them by updating pointers 5. Move prev forward to the next pair This ensures all pairs are swapped correctly. ⏱ Time: O(n) 📦 Space: O(1) Day 114/365 complete. 💻 251 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #LinkedList #LeetCode #LearningInPublic
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
-
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
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 56/75 — Sliding Window Maximum Today’s problem was about finding the maximum element in every sliding window of size k. Approach: • Use a deque to store indices of useful elements • Maintain decreasing order in deque (front = max) • Remove elements out of current window Key logic: while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) { dq.pollLast(); } if (!dq.isEmpty() && dq.peekFirst() == i - k) { dq.pollFirst(); } dq.offerLast(i); Time Complexity: O(n) Space Complexity: O(k) A classic problem that strengthens sliding window + monotonic deque concepts. 56/75 🚀 #Day56 #DSA #SlidingWindow #Deque #Java #Algorithms #LeetCode
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
Keep it up 👍