I recently tackled an interesting sliding window problem: given a binary array, what is the maximum number of consecutive 1's you can get if you are allowed to flip at most k zeros? The Logic: Instead of trying every possible flip (which would be O(n^2) or worse), I used the Sliding Window (Two Pointers) technique. ✅ Expand: Move the right pointer to grow the window. ✅ Constraint Check: If we hit more than 'k' zeros, it's time to shrink the window from the left. ✅ Maximize: Keep track of the largest window size we've seen that satisfies the condition. Efficiency: By only passing through the array once, the solution hits an optimal O(n) time complexity and O(1) space complexity. It’s a classic example of how a dynamic window can turn a complex search into a streamlined linear process. Implementation: https://htmlify.me/r/6uhp #DataStructures #Algorithms #Python #CodingChallenge #SlidingWindow #ProblemSolving
Max Consecutive 1's in Binary Array with K Flips
More Relevant Posts
-
Spent some time working through array pattern problems and revisited the Two Pointer technique using the “Valid Mountain Array” problem. 🧩 Problem Insight: A valid mountain array must: - Strictly increase - Have a peak that is not at the beginning or end - Then strictly decrease 💡 Approach: Instead of checking every possible peak, I used two pointers: - One is moving from the left while the elements increase - One moving from the right while elements decrease - If both pointers meet at the same index (and not at boundaries), the array forms a valid mountain ⚙️ Complexity: Time: O(n) Space: O(1) What I like about this pattern is how it simplifies traversal problems without extra space — clean logic, efficient execution. Always interesting to see how small structural patterns make array problems much clearer. #LeetCode #Python #DataStructures #TwoPointers #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode Problem 1582: "Special Positions in a Binary Matrix": Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Approach: Initialize two arrays, one stores the number of 1s in each row of the matrix and other stores the number of 1s in each column, by traversing the matrix for filling each of the arrays. Now re-traverse the matrix and if mat[i][j]==1, check for the number of 1s in corresponding row and column, if number of 1s in that row and column is equal to one, we get our required position, calculate the total number of such positions. #Python #LeetCode #Matrices #ProblemSolving #CompetitiveProgramming #DataStructures #Algorithms #Arrays #Coding
To view or add a comment, sign in
-
-
🚀 Day 42 / 200 – Minimum Window Substring (Hard) Solved LeetCode 76 – Minimum Window Substring today! 💪 This problem was a great test of Sliding Window + HashMap concepts. The challenge was to find the smallest substring that contains all characters of another string (including duplicates). 🔎 Key Learnings: Mastered the two-pointer (left & right) sliding window technique Used frequency counters to track required characters Optimized window shrinking to ensure minimum length Improved understanding of handling duplicate character constraints ✅ 268 / 268 test cases passed ⚡ Runtime: 75 ms 🐍 Language: Python Problems like this strengthen real-world problem-solving skills and improve optimization thinking. Consistency > Motivation. 200 Days. No excuses. 💯 #Day42 #200DaysChallenge #LeetCode #Python #DataStructures #Algorithms #SlidingWindow #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
LeetCode Problem 1545: "Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0)." Approach: Initialize an array with a single element '0' which serves as the string1 then iteratively calculate the consecutive strings and store them in the array. Finally, form the final string using the join() function and return the kth character of the string. #Python #LeetCode #String #ProblemSolving #CompetitiveProgramming #DataStructures #Algorithm
To view or add a comment, sign in
-
-
🚀 Problem Solved: Longest Span in Two Binary Arrays Solved the “Longest Span in Two Binary Arrays” problem on GeeksforGeeks using an optimized Prefix Sum + HashMap approach. 🔍 Approach: Instead of checking all subarrays (O(N²)), I transformed the problem by: Creating a difference array (a1[i] - a2[i]) Using Prefix Sum to track cumulative differences Storing first occurrences in a dictionary to efficiently find the longest subarray with sum = 0 ⚡ Performance: ✔ 1113 / 1113 Test Cases Passed ✔ Time Complexity: O(N) ✔ Space Complexity: O(N) This problem strengthened my understanding of: Prefix Sum concepts HashMap optimization techniques Converting problems into standard subarray sum patterns Consistently working on improving my DSA skills to build strong problem-solving fundamentals. 💪 #geekstreak60 #POTDwithGFG #DataStructures #Algorithms #Python #ProblemSolving #CodingJourney #FutureDataScientist
To view or add a comment, sign in
-
-
🌳 Turning Code into Nature – Simple Tree with Fruits using Python Turtle 🌳 I created a minimalistic tree simulation using Python Turtle, exploring the intersection of recursion, randomness, and graphical representation. Features of this project: 🌿 Recursive branch generation: Each branch splits into smaller branches automatically, simulating a natural tree structure. 🍃 Leaves and fruits: Randomly generated green leaves and red fruits make the tree visually appealing. 🎨 Clean visual design: Sky-blue background and simple aesthetic for a minimal yet realistic look. 🧠 Algorithmic thinking practice: Recursion and randomness were used to model natural growth patterns. This project helped me apply programming logic to creative visualization, combining computer science concepts with artistic expression. #Python #TurtleGraphics #Recursion #CreativeCoding #DataVisualization #CodingMeetsNature
To view or add a comment, sign in
-
𝗜 𝗳𝗼𝘂𝗻𝗱 𝗮 𝟰𝟰× 𝘀𝗽𝗲𝗲𝗱 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗶𝗻 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝘀𝘂𝗺() 𝗼𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻 🚀 I benchmarked three ways of summing 100,000 numbers: • Manual for loop → ~11.4 ms • Built-in 𝘀𝘂𝗺() → ~8.27 ms • 𝗻𝗽.𝘀𝘂𝗺() → ~0.259 ms 𝗡𝘂𝗺𝗣𝘆 𝘄𝗮𝘀 ~𝟰𝟰× 𝗳𝗮𝘀𝘁𝗲𝗿 𝘁𝗵𝗮𝗻 𝗮 𝗣𝘆𝘁𝗵𝗼𝗻 𝗹𝗼𝗼𝗽 ⚡ The real insight isn’t that “NumPy is faster.” It’s about execution layers. A Python loop runs inside the interpreter with dynamic checks every iteration. 𝘀𝘂𝗺() shifts the work into C. 𝗻𝗽.𝘀𝘂𝗺() operates on contiguous memory using optimized low-level code, avoiding Python-level iteration entirely. Same computation. Different execution layer. Massive performance gap. #Python #NumPy #DataScience #LearningInPublic
To view or add a comment, sign in
-
-
I just cleared the Find Kth Rotation challenge on GeeksforGeeks and wanted to share the logic behind the solution. The goal is to find how many times a sorted array has been right-rotated. The key insight here is that the number of rotations is exactly equal to the index of the smallest element in the array. While a simple linear scan works, you can optimize this using Binary Search. By comparing the middle element with its neighbors, you can determine if you have found the pivot point. If the middle element is greater than the first element, the rotation happened in the right half; otherwise, it happened in the left half. This approach cuts the time complexity down to logarithmic time, making it much more efficient for large datasets. Implementation: https://htmlify.me/r/f0ub #Algorithms #DataStructures #CodingTips #Python #BinarySearch #GeeksforGeeks
To view or add a comment, sign in
-
🔥 LeetCode 210 — Course Schedule II | Topological Sort Mastery problem number :- 21 Today I tackled one of the most important graph problems on LeetCode — Course Schedule II — and honestly, this one was a beautiful test of understanding DFS + cycle detection. At first glance, it looks like just another graph problem… But the real game is: ✅ Building the adjacency list correctly ✅ Using the 3-state visited array (0,1,2) ✅ Detecting cycles during DFS ✅ Producing a valid topological order The most powerful insight for me was this small but deadly piece of code: for nei in adj[node]: if not dfs(nei): return False 💡 Key realization: If even ONE neighbor leads to a cycle → the whole course plan collapses. This problem strengthened my understanding of: 🔹 Topological Sorting via DFS 🔹 Graph traversal patterns 🔹 Cycle detection in directed graphs 🔹 Writing clean recursive logic #LeetCode #DSA #GraphTheory #TopologicalSort #Python #CodingJourney
To view or add a comment, sign in
-
-
A clean and efficient approach to finding the longest span with equal sum in two binary arrays 🚀 This solution uses prefix sum differences and indexing optimization to achieve O(n) time and O(n) space, avoiding nested loops altogether. Always satisfying when math + data structures simplify a problem this much. 💡 #DataStructures #Algorithms #Python #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
More from this author
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