🚀 LeetCode Problem Solved: Max Consecutive Ones III (Sliding Window Technique) Day 16 of #75DaysofLeetCode Today I solved LeetCode 1004 – Max Consecutive Ones III, a great problem to practice the Sliding Window / Two Pointer technique. 🔹 Problem: Given a binary array and an integer k, we can flip at most k zeros to ones. The goal is to find the maximum number of consecutive 1’s in the array after performing at most k flips. 💡 Key Idea: Instead of checking every possible subarray, we maintain a sliding window and allow at most k zeros inside the window. If the number of zeros exceeds k, we shrink the window from the left until the condition becomes valid again. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Java Implementation: class Solution { public int longestOnes(int[] nums, int k) { int left = 0; int zeroCount = 0; int maxLen = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] == 0) { zeroCount++; } while (zeroCount > k) { if (nums[left] == 0) { zeroCount--; } left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen; } } 📚 This problem strengthened my understanding of efficient window management in arrays, which is a common pattern in coding interviews. #LeetCode #Java #SlidingWindow #DSA #ProblemSolving #CodingJourney #SoftwareDevelopment
Max Consecutive Ones III LeetCode Solution
More Relevant Posts
-
🚀 Day 17 of #75DaysofLeetCode LeetCode Problem Solved: Longest Subarray of 1's After Deleting One Element (Sliding Window) Today I solved LeetCode 1493 – Longest Subarray of 1's After Deleting One Element. This problem is a great example of applying the Sliding Window / Two Pointer technique to optimize array problems. 🔹 Problem Statement: Given a binary array nums, we must delete exactly one element and then find the longest non-empty subarray containing only 1's. 💡 Approach: The key idea is to maintain a sliding window that allows at most one 0 in the window. If the number of zeros exceeds one, we move the left pointer to shrink the window until the condition becomes valid again. Since we must delete one element, the final answer becomes: window_size - 1 ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Java Implementation: class Solution { public int longestSubarray(int[] nums) { int left = 0; int zeroCount = 0; int maxLen = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] == 0) { zeroCount++; } while (zeroCount > 1) { if (nums[left] == 0) { zeroCount--; } left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen - 1; } } 📚 Practicing problems like this helps strengthen understanding of Sliding Window patterns, which are frequently asked in coding interviews. #LeetCode #Java #DSA #SlidingWindow #ProblemSolving #CodingPractice #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 11 of #50DaysLeetCode Challenge Today I tackled a HARD problem: “Regular Expression Matching” on LeetCode using Java. 🔹 Problem: Given a string "s" and a pattern "p", implement regex matching with support for: • "." → matches any single character • "*" → matches zero or more of the preceding element Return true if the entire string matches the pattern. Example: Input: "s = "aa", p = "a*"" → Output: "true" Input: "s = "aa", p = "a"" → Output: "false" 🔹 Approach I Used: I used Dynamic Programming (DP) — anything else here is inefficient or breaks on edge cases. ✔ Created a 2D DP table "dp[m+1][n+1]" ✔ "dp[i][j]" represents whether "s[0...i-1]" matches "p[0...j-1]" ✔ Handled "*" carefully: - Treat it as zero occurrence → "dp[i][j-2]" - Or one/more occurrence → match previous character ✔ Built the solution bottom-up 🔹 Concepts Practiced: • Dynamic Programming (2D DP) • String pattern matching • Handling complex edge cases #LeetCode #DSA #Java #DynamicProgramming #Algorithms #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
1980. LeetCode Daily Challenge Solved | Find Unique Binary String Solved today’s Find Unique Binary String problem using an elegant Diagonal Construction (Cantor’s Argument) approach. 🔹 Key Idea: Instead of generating all possible binary strings, we construct a new string by flipping the diagonal bits of the given strings. This guarantees the new string differs from every string in the array at least in one position. 🔹 Approach: Traverse each string i Check the i-th character of nums[i] Flip it (0 → 1, 1 → 0) Build a new binary string from these flipped bits This ensures the generated string cannot match any existing string in the input. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String findDifferentBinaryString(String[] nums) { char[] res = new char[nums.length]; for (int i = 0; i < nums.length; i++) { char c = nums[i].charAt(i); res[i] = (c == '0') ? '1' : '0'; } return new String(res); } } ⚡ Result: ✔ Runtime: 0 ms (Beats 100%) ✔ Memory: 42.86 MB Consistency with daily problems builds strong problem-solving intuition. On to the next challenge! #LeetCode #DSA #Java #CodingPractice #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 LeetCode Practice Update Solved “1415. The k-th Lexicographical String of All Happy Strings of Length n” today. It’s an easy–medium problem for anyone comfortable with Backtracking, but a great exercise to strengthen recursive thinking and constraint-based generation. 🧠 Approach The idea is to generate all valid “happy strings” using backtracking and then simply pick the k-th string in lexicographical order. A happy string means: It only contains characters 'a', 'b', 'c' No two adjacent characters are the same ⚙️ Strategy 1. Start with an empty string and recursively build all possible strings of length n. 2. At each step, try adding characters from 'a' → 'c' to maintain lexicographical order. 3. Before adding a character, check the constraint: If the last character of the current string is the same as the character we want to add → skip it. 4. If the string length becomes n, add it to the list of valid happy strings. 5. After generating all valid strings: If k > total strings, return an empty string. Otherwise return the (k-1)th index from the list. 🔁 Key Backtracking Step After exploring a choice, we remove the last character to restore the previous state and try the next option. This pattern of choose → explore → undo (backtrack) is the heart of backtracking problems. 💡 Problems like this really show how powerful backtracking can be when generating all valid combinations under constraints. #LeetCode #Backtracking #Java #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 22 of #75DaysofLeetCode LeetCode Problem Solved: Determine if Two Strings Are Close (1657) Another interesting String + Frequency Analysis problem from LeetCode! 🔹 Problem: Two strings are considered close if we can transform one into the other using: 1️⃣ Swap any two characters (rearranging characters). 2️⃣ Transform all occurrences of one character into another existing character and vice versa. We need to determine whether word1 can be converted into word2 using these operations. 💡 Key Insights: To make two strings close, three conditions must hold: ✔️ Both strings must have the same length. ✔️ Both strings must contain the same set of characters. ✔️ The frequency distribution of characters must match after sorting. Why? Because operation 2 allows us to swap character frequencies between existing characters. 💻 Java Solution: import java.util.*; class Solution { public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] freq1 = new int[26]; int[] freq2 = new int[26]; for(char c : word1.toCharArray()) freq1[c - 'a']++; for(char c : word2.toCharArray()) freq2[c - 'a']++; for(int i = 0; i < 26; i++){ if((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) return false; } Arrays.sort(freq1); Arrays.sort(freq2); return Arrays.equals(freq1, freq2); } } 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this help strengthen understanding of hashing, frequency counting, and string manipulation, which are common in coding interviews. #LeetCode #DSA #Java #CodingPractice #Algorithms #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 97 of My 100 Days LeetCode Challenge | Java Today’s problem was a solid exercise in matrix processing and prefix sum optimization. The goal was to count the number of submatrices whose sum is less than or equal to a given value (k). A brute-force approach would be too slow, so the key was to use 2D prefix sums to efficiently compute submatrix sums. By converting the matrix into a prefix sum matrix, we can calculate the sum of any submatrix in constant time, making the overall solution much more efficient. ✅ Problem Solved: Count Submatrices With Sum ≤ K ✔️ All test cases passed (859/859) ⏱️ Runtime: 7 ms 🧠 Approach: 2D Prefix Sum 🧩 Key Learnings: ● Prefix sums are powerful for optimizing repeated range sum queries. ● 2D prefix sums extend the same idea from arrays to matrices. ● Preprocessing can drastically reduce computation time. ● Avoiding brute force is key in large input problems. ● Matrix problems often become easier with the right transformation. This problem reinforced how preprocessing techniques like prefix sums can turn complex problems into efficient solutions. 🔥 Day 97 complete — sharpening matrix optimization and prefix sum skills. #LeetCode #100DaysOfCode #Java #PrefixSum #Matrix #Algorithms #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀Day 24 of #75DaysofLeetCode LeetCode Problem Solved: Removing Stars From a String (2390) Today I solved the problem “Removing Stars From a String.” 🔹 Problem Statement: We are given a string containing characters and *. Each * removes the closest non-star character to its left, along with the * itself. The task is to return the final string after all stars are processed. 💡 Approach: The most efficient way to solve this is using a Stack-like approach. 1️⃣ Traverse the string from left to right. 2️⃣ If the character is not *, add it to the result (stack). 3️⃣ If the character is *, remove the last added character. 4️⃣ Continue until the string is processed. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String removeStars(String s) { StringBuilder sb = new StringBuilder(); for(char c : s.toCharArray()) { if(c == '*') { sb.deleteCharAt(sb.length() - 1); } else { sb.append(c); } } return sb.toString(); } } ✨ Key Learning: Using a stack or StringBuilder helps efficiently simulate the removal of the closest character on the left. #LeetCode #Java #DataStructures #ProblemSolving #CodingPractice #100DaysOfCode
To view or add a comment, sign in
-
-
💻 LeetCode Daily Challenge – Find Unique Binary String (Problem 1980) Today's LeetCode Daily Challenge was "Find Unique Binary String". 📌 Problem Summary We are given n unique binary strings of length n. The task is to construct a binary string of length n that does not exist in the given list. 🔎 Approach 1: HashSet + Generate All Possibilities Idea: Store all given strings in a HashSet. Generate binary numbers from 0 to 2^n - 1. Convert each number to a binary string of length n. Return the first string not present in the set. Time Complexity: O(2^n) Space Complexity: O(n) 🔎 Approach 2: Backtracking Idea: Recursively generate all binary strings of length n. Check if the generated string exists in the set. Return the first missing string. Time Complexity: O(2^n) Space Complexity: O(N) 🚀 Approach 3 (Optimal – Cantor’s Diagonalization) This elegant approach guarantees a unique string. Idea: Look at the i-th character of the i-th string. Flip the bit (0 → 1 or 1 → 0). Build a new string using these flipped bits. This ensures the constructed string differs from every string at least at one position. Time Complexity: O(n) Space Complexity: O(n) 💡 Java Implementation (Optimal Approach) class Solution { public String findDifferentBinaryString(String[] nums) { StringBuilder res = new StringBuilder(); for(int i = 0; i < nums.length; i++){ char ch = nums[i].charAt(i); if(ch == '0') res.append('1'); else res.append('0'); } return res.toString(); } } 📚 Key Takeaway This problem demonstrates a clever application of Cantor’s Diagonalization, allowing us to construct a guaranteed unique binary string in linear time. #LeetCodeDaily #DSA #Java #ProblemSolving #CodingPractice #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 11 – LeetCode Practice Today, I solved the Wildcard Matching problem on LeetCode: 🎯 Difficulty: Hard 💻 Language Used: Java 💡 Problem Overview: Given a string s and a pattern p, determine if the string matches the pattern. The pattern can contain special wildcard characters: ? → matches any single character * → matches any sequence of characters (including empty) The match must cover the entire string, not just a substring. 💡 Approach: I used a Dynamic Programming (DP) approach. Created a dp table where dp[i][j] represents whether the first i characters of string s match the first j characters of pattern p. If characters match or pattern has ?, we move diagonally in the DP table. If pattern contains *, it can represent: empty sequence → dp[i][j-1] multiple characters → dp[i-1][j] Finally, dp[m][n] gives the final result. ⏱ Complexity Time Complexity: O(m × n) Space Complexity: O(m × n) (where m = length of string, n = length of pattern) 📚 Key Takeaway This problem strengthened my understanding of Dynamic Programming for string pattern matching, especially handling flexible wildcards like * which can represent multiple states. Consistent practice is helping me recognize patterns and improve problem-solving speed. 💪 #LeetCode #Java #DSA #DynamicProgramming #Algorithms #ProblemSolving #CodingPractice #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Day 21/30 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #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