🔥 Day 74/100 of #100DaysOfCode – Sliding Window Maximum: Deque for O(n)! Today solved a classic problem requiring efficient maximum tracking in a moving window: ✅ Problem 239: Sliding Window Maximum Task: Return the maximum in each sliding window of size k in O(n) time. Approach: Monotonic decreasing deque (Double-ended Queue): Store indices (not values) in deque, maintaining decreasing order of values Remove out-of-window indices from front Remove smaller elements from back before adding new index Front of deque always holds current window’s max Key Insight: A deque lets us efficiently maintain candidates for maximum while sliding the window, avoiding repeated O(k) scans. Complexity: O(n) time, O(k) extra space — optimal linear solution. A powerful example of using the right data structure to maintain order while supporting efficient insertions and deletions from both ends! 📊🔍 #100DaysOfCode #LeetCode #Java #Deque #SlidingWindow #MonotonicQueue #Algorithms #CodingInterview
Sliding Window Maximum with Deque in O(n) Time
More Relevant Posts
-
🔥 Day 83/100 of Code – Substrings Containing All Three Characters: Counting with Minimal Valid Window! Today solved a substring counting problem by leveraging the "minimal valid window" property: ✅ Problem 1358: Number of Substrings Containing All Three Characters Task: Count substrings containing at least one a, b, and c. Approach: Sliding window with earliest valid start tracking: For each ending index r, find the smallest l such that s[l..r] contains all three chars Once found, all substrings starting from 0..l and ending at r are valid → add l+1 to count Use a frequency map or array to track counts of a,b,c and shrink window when possible Key Insight: If the minimal valid window ending at r starts at minStart, then any substring starting before minStart and ending at r also contains all three characters — giving minStart + 1 valid substrings per r. Complexity: O(n) time, O(1) space — efficient single pass. A smart counting trick that turns a "contain all" constraint into an elegant O(n) accumulation! 🔤🔢 #100DaysOfCode #LeetCode #Java #SlidingWindow #String #SubstringCounting #Algorithm
To view or add a comment, sign in
-
-
🔥 Day 84/100 of Code – Maximum Points from Cards: Sliding Window on a Circular Array! Today solved a problem that cleverly reframes picking from ends as finding the minimum subarray sum in the middle: ✅ Problem 1423: Maximum Points You Can Obtain from Cards Task: Pick k cards from either end of the array to maximize sum. Approach: Complementary sliding window: Total sum of picking k from ends = total sum of array - sum of middle subarray of length n-k Find minimum sum of any subarray of length n-k Answer = total sum - min middle sum Implemented with initial leftSum of first k cards, then slide by removing from left, adding from right Key Insight: Instead of simulating all combinations of left/right picks, think about the unchosen middle segment — minimizing it maximizes chosen ends. Complexity: O(n) time, O(1) space — efficient two-pass solution. A great example of how reframing the problem reveals a simpler sliding window approach! 🃏➕➖ #100DaysOfCode #LeetCode #Java #SlidingWindow #Array #Algorithm #CodingInterview
To view or add a comment, sign in
-
-
🔥 Day 86/100 of Code – Subarrays with K Different Integers: The “At Most” Pattern Strikes Again! Today revisited a powerful counting technique to solve a distinct-value subarray problem efficiently: ✅ Problem 992: Subarrays with K Different Integers Task: Count subarrays with exactly k distinct integers. Approach: "At most K distinct" subtraction method: Helper: atMost(k) = subarrays with ≤ k distinct integers Answer = atMost(k) - atMost(k-1) atMost uses sliding window + HashMap to track frequency of values Expand right, shrink left if distinct count > k, count valid subarrays ending at r Key Insight: Converting “exactly K distinct” into “at most K distinct” avoids complex exact matching logic — a reusable pattern seen in Problems 930 and 1248. Complexity: O(n) time, O(k) space — efficient and clean. When you master a pattern, solving variations becomes systematic! 🔄🧠 #100DaysOfCode #LeetCode #Java #SlidingWindow #HashMap #SubarrayCounting #Algorithm
To view or add a comment, sign in
-
-
#200DaysOfCode – Day 111 Word Search Problem: Given a 2D grid of characters and a word, determine whether the word exists in the grid. The word must be formed using adjacent cells (up, down, left, right), and each cell can be used only once. Example: Input: board = [[A, B, C, E], [S, F, C, S], [A, D, E, E]] word = "ABCCED" Output: true My Approach: Used DFS (Depth First Search) starting from every cell. Matched characters step-by-step with the given word. Marked cells as visited during the path to avoid reuse. Applied backtracking to explore all possible directions safely. Time Complexity: O(m × n × 4^L) Space Complexity: O(L) (recursion stack) Grid problems often look complex, but breaking them down with DFS + backtracking makes the logic clear and manageable. Patience and careful state handling are the real keys here #takeUforward #100DaysOfCode #Java #LeetCode #ProblemSolving #Backtracking #DFS #DataStructures #Algorithms #CodeNewbie #Consistency
To view or add a comment, sign in
-
-
Day - 34 Longest Common Prefix The problem - Write a function to find the longest common prefix string amongst an array of strings. Example : strs = [“flower”,”flow”,”flight”] -> “fl” strs=[“dog”,”racecar”,”car”] -> “” Brute force - Compare all the characters at each position across the strings, but the time complexity will be O(S), S is sum of all characters and require multiple traversals. Approach Used - Horizontal Scanning •) Handle edge case: if array is null or empty, return "". •) Initialise pref = strs[0], prefLen = prefix.length(). •) while(prefLen > s.length()) or pref doesn't match the beginning of s (or prefix is longer than s) 1 - Reduce prefix length by 1 (prefLen--). 2 - If prefLen becomes 0, no common prefix exists - return "". 3 - Update prefix to pref.substring(0, prefLen). 4 - Continue to next string. •) Return the final pref. Complexity - Time - O(S), total number of characters in all strings. Space - O(1), only used variables. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day 39/100 – LeetCode Challenge ✅ Problem: #1984 Minimum Difference Between Highest and Lowest of K Scores Difficulty: Easy Language: Java Approach: Sorting + Sliding Window Time Complexity: O(n log n) Space Complexity: O(1) Key Insight: After sorting, the minimum range in k elements must come from consecutive elements in sorted order. Sliding window of size k finds the minimum difference between first and last element in window. Solution Brief: Sorted the array to bring close values together. Initialized answer with first k elements. Slided window across array, updating minimum difference. Finding minimal range in sorted array with sliding window #LeetCode #Day39 #100DaysOfCode #Sorting #SlidingWindow #Java #Algorithm #CodingChallenge #ProblemSolving #MinimumDifference #EasyProblem #Array #Optimization #DSA
To view or add a comment, sign in
-
-
🪟 Sliding Window — Algorithm When a window moves right by 1 👉 ➖ subtract what leaves ➕ add what enters 🧱 Step 1: Build the first window (ONLY once) Before sliding anything, we must have a window. This gives us: ✅ Initial window sum ✅ Initial max ✅ Initial index 🔁 Step 2: Move the window This single line captures the entire sliding window idea 👇 sum = sum - arr[i - k] + arr[i]; 🧠 What’s happening? The leftmost element exits the window ➖ The next right element enters the window ➕ The rest of the window stays the same 🚫 We never recompute the whole sum ✅ We just adjust the state 🤔 What really changes when the window moves? Only two elements. Everything else is reused. That’s efficiency thinking. 🔄 Evolution of thinking Brute force → you didn’t trust memory and calculated whole, every iteration HashMap → you tried to store everything, in each index pass Sliding Window → “I don’t need everything. I only need what changes.” 🔥 Sliding Window = reuse the previous result by ➖ removing what exits the window ➕ adding what enters the window range 🔖Frontlines EduTech (FLM) #SlidingWindow #DSA #CodingConcepts #ProblemSolving #Java #Algorithms #SoftwareEngineering #LearnToThink
To view or add a comment, sign in
-
-
Day 33/100 – LeetCode Challenge ✅ Problem: #1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold Difficulty: Medium Language: Java Approach: Prefix Sum + Binary Search on Square Size Time Complexity: O(m × n × log(min(m, n))) Space Complexity: O(m × n) Key Insight: Use 2D prefix sum to quickly compute sum of any square submatrix in O(1). For each cell, binary search the maximum square side length starting at that cell with sum ≤ threshold. Solution Brief: Built prefix sum matrix psum for O(1) submatrix sum queries. For each possible starting cell, used binary search to find largest valid square. Tracked global maximum side length across all positions. Optimizing submatrix queries with prefix sum. #LeetCode #Day33 #100DaysOfCode #BinarySearch #Java #Algorithm #CodingChallenge #ProblemSolving #MaxSquareSide #MediumProblem #PrefixSum #Matrix #Optimization #DSA
To view or add a comment, sign in
-
-
🚀 Day 57 of #100DaysOfCode Solved LeetCode Problem #2943 – Maximize Area of Square Hole in Grid. This problem focused on identifying the largest possible square that can be formed after removing horizontal and vertical bars from a grid. The key was to analyze consecutive gaps efficiently and translate them into the maximum square area. Key Learnings: -> Sorting input arrays to simplify gap analysis -> Tracking longest consecutive segments in both dimensions -> Understanding how grid constraints map directly to square geometry -> Writing clean, optimal logic for interval-based problems Language Used: Java -> Runtime: 4 ms (Beats 100.00%) -> Memory: 45.45 MB (Beats 50.00%) Consistent problem-solving, sharper logic, one day at a time 🚀 #LeetCode #Arrays #Geometry #Java #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🌳 LeetCode Solved: Maximum Product of Splitted Binary Tree Key idea wasn’t brute force — it was smart traversal. 💡 Key Insight: Instead of trying all possible splits explicitly (which would be inefficient), the trick is to: 1️⃣ Compute the total sum of the tree once 2️⃣ Traverse again, treating every node as a potential split point 3️⃣ For each node: Calculate subTreeSum Remaining sum = totalSum - subTreeSum Product = subTreeSum * remainingSum 4️⃣ Track the maximum product This turns a complex-looking problem into a simple DFS-based optimization. ⏱ Complexity Time: O(N) Space: O(H) (recursion stack) A great example of how separating calculation from decision-making simplifies complex problems. #LeetCode #BinaryTree #DFS #Java #ProblemSolving #DailyCoding
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
Another One , bro is playing on hard mode with ease 💪🏼