🚀 **LeetCode Problem Solved – Max Consecutive Ones III** Today I solved **Problem 1004: Max Consecutive Ones III** using the **Sliding Window technique**. 🔹 **Problem Summary** Given a binary array `nums` containing 0s and 1s and an integer `k`, we are allowed to flip at most `k` zeros to ones. The goal is to determine the **maximum number of consecutive 1s** possible after performing at most `k` flips. 🔹 **Approach** Instead of checking every possible subarray, I used the **Sliding Window (Two Pointer) approach**: • Expand the window using the right pointer • Count the number of zeros in the window • If zeros exceed `k`, move the left pointer to maintain a valid window • Track the maximum window size 🔹 **Complexity** ⏱ Time Complexity: **O(n)** 💾 Space Complexity: **O(1)** 📊 **Result** ✔ 60 / 60 Testcases Passed ⚡ Runtime: **2 ms (Beats 99.93%)** Consistent practice with **Data Structures & Algorithms** helps build strong problem-solving skills and deeper understanding of algorithmic patterns. Always open to learning better approaches or optimizations! 💡 #LeetCode #DSA #Java #SlidingWindow #ProblemSolving #CodingJourney
Max Consecutive Ones III LeetCode Solution
More Relevant Posts
-
🚀 DSA Journey | Day 4 — Majority Element (LeetCode) Today, I solved the Majority Element problem and focused on improving my approach from a brute force solution to an optimized one. 🔹 🧠 Problem Understanding Given an integer array, the task is to find the element that appears more than ⌊n/2⌋ times. ✔ The problem guarantees that a majority element always exists ✔ Focus is on optimizing the approach efficiently 🔹 ⚙️ Approach 1: Brute Force For each element, I traversed the entire array again to count its frequency If the frequency exceeded n/2, I returned that element ❌ Time Complexity: O(n²) 👉 Works fine but not scalable for large inputs 🔹 ⚡ Approach 2: Optimized (Using HashMap) Stored frequency of elements using a HashMap Identified the element with count greater than n/2 ✔ Time Complexity: O(n) ✔ Space Complexity: O(n) 💡 Significant improvement compared to brute force 🔹 💡 Key Learnings ✔ How to optimize from O(n²) → O(n) ✔ Importance of choosing the right data structure ✔ Better understanding of frequency-based problems #DSA #LeetCode #Java #ProblemSolving #CodingJourney #Day4 #Learning #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 48 of #100DaysOfCode Solved 295. Find Median from Data Stream on LeetCode 📊 🧠 Key Insight: We need to dynamically maintain numbers and efficiently return the median at any time. A naive approach (like maintaining a sorted list) works but is not optimal for large inputs. ⚙️ Approach Used (Sorted List + Binary Search): 1️⃣ Maintain a sorted list 2️⃣ Insert each incoming number at the correct position using Binary Search 3️⃣ For median: 🔹If size is odd → return middle element 🔹If even → return average of two middle elements ⏱️ Time Complexity: 🔹Insert: O(n) (due to shifting) 🔹Median: O(1) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #Heaps #BinarySearch #Algorithms #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
#CodeEveryday — My DSA Journey | Day 2 🧩 Problem Solved: Combination Sum II (LeetCode) 💭 What I Learned: Used backtracking to generate all unique combinations whose sum equals the target. Sorted the array initially to efficiently handle duplicates and enable pruning. At each step: ✔️ Skipped duplicate elements using i > n && nums[i] == nums[i-1] ✔️ Stopped recursion early when the current element exceeded the target ✔️ Moved to the next index (i+1) to avoid reusing elements Strengthened my understanding of handling duplicates in recursion and optimizing search space. ⏱ Time Complexity: O(2ⁿ)*k (k is avg length of each combination) 🧠 Space Complexity: O(n) ⚡ Key Takeaways: ✔️ Sorting helps in both pruning and duplicate handling ✔️ Skipping duplicates is crucial for unique combinations ✔️ Backtracking becomes efficient with early stopping conditions 💻 Language Used: Java ☕ 📘 Concepts: Backtracking · Recursion · Arrays · Duplicate Handling · Pruning #CodeEveryday #DSA #LeetCode #Java #Backtracking #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 26 Today’s focus: Binary Search fundamentals. Problems solved: • Binary Search (LeetCode 704) • Search a 2D Matrix (LeetCode 74) Concepts used: • Binary Search • Search space reduction • Index mapping in 2D arrays Key takeaway: In Binary Search, the idea is to repeatedly divide the search space in half. By comparing the target with the middle element, we eliminate half of the array each time, achieving O(log n) time complexity. In Search a 2D Matrix, the matrix can be treated as a flattened sorted array. Using index mapping: row = mid / cols col = mid % cols we can apply binary search directly on the matrix without extra space. These problems highlight how binary search is not limited to 1D arrays—it can be extended to structured data with proper transformations. Continuing to strengthen fundamentals and consistency in DSA problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 35 Today’s focus: Binary Search with index patterns. Problem solved: • Single Element in a Sorted Array (LeetCode 540) Concepts used: • Binary Search • Index parity (even/odd pattern) • Search space reduction Key takeaway: The array is sorted and every element appears twice except one. A key observation: Before the single element, pairs start at even indices After the single element, this pattern breaks. Using binary search: • If mid is even and nums[mid] == nums[mid + 1], the single element lies on the right side • Else, it lies on the left side (including mid) By leveraging this pattern, we can find the answer in O(log n) time and O(1) space. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem extended the previous one by introducing duplicates in a rotated sorted array. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Minimum in Rotated Sorted Array II 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used modified binary search • Compared nums[mid] with nums[right] Logic: • If nums[mid] > nums[right] → minimum is in right half • If nums[mid] < nums[right] → minimum is in left half (including mid) • If equal → cannot decide, so shrink search space (right--) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Duplicates can break standard binary search logic • When unsure, safely reduce the search space • Edge cases often define the complexity of the problem • Small changes in conditions can affect performance 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Average Time: O(log n) • Worst Case: O(n) (due to duplicates) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When the data becomes ambiguous, focus on reducing the problem safely instead of forcing a decision. 55 days consistent 🚀 On to Day 56. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
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