🔥 Day 85 of #100DaysOfCode Today’s challenge: LeetCode: Sliding Window Maximum 🪟📈 📌 Problem Summary Given an integer array nums and a window size k, return the maximum value in each sliding window of size k. Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output → [3,3,5,5,6,7] 🧠 Approach: Monotonic Deque (Optimal Solution) Instead of recalculating the max for every window (which would be slow), we maintain a deque that stores indices in decreasing order of values. ⚙️ Key Steps: Remove elements from the back of deque → if they are smaller than the current element (because they’ll never be maximum again). Add current index to the deque. Remove front index → if it is outside the current window. The front of deque always contains ✅ the maximum element of the window. 🚀 Why This Works The deque always maintains elements in decreasing order, so the largest element is always at the front. ⏱ Time Complexity: O(n) Each element is added and removed at most once. 💾 Space Complexity: O(k) ⚡ Performance Runtime: 30 ms Better than ~70% submissions. 💡 What I Learned When you need max/min in a sliding window → think Monotonic Queue. Removing useless elements early keeps solution efficient. Advanced data structure knowledge gives huge performance gains. Two Pointers → Sliding Window → Monotonic Queue The progression is real. 🔥 On to Day 86 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Deque #Java #DSA #InterviewPrep
LeetCode Sliding Window Maximum Challenge
More Relevant Posts
-
Most people would return this answer: [2, 2] But the correct answer is: [2] Why? 🚀 Day 64/365 — DSA Challenge Solved: Intersection of Two Arrays The task: Given two arrays, return their intersection. But there are two conditions: • The element must exist in both arrays • The result must contain only unique values Example: nums1 = [1,2,2,1] nums2 = [2,2] Output: [2] Even though 2 appears multiple times, it should appear only once in the result. 💡 My Approach (Simple Logic) Step 1 Loop through every element of nums1. Step 2 Check if that number exists in nums2. Step 3 Before adding it to the result, make sure it hasn't already been added. To keep the code clean, I used three methods: intersection() Main method that loops through nums1 and builds the result. existsInArray(num, arr) Checks if a number exists in another array. existsInArray(num, arr, length) Checks duplicates only inside the filled part of the result array. Example walkthrough: 1 -> not in nums2 -> skip 2 -> exists -> add 2 -> already added -> skip 1 -> skip Final output: [2] ⏱ Time Complexity: O(n × m) 📦 Space Complexity: O(n) Day 64/365 complete. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🔥 Day 92 of #100DaysOfCode Today’s challenge: LeetCode – Search a 2D Matrix 🧩📊 📌 Problem Summary You are given a matrix where: Each row is sorted in ascending order The first element of each row is greater than the last element of the previous row 👉 This means the entire matrix behaves like a sorted 1D array. Goal: Return true if target exists, otherwise false. 🧠 Approach: Double Binary Search Instead of scanning row by row, we use Binary Search twice. Step 1️⃣: Find the Correct Row Binary search on rows: If target > last element of row → move down If target < first element of row → move up Otherwise → target must be inside this row Step 2️⃣: Binary Search Inside That Row 💡 Why This Works? Because: Rows are sorted Row ranges don’t overlap It behaves like a flattened sorted array. ⏱ Time Complexity: O(log m + log n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Beats 100% submissions Memory: Very efficient 🔥 🧠 Key Learning Whenever: Data looks 2D But ordering behaves like 1D 👉 Think Binary Search Optimization Stack → Sliding Window → Queue → Binary Search → Matrix Search Patterns are connecting now 💪 On to Day 93 🚀 #100DaysOfCode #LeetCode #BinarySearch #Matrix #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
🔥 Day 94 of #100DaysOfCode Today’s problem: LeetCode – Online Stock Span 📈 📌 Problem Summary Design a class StockSpanner that calculates the stock span for each new price. 👉 The span of a stock’s price today is the number of consecutive days (including today) the price was less than or equal to today’s price. Example input: [100, 80, 60, 70, 60, 75, 85] Output: [1, 1, 1, 2, 1, 4, 6] 🧠 Approach: Monotonic Stack (Decreasing Stack) This is another powerful Next Greater Element pattern, but optimized for streaming input. Instead of storing just prices, we store: {price, span} ⚙️ Core Logic (in next(price)): 1️⃣ Initialize span = 1 2️⃣ While stack is not empty AND top price ≤ current price: Add popped span to current span 3️⃣ Push {price, span} into stack 4️⃣ Return span 💡 Why Store Span Instead of Index? Because: It compresses previous smaller values into one value. Avoids recalculating spans repeatedly. Makes each element pushed & popped only once. ⏱ Time Complexity: O(n) amortized Each price is pushed once and popped once. 💾 Space Complexity: O(n) 🚀 Performance Runtime: 30 ms Beats ~72% Clean and optimal solution ✔️ 🧠 Pattern Insight Problems like: Daily Temperatures Next Greater Element Stock Span 👉 All use Monotonic Stack Stack mastery getting stronger 🔥 On to Day 95 🚀 #100DaysOfCode #LeetCode #MonotonicStack #StockSpan #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
Day 17/60: Why calculate the same sum repeatedly when you can just SLIDE the window? 🪟⚡ Body: Entering the next phase of Array manipulation today! I learned how to drastically optimize code using the Sliding Window Technique. Instead of using a nested loop to find the maximum sum of a subarray ($O(N \times K)$), I created a 'window' of size K. As the window slides forward, I simply add the new element and subtract the one left behind. Boom! Time complexity reduced to $O(N)$! Today’s Checklist: ✅ Coded the Maximum Sum Subarray using the Sliding Window logic. ✅ Mastered Syllogism in Logical Reasoning. Learned the golden rule: Never assume relationships; always draw Venn Diagrams to guarantee 100% accuracy! ⭕ The logic is getting sharper every day. Onwards! 🚀 Tags: #Java #DataStructures #Algorithms #SlidingWindow #PlacementPrep #MCA #CodingJourney #LogicalReasoning
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 20/100 — Bit Manipulation & Modular Arithmetic! Today’s Problem: 1680. Concatenation of Consecutive Binary Numbers 🔹 The Goal: Given an integer $n$, concatenate the binary representations of numbers from $1$ to $n$ into a single string and return its decimal value modulo $10^9 + 7$. 🔹 The Insight: At first glance, this looks like a string problem, but building a massive binary string is a recipe for a Memory Limit Exceeded (MLE) error. The trick is to realize that when you "append" a new number $i$ to your current result, you are essentially shifting your current value to the left by the number of bits in $i$ and then adding $i$. 🔹 The Difficulty: The numbers grow exponentially. To keep things under control, we apply the property of modular arithmetic: $$(A + B) \pmod M = ((A \pmod M) + (B \pmod M)) \pmod M$$ The real challenge? Knowing when the "bit length" of your current number increases (e.g., when moving from 3 to 4, you go from 2 bits to 3 bits). ✨ Achievement: Successfully bypassed string manipulation entirely to create a pure mathematical $O(n)$ solution. 🔍 Steps followed: ✔ Bit-Width Tracking: Monitored when $i$ reached a power of 2 to increment the shift amount. ✔ Efficient Shifting: Used (ans << bitLength) | i to concatenate values at the bit level. ✔ Modular Discipline: Applied the modulo at every step to prevent integer overflow. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ Thirteen days in and the "bit-shifting" logic is starting to feel like second nature. Onward! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #BitManipulation #MathAlgorithms #SoftwareEngineer #Optimization
To view or add a comment, sign in
-
-
Day - 104 Recover Binary Search Tree The problem - You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant O(1) space solution? Brute Force - Perform inorder traversal to collect all values in an array, identify the two swapped elements, store their positions, traverse the tree again to find and swap them back. This gives O(n) time and O(n) space for storing all node values. Approach Used - •) Declare first (first swapped node), second (second swapped node), prev (previous node in inorder traversal). •) Call helper function, helper(root). •) Swap the values, temp = first.val, first.val = second.val, second.val = temp. Helper Function - helper(TreeNode node) •) If node == null, return. •) Traverse left subtree, helper(node.left). •) If prev != null AND prev.val > node.val, - If first == null, set first = prev. - Set, second = node. •) Update, prev = node. •) Traverse right subtree, helper(node.right). Complexity - Time - O(n), where n is number of nodes. Space - O(h), recursion stack depth. Note - In a valid BST, inorder traversal produces a sorted sequence. When two nodes are swapped, it creates violations where prev.val > current.val. For adjacent swaps, there's one violation; for non-adjacent swaps, there are two. By tracking the first and second violating nodes during inorder traversal, we identify the swapped pair. The algorithm handles both cases by always updating second and only setting first once. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 103 Construct Binary Search Tree from Preorder Traversal The problem - Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. Brute Force - Sort the preorder array to get inorder traversal, then use both preorder and inorder arrays to reconstruct the BST (like standard tree construction). This gives O(n log n) time due to sorting, which is inefficient when BST properties can guide direct construction. Approach Used - •) If preorder.length == 0, return null (empty tree). •) Create root with first element, root = new TreeNode(preorder[0]). •) For i = 1 to preorder.length - 1, insert each element, insert(root, preorder[i]). •) Return root. Helper Function - insert(TreeNode root, int val) •) If val < root.val, insert in left subtree, - If root.left == null, create node, root.left = new TreeNode(val). - Else, recurse left, insert(root.left, val). •) Else (when val > root.val), insert in right subtree, - If root.right == null, create node, root.right = new TreeNode(val) - Else, recurse right, insert(root.right, val). Complexity - Time - O(n x h), where h = height of tree, n is number of nodes. Space - O(h), recursion stack depth. Note - Preorder traversal's first element is always the root. By leveraging BST insertion rules (smaller values go left, larger go right), we can sequentially insert each element from the preorder array. Each insertion automatically finds the correct position, building the BST without needing inorder traversal or sorting. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 87 Binary Tree Level Order Traversal The problem - Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level). Each level should be represented as a separate list. Brute Force - Use recursive DFS to traverse the tree while tracking depth. Store nodes at each depth level in separate lists. This gives O(n) time but requires complex depth tracking and is less intuitive than an iterative approach. Approach Used - •) Create res = new ArrayList<>(), queue = new ArrayDeque<>(). •) If root == null, return empty res. •) Add root to queue. •) While queue is not empty, 1 - Get current level size: size = queue.size(). 2 - Create list = new ArrayList<>(). 3 - While size > 0, - Poll node from queue, node = queue.poll(). - If node.left != null, add to queue: queue.add(node.left). - If node.right != null, add to queue: queue.add(node.right). - Add node value to current level: list.add(node.val). - Decrement size—. 4 - Add current level to result, res.add(list). •) Return res. Complexity - Time - O(n), where n = number of nodes. Space - O(w), where w = maximum width of tree. Note - Use BFS with a queue to traverse level by level. By capturing the queue size at the start of each iteration, we know exactly how many nodes belong to the current level. Process all nodes in that level, adding their children to the queue for the next level. This naturally groups nodes by level without needing depth tracking. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 16 Problem: 1878. Biggest Three Rhombus Sums in a Grid Topic: Array, Matrix, Sorting, Simulation 📌 Quick Problem Sense: You're given an m × n integer grid. A rhombus is a square rotated 45°, you sum only its border cells, not the inside. Find the top 3 distinct rhombus sums across all valid sizes and positions in descending order. A rhombus of size 0 is just a single cell, every cell counts! 🧠 Approach (Simple Thinking): 🔹 Every cell (i, j) can be the center of a rhombus of size r = 0, 1, 2, ... 🔹 Size 0 = just the cell itself, add it directly 🔹 For size r ≥ 1, walk the 4 diagonal sides of the rhombus border 🔹 Start at the top tip (i-r, j) and walk with directions: (+1,+1), (+1,-1), (-1,-1), (-1,+1) 🔹 Each side has exactly r steps, skip the last cell to avoid double counting corners 🔹 Use a TreeSet capped at size 3 to track top 3 distinct sums automatically 🔹 TreeSet handles sorting + deduplication, just poll the top 3 at the end! ⏱️ Time Complexity: Iterating all centers and sizes → O(m × n × min(m,n)²) Manageable for given constraints! 📦 Space Complexity: TreeSet holds at most 3 values → O(1) No extra matrix or prefix array needed! I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/ggewfAsx If you solved it using diagonal prefix sums or a different top-K trick, drop it in the comments, always curious to see how others think about it 💬 See you in the next problem 👋 #Java #ProblemSolving #DSA #CodingInterview
To view or add a comment, sign in
-
-
#100DaysOfCode 🚀 👉Solved: LeetCode 75 – Sort Colors The goal was to sort an array containing only three values: 0 (Red), 1 (White), and 2 (Blue) At first glance this looks like a simple sorting problem. But the twist: ❌ No built-in sort ✔ One pass ✔ Constant space The solution uses the famous **Dutch National Flag Algorithm**. Instead of sorting normally, we maintain three pointers: • low → for 0s • mid → current element • high → for 2s Rules: • If nums[mid] == 0 → swap with low • If nums[mid] == 1 → move mid forward • If nums[mid] == 2 → swap with high This allows sorting the array in a single pass. 📌 Key Points: ✔ In-place sorting ✔ One pass algorithm ✔ Constant space usage ✔ Classic three-pointer technique ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this show how powerful pointer techniques can be. Day 15✅ #DSA #Java #LeetCode #Algorithms #ProblemSolving #100DaysOfCode #CodingJourney #LearnInPublic
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