Day 27 of #30DaysOfCode with Educative Challenge: Moving Average from Data Stream (Easy) Core Idea: Maintain a running sum over a fixed-size window The Pattern: Queue-backed sliding window Keep the last N values in a queue and maintain their running sum. Each new value is added to the queue and the sum, and when the window is full, the oldest value is removed and subtracted from the sum. Why It Works Here: The moving average can be updated in constant time by adjusting the sum incrementally instead of recomputing it over the entire window each time. This makes the structure efficient even for long-running streams. Production Lesson: This is the same pattern used in lightweight monitoring and rate calculations—CPU load averages, rolling error rates, or moving metrics can all be tracked with a small buffer and an incremental update instead of full recomputation. Edge Worth Remembering: When the stream has fewer values than the window size, the average is taken over the actual count in the buffer, not the configured window size. #Educative #Python #SoftwareEngineering #ContinuousLearning #ProblemSolving
Maintain Running Sum with Queue-Backed Sliding Window
More Relevant Posts
-
🗓 Day 64 / 100 – #100DaysOfLeetCode 📌 Problem 1339: Maximum Product of Splitted Binary Tree Today’s problem combined tree traversal with optimization logic. The task was to split a binary tree into two subtrees by removing exactly one edge, such that the product of the sums of the two resulting subtrees is maximized. 🧠 My Approach: First, computed the total sum of all nodes in the tree. Used a post-order DFS traversal to calculate the sum of each subtree. For every subtree: Considered it as one part after the split. The other part would have sum: total_sum − subtree_sum Calculated the product of these two values. Tracked the maximum product across all possible splits. Returned the result modulo 109+710^9 + 7109+7, as required. Post-order traversal works perfectly here because subtree sums must be known before evaluating the split. 💡 Key Learning: This problem reinforced: ✔ how post-order DFS is ideal for subtree-based calculations ✔ combining traversal with optimization criteria ✔ thinking globally (total sum) while evaluating local decisions (each split) A great example of how tree problems often require two passes: one for data collection and one for optimization. Another strong tree-based DP-style problem completed 🌳🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #BinaryTree #DFS #TreeDP #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
Day 2/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 242 – Valid Anagram (Easy) At first glance, the problem looks simple: 👉 How do we check if two strings are just rearrangements of each other? The idea is straightforward. If two strings are anagrams, they must: 1️. Have the same length 2️. Contain the same characters with the same frequency So I started by checking the length. Then I sorted both strings and compared them. If the sorted versions match, the strings are anagrams. class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s)!=len(t): return False return sorted(s)==sorted(t) ⏱ Time | Space: O(n log n) | O(n) 📌 Key Takeaway: Problems like this highlight a recurring pattern in DSA. Sorting and frequency counting are powerful tools for string manipulation. #leetcode #dsa #python #strings #coding #codingchallenge #problemSolving #learning
To view or add a comment, sign in
-
-
🗓 Day 63 / 100 – #100DaysOfLeetCode 📌 Problem 1161: Maximum Level Sum of a Binary Tree Today’s problem focused on tree traversal and level-wise aggregation. The task was to find the level in a binary tree that has the maximum sum of node values, with levels numbered starting from 1. 🧠 My Approach: Used Breadth-First Search (BFS) to traverse the tree level by level. For each level: Calculated the sum of all node values at that level. Compared it with the maximum sum seen so far. Kept track of: the current level number the level with the maximum sum Returned the smallest level number in case of a tie, as required. This level-order traversal makes the solution both intuitive and efficient. 💡 Key Learning: This problem reinforced: ✔ how BFS naturally fits level-based tree problems ✔ careful tracking of level indices during traversal ✔ handling ties correctly based on problem constraints Tree problems often become much simpler once the right traversal strategy is chosen. Another solid step forward in mastering binary tree patterns 🌳🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #BinaryTree #BFS #TreeTraversal #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
DSA Daily — Hashing Pattern LeetCode 349: Intersection of Two Arrays Day 14 of staying consistent with problem solving Today’s problem was a simple but important example of how sets simplify array problems when uniqueness is a requirement. We’re given two arrays and asked to return their intersection — with no duplicate elements in the result. This problem clearly signals the use of hashing. Key observations: - The result must contain unique elements only - Order does not matter - Fast lookup is more important than maintaining positions Core idea: - Convert one array into a set to remove duplicates and enable O(1) lookup - Traverse the second array - If an element exists in the set, add it to the result set - Using a set for the result automatically ensures uniqueness. Complexity: Time: O(n + m) Space: O(n + m) (sets for lookup and result) Sets are especially useful for intersection-type problems on arrays. This problem fits well with earlier hashing-based questions and reinforces how choosing the right data structure can make solutions both cleaner and more efficient. On to the next one 🚀 #DSADaily #Hashing #LeetCode #ProblemSolving #Python
To view or add a comment, sign in
-
-
Solved LeetCode 944 – Delete Columns to Make Sorted 🧠📊 This problem looks simple at first, but it’s a great reminder that clear thinking beats complex logic. 🔍 Problem in short: - You’re given multiple strings of equal length. Imagine them stacked one below another, forming a grid. Your task is to delete columns that are NOT lexicographically sorted from top to bottom and return how many such columns exist. 🧠 How I approached it: 1️⃣ First, I visualized the strings as a table where: - Each row is a string - Each column contains characters from all strings at that position 2️⃣ Then, I checked each column independently: - Start from the top row - Compare every character with the one directly below it 3️⃣ If at any point: - The upper character is greater than the one below → That column is not sorted 4️⃣ The moment a column fails this condition: - I mark it for deletion - Move on to the next column (no need to check further for that one) 5️⃣ Finally, I count how many columns were marked for deletion. ✨ Key takeaway - You don’t always need advanced data structures. - Sometimes, a simple comparison + clean iteration is all it takes. #LeetCode #DSA #ProblemSolving #Python #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Python with DSA — Day 33 What I worked on: Prime checks: moved from naive divisibility to the √n optimization and the 6k±1 rule to cut unnecessary iterations. Time complexity intuition: compared O(n) vs O(√n) for primality tests; saw how early exits change best/worst cases. Clean loops & edge cases: handled n <= 1, negative inputs, and printed primes from 1–100 with a tight loop. Key snippet (conceptual): Idea: Only test divisors up to √n; if none divide, the number is prime. #Day33 #PythonWithDSA #DataStructures #DSAJourney #ProblemSolving #PythonProgramming #SoftwareEngineer
To view or add a comment, sign in
-
-
🗓 Day 66 / 100 – #100DaysOfLeetCode 📌 Problem 865: Smallest Subtree with All the Deepest Nodes Today’s problem focused on binary tree depth analysis. The goal was to find the smallest subtree that contains all the deepest nodes in the tree. 🧠 My Approach: Used Depth-First Search (DFS) to compute information bottom-up. For each node, tracked: the maximum depth reachable from that node, and the candidate subtree root that contains all deepest nodes. Compared depths of left and right subtrees: If both sides have the same depth → the current node is the answer. Otherwise, propagated the deeper side upward. Returned the node that satisfies the condition for all deepest nodes. This approach cleanly combines depth calculation with subtree selection in a single traversal. 💡 Key Learning: This problem reinforced: ✔ how returning multiple values from DFS simplifies logic ✔ thinking bottom-up for tree optimization problems ✔ identifying the exact node where depths converge Tree problems often become elegant once the right recursive structure is identified 🌳🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #BinaryTree #DFS #TreeTraversal #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
Today I went down a rabbit hole: Queue + BFS 🕳️🐇 I started with a question: 🧐 When people say BFS, why do they always bring up a queue? Here’s what I learned: ✅ Queue basics (Python): Queue = FIFO (first in, first out) 🚶♂️➡️🚶♀️ In Python, collections.deque is the right tool because popleft() is O(1) ⚡ list.pop(0) looks similar, but it becomes O(n) because everything shifts left 🐢 ✅ What BFS is actually doing: BFS explores a graph level by level 🪜 Start node → all nodes 1 step away → then 2 steps away → and so on. That “level order” is exactly why BFS uses a queue. ✅ The big missing piece: seen/visited 👀 Without seen, cycles can make BFS loop forever 🔁😬 So marking nodes as visited (usually when enqueuing) keeps traversal correct and efficient. 🤔 Fun detail: neighbor order changes traversal order A: [B, C] vs A: [C, B] → same BFS, different visitation sequence. #Python #DSA #BFS #Queue #Deque #Algorithms #InterviewPrep #BackendEngineering
To view or add a comment, sign in
-
-
Day 13/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 268 – Missing Number (Easy) 🧠 Approach: Sort the array and compare each index with its value. If at any index i, nums[i] ≠ i, then i is the missing number. If all indices match, then the missing number is n. 💻 Solution: class Solution: def missingNumber(self, nums: List[int]) -> int: nums.sort() for i in range(len(nums)): if i!=nums[i]: return i else: return i+1 ⏱ Time | Space: O(n log n) | O(n) 📌 Key Takeaway: When numbers are expected to be in a fixed range (0 to n), comparing indices with values is a powerful way to detect what’s missing. #leetcode #dsa #python #problemSolving
To view or add a comment, sign in
-
-
🧠 LEETCODE CONSISTENCY SERIES 🚀 Day 1️⃣2️⃣ of 365 Days 🔁 📘 Topic: Number Problem 🧩 Problem: 3Sum (LeetCode #15) ⏱ Time Taken: ~65 minutes 💡 Key Idea: Sort the array first, then fix one element and use the two-pointer technique to find pairs that sum to the negative of the fixed element. Fix nums[i] Use left and right pointers to search for nums[left] + nums[right] = -nums[i] Move pointers based on sum comparison 🛠 Important Techniques Used: Sorting to simplify duplicate handling Two-pointer approach for optimized searching Skipping duplicates to ensure unique triplets only ⚠ Edge Cases Handled: Duplicate values in input array Arrays with less than 3 elements All zero case → [0,0,0] No valid triplet case → return empty list 🚀 What I learned today: How sorting enables efficient two-pointer traversal Proper duplicate removal at both index and pointer levels Reducing brute-force O(n³) to optimized O(n²) 📌 Next Goal: Solve 4Sum using similar logic Practice more problems on two pointers & hashing Consistency > Motivation 💪 🔗 GitHub: https://lnkd.in/dRGB_B8Z #DSA #LeetCode #Python #ProblemSolving #365DaysOfCode #CodingJourney
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