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
Max Consecutive Ones III with Sliding Window
More Relevant Posts
-
Day 105: Circular Arrays & Shortest Paths 🔄 Problem 2515: Shortest Distance to Target String in a Circular Array Today’s challenge involved finding the minimum steps to reach a target string in a circular array, allowing movement in both directions. The Strategy: • Bidirectional Search: Since the array is circular, the distance can be calculated in two ways: moving forward or moving backward. • Modular Arithmetic: I used (dist + n) % n to handle the wrap-around logic seamlessly, ensuring the index stays within bounds regardless of the direction. • Optimization: By iterating once through the array and comparing the distances for every occurrence of the target, I maintained an O(N) time complexity. Sometimes the most elegant way to handle a "circular" problem is simply embracing the symmetry of the path. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
💡 Day 57 of LeetCode Problem Solved! 🔧 🌟 Maximum Distance Between a Pair of Values 🌟 🔗 Solution Code: https://lnkd.in/gSP_QePE 🧠 Approach: • Two-Pointer Strategy: Maintain two indices (i for nums1 and j for nums2) to scan both non-increasing arrays in a single efficient pass. • Greedy Search: If nums1[i] <= nums2[j], calculate j - i and expand j to find the maximum possible distance. If the value in nums1 is too large, move i forward. ⚡ Key Learning: • Leveraging the non-increasing nature of arrays with two pointers eliminates the need for nested loops, reducing complexity from O(N^2) to linear O(N+M). ⏱️ Complexity: • Time: O(n + m) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #Algorithms #TwoPointers
To view or add a comment, sign in
-
-
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 39 of Daily DSA 🚀 Solved LeetCode 1446: Consecutive Characters ✅ Problem: The power of a string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return its power. Rules: * Substring must be non-empty * Substring must contain only one unique character * Return the maximum such length Approach: Used a simple linear scan to track the current streak of consecutive identical characters and update the maximum. Steps: 1. Initialize max and count both to 1 2. Iterate from index 1 onwards 3. If current character equals previous → increment count 4. Else → reset count to 1 5. Update max at every step 6. Return max ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 29 ms (Beats 2.02%) • Memory: 45.33 MB Sometimes the simplest sliding window — just two variables — is all you need to solve a problem cleanly. #DSA #LeetCode #Java #SlidingWindow #Strings #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 56/100 | #100DaysOfDSA 🧠⚡ Today’s problem: String Compression A clean in-place array manipulation problem. Core idea: Compress consecutive repeating characters and store the result in the same array. Approach: • Traverse the array using a pointer • Count consecutive occurrences of each character • Write the character to the array • If count > 1 → write its digits one by one • Move forward and repeat Key insight: We don’t need extra space — just carefully manage read & write pointers. Time Complexity: O(n) Space Complexity: O(1) Big takeaway: In-place algorithms require precise pointer control but give optimal space efficiency. Mastering these improves real-world memory optimization skills. 🔥 Day 56 done. #100DaysOfCode #LeetCode #DSA #Algorithms #Strings #TwoPointers #InPlace #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 567 of #750DaysOfCode 🚀 🔍 Problem Solved: Maximum Distance Between a Pair of Values Today’s challenge was about finding the maximum distance (j - i) such that: ✔️ i ≤ j ✔️ nums1[i] ≤ nums2[j] ✔️ Both arrays are non-increasing 💡 Key Insight: Since both arrays are sorted in descending order, we can avoid brute force and use a Two Pointer approach to achieve optimal performance. 🧠 Approach: Initialize two pointers i and j at 0 If nums1[i] ≤ nums2[j] → valid pair → update distance & move j Else → move i forward Maintain j ≥ i at all times 📊 Complexity: Time: O(n + m) Space: O(1) 🔥 Takeaway: Whenever arrays are sorted, always think of two pointers or binary search before jumping to brute force. This simple shift can reduce complexity from O(n²) → O(n)! #Day567 #750DaysOfCode #LeetCode #Java #DataStructures #Algorithms #TwoPointers #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 103: Simple & Clean 🎯 Problem 1848: Minimum Distance to the Target Element After some complex DP challenges, today was a straightforward exercise in linear search and distance calculation. The Strategy: • Linear Traversal: I iterated through the array to find every occurrence of the target element. • Absolute Minimization: For each match, I calculated the absolute difference between the current index and the start index, keeping track of the minimum value found. Sometimes a simple, O(N) solution is all you need. Day 103 down—maintaining the streak with clarity and consistency. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
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 114 of #365DaysOfLeetCode Challenge** Today’s problem: **Keyboard Row (LeetCode 500)** A fun and simple problem focused on **strings + simulation + clean logic**. We need to return words that can be typed using letters from **only one row** of the American keyboard. Rows: * Row 1 → `qwertyuiop` * Row 2 → `asdfghjkl` * Row 3 → `zxcvbnm` 💡 **Core Idea:** For each word: 1️⃣ Convert to lowercase 2️⃣ Identify keyboard row of first character 3️⃣ Check whether every remaining character belongs to same row 📌 **Approach:** * Use strings to represent rows * Use `indexOf()` for membership check * Preserve original word in output ⚡ **Time Complexity:** O(total characters in all words) ⚡ **Space Complexity:** O(result list) **What I learned today:** Even easy problems teach valuable habits: 👉 Clean iteration 👉 Case handling 👉 Efficient validation logic 💭 **Key Takeaway:** Not every challenge needs advanced algorithms. Sometimes simplicity + clean implementation = best solution. #LeetCode #DSA #Strings #Java #CodingChallenge #ProblemSolving #TechJourney #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