Just solved LeetCode 862: Shortest Subarray with Sum at Least K If you've ever been trapped by a sliding window that just won't slide right, this one is for you! 👇 The Brute Force (O(N²)) The most intuitive approach is to calculate the prefix sum of the array, and then use a nested loop to check the sum of every possible subarray, keeping track of the shortest one that is >= K. The problem? The array length can be up to 10⁵. An O(N²) solution will immediately hit a Time Limit Exceeded (TLE). We need O(N). Normally, to find a shortest/longest subarray, we reach for the Sliding Window technique. But there's a catch: The array contains negative numbers. Because of negative numbers, our prefix sum is NOT monotonically increasing. The standard sliding window is completely broken here. To fix this, we need a way to track prefix sums intelligently. We can use a Double-Ended Queue (Deque) to store tuples of (prefix_sum, index) and force it to be strictly increasing (monotonic). Shrinking the window: As we iterate, we check if current_sum - smallest_prefix_sum_in_deque >= K. If it is, we found a valid subarray! We record the length, and throw away that starting index (pop left). Why? Because any future subarray using that start index would only be longer and therefore worse. Maintaining Monotonicity (Pop Right): What if our current_sum dips and is smaller than the most recent prefix sums in our deque? We can keep popping the back of queue as the older greater prefix sums work but make the subarray longer. This approach has a time complexity of O(n) and a space complexity of O(n) as well as in the worst case, the queue may contain n prefix sum where n: number of elements in the array. #LeetCode #Python #Algorithms #DataStructures #SoftwareEngineering #ProblemSolving #CodingInterviews
LeetCode 862: Shortest Subarray with Sum at Least K
More Relevant Posts
-
🚀 DSA Day — Merge Two Sorted Arrays (LeetCode 88) Today I worked on a classic problem that looks simple but teaches an important optimization technique 👇 🔹 Problem Statement You are given two sorted arrays and need to merge them into one sorted array in-place. Example: nums1 = [1, 7, 8, 0, 0, 0], m = 3 nums2 = [2, 5, 6], n = 3 ✅ Output: [1, 2, 5, 6, 7, 8] 🔸 Approach 1: Brute Force ✔ Copy nums2 into nums1 ✔ Sort the entire array ⏱ Time Complexity: O((m+n) log(m+n)) 👉 Simple but not efficient 🔸 Approach 2: Optimized (Two Pointers) 💡 Key Idea: Start filling from the end ✔ Compare last elements of both arrays ✔ Place the larger one at the end ✔ Move pointers accordingly ⏱ Time Complexity: O(m+n) 📦 Space Complexity: O(1) 🔥 Why this works? Because nums1 already has extra space at the end — we use it smartly without shifting elements. 💻 Code Snippet (Optimized) https://lnkd.in/g9Z7yf3d def merge(nums1, m, nums2, n): i = m - 1 j = n - 1 k = m + n - 1 while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while j >= 0: nums1[k] = nums2[j] j -= 1 k -= 1 🎯 Key Takeaway 👉 Always think from the end when dealing with in-place array problems. #DSA #Python #CodingInterview #LeetCode #ProblemSolving #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Day 42/100 – LeetCode Challenge Solved 206. Reverse Linked List today! 🔍 Problem Summary: Given the head of a singly linked list, reverse the list and return the new head. 💡 Approach: Implemented an iterative solution using three pointers (prev, curr, next) to reverse the links efficiently in-place. Also explored the recursive approach to strengthen understanding of linked list manipulation. ⚡ Complexity: • Time Complexity: O(n) • Space Complexity: O(1) (Iterative) 📌 Key Takeaways: Importance of pointer manipulation Handling edge cases like empty list Difference between iterative vs recursive approaches Consistency is key — one step closer to mastering Data Structures & Algorithms! 💪 #LeetCode #100DaysOfCode #DataStructures #Algorithms #CodingJourney #Python #ProblemSolving #LinkedList
To view or add a comment, sign in
-
-
Insert Interval (LeetCode 57) - Medium I explored a more optimized way to handle intervals when the input is already sorted. Instead of re-sorting everything, I learned how to process the intervals in a single linear pass. Key Learnings: * Linear Scan: Since the input is sorted, we can divide the problem into three logical parts: Before overlap, During overlap (merge), and After overlap. * In-place Merging: For the overlapping part, we simply update the start to the min and the end to the max of the conflicting intervals. * Efficiency: No sorting means we save time! This approach is much faster for pre-sorted data. Complexity: ⏱️ Time Complexity: O(N) — because we only iterate through the list once. 📂 Space Complexity: O(N) — to store the result list. Consistency is the key #LeetCode #CodingJourney #Blind75 #SDEPrep #DataStructures #Python #ProblemSolving #TechCommunity
To view or add a comment, sign in
-
-
Don't flatten what naturally has structure. It's tempting to model everything in a single class. Easy to write, easy to read, at least until your data grows. This is where most codebases start, with just one model. But with model composition, each model has a single responsibility. And Pydantic handles nested validation automatically. Structure your models the way your domain is actually structured. The code gets cleaner, the errors get clearer, and reuse becomes obvious. This and other real-world modelling patterns are covered in Practical Pydantic: 👉 https://lnkd.in/eGiB7ZxU Model your domain. Not just your data. #Python #Pydantic #Data #Models #Patterns
To view or add a comment, sign in
-
-
Day 8: Cracking the Subarray Sum Logic 🧩 💡 How I solved it: Instead of a slow O(n^2) brute-force approach, I used the Prefix Sum + Hash Map technique to achieve a highly efficient O(n) solution. *Tracked the Running Sum: Maintained a current_sum as I traversed the array. *The Difference Trick: For every element, I checked if (current_sum - k) existed in my hash map. If it did, it meant a subarray summing to k had just been completed. *Frequency Mapping: Used a dictionary to store how many times each prefix sum occurred, ensuring every valid subarray was counted. *Handled the Edge Case: Initialized the map with {0: 1} to correctly catch subarrays that sum to k starting right from index 0. 🧠 Key Takeaway: *Space-Time Optimization: By using O(n) space for the hash map, I eliminated the need for nested loops, drastically speeding up the execution. *Mathematical Insight: Reinforced the logic that Sum(i, j) = PrefixSum(j) - PrefixSum(i-1). This is a powerhouse pattern for any range-sum problem. One step closer to mastering Data Structures and Algorithms! 💻🔥 The logic is getting sharper every day! 📈🤝 #100DaysOfCode #DSA #Python #ProblemSolving #StriverA2ZSheet #CodingJourney
To view or add a comment, sign in
-
-
Day 9: Mastering the Two-Sum Strategy 🎯 💡 How I solved it: Instead of a slow O(n^2) nested loop to find pairs, I used a One-Pass Hash Map to achieve a lightning-fast O(n) solution. Target Calculation: For every number n, I calculated the diff (target - n) needed to complete the pair. Instant Lookup: I checked if this diff already existed in my prev_map. If it did, I immediately returned the indices. Dynamic Mapping: If the complement wasn't found, I stored the current number and its index {val: index} in the map to be used for future lookups. The Single Pass: This allowed me to find the answer in just one trip through the array. 🧠 Key Takeaway: Efficiency First: Trading a tiny bit of memory O(n) space for a massive gain in speed O(n) time is the hallmark of an optimized algorithm. Complement Logic: Learned that searching for a "pair" is really just searching for a "complement." Dictionary Power: This project reinforced how Python’s dictionary lookups are O(1) on average, making them the ultimate tool for reducing time complexity. One step closer to mastering Data Structures and Algorithms! 💻🔥 The logic is getting sharper every day! 📈🤝 #100DaysOfCode #DSA #Python #TwoSum #ProblemSolving #StriverA2ZSheet #CodingJourney
To view or add a comment, sign in
-
-
🧩 How Do YOU Solve This ❓ ❓ ❓ 👉 You must find the smallest missing positive integer in an unsorted array. 👉 Your Time Complexity must be O(n) and your Space Complexity O(1). 👉 No sorting allowed, no hash maps. Before coding, YOU must understand these key insights: 1️⃣ For an array of size n, the answer is always between 1 and n+1. This is crucial! 2️⃣ Use the array itself as storage: Since we know valid numbers are only 1 to n, we can use array indices as a "hash". Position 0 represents number 1, position 1 represents number 2, and so on. e.g: [1, 2, 3, 4, 5] => positions are: [0, 1, 2, 3, 4] 3️⃣ Clean before processing: Replace all invalid numbers (≤ 0 or > n) with n+1. They can't be the answer anyway. 4️⃣ Swap into place: Use a while loop to keep swapping each number to its correct position (number k goes to index k-1) until everything that can be placed is placed. 5️⃣ Scan through and return the first index where the expected number is missing. 💡 Making sure the while loop doesn't become O(n²). It stays O(n) because each number gets swapped at most once to its final position across the entire algorithm. #Python #AlgorithmPractice #ProblemSolving #CodingChallenge #DataStructures
To view or add a comment, sign in
-
-
Topic 5/100 🚀 🧠 Topic 5 — Iterators Ever wondered how a for loop actually works behind the scenes? 🤔 This is the concept powering it. 👉 What is it? Iterators are objects that allow you to traverse through data step-by-step using __iter__() and __next__() methods. 👉 Use Case: Used in real-world applications for: Custom data pipelines Streaming data Building your own iterable objects 👉 Why it’s Helpful: Gives full control over iteration Enables custom looping logic Foundation for generators 💻 Example: class Counter: def __init__(self, max): self.max = max self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.max: self.current += 1 return self.current raise StopIteration for num in Counter(3): print(num) 🧠 What’s happening here? We created a custom object that behaves like a loop by controlling how values are returned one by one. ⚡ Pro Tip: If you understand iterators, you’ll unlock how Python handles loops internally. 💬 Follow this series for more Topics #Python #BackendDevelopment #100TopicOfCode #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 189 Problem: Decode String 🔐📜 Today’s problem is a classic stack-based parsing question that tests your ability to handle nested structures. 🧠 Problem Summary You are given an encoded string s. The encoding rule is: 👉 k[encoded_string] → repeat encoded_string exactly k times Constraints: k is a positive integer The string may contain nested patterns Input is always valid (well-formed brackets, no extra spaces) 🎯 Goal: Return the decoded string. 💡 Key Insight The presence of nested brackets makes recursion possible, but using a stack is more intuitive. 👉 Whenever we encounter ], we know a complete pattern is ready to decode. We then: 1️⃣ Extract the string inside the brackets 2️⃣ Extract the number k before it 3️⃣ Repeat the string k times 4️⃣ Push it back to the stack ⚙️ Approach 1️⃣ Traverse the string character by character. 2️⃣ If the character is not ], push it onto the stack. 3️⃣ When encountering ]: Pop characters until '[' → this gives the substring Pop digits to form the number k Repeat the substring k times Push the result back to the stack 4️⃣ At the end, join everything in the stack. 📈 Complexity Time Complexity: O(n) Space Complexity: O(n) ✨ Why This Problem Is Important This problem highlights a key pattern: 🔥 Stack for parsing nested expressions Similar patterns appear in: ➡️ Valid Parentheses ➡️ Basic Calculator problems ➡️ Expression evaluation ➡️ XML/JSON parsing Understanding how to process nested structures using a stack is crucial for many real-world problems. 🔖 #DSA #100DaysOfCode #Day189 #Stack #Strings #Parsing #LeetCode #Algorithms #ProblemSolving #CodingChallenge #InterviewPrep #Python #SoftwareEngineering #DeveloperJourney #TechCommunity #CodingLife
To view or add a comment, sign in
-
-
Day 36 of LeetCoding everyday until I get a J-O-B: Search a 2D Matrix. Today’s secret: The Matrix is fake, and we need to escape it. You are given a grid of numbers and a target. Here is the truth LeetCode doesn't want you to know: If you look at the constraints, the end of one row connects perfectly to the start of the next. It’s not actually a 2D grid. It’s just a single, sorted 1D array that got folded up to intimidate you. The Strategy: The 1D Illusion Because it's technically sorted from top-left to bottom-right, we don't need two binary searches. We just do one. 1. The Bounds: Our pointers are 0 and (ROWS * COLS) - 1. 2. The Math Translation: We find our 1D mid index, but to check the actual value, we have to translate it back to a 2D coordinate: - row = mid // COLS - col = mid % COLS ⚠️ Python Pro-Tip (A Warning): Do NOT name your row variable r if your right pointer is also named r. You will overwrite your boundary, skip your target, and question the validity of your CS degree. Name them row and col. See more: https://lnkd.in/gUki2imQ #LeetCode #Python #BinarySearch #Algorithms #SoftwareEngineering #JobSearch
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
Brilliant solution!