Introduction
Complexity Analysis
Time Complexity: O(n²)
Explanation:
All subarrays are generated.
Space Complexity: O(1)
Explanation:
Only variables are used.Approach 2 : Prefix Sum + Monotonic Deque
Explanation
The optimized solution uses:
Prefix Sum + Monotonic Increasing DequeIdea:
- build prefix sums
- deque stores indices
with increasing prefix sums
Why increasing?
- smaller prefix sum helps
form larger valid difference
Conditions:
- Remove useless larger prefix sums
- Remove valid shortest ranges
- Maintain increasing order
This gives:
- O(n) solution
Steps
- Build prefix sum array.
- Create deque.
- Remove larger prefix sums.
- Check valid subarrays.
- Update shortest length.
- Return answer.
Dry Run
Input:[2,-1,2]
k = 3
Prefix Sum: [0,2,1,3]
Process: 3 - 0 >= 3 Valid subarray found
Length:
3
Final Result: 3
Prefix Sum + Monotonic Deque Code
- Dry Run
Time Complexity: O(n)
Explanation:
Each index is inserted and removed from deque at most once.
Space Complexity: O(n)
Explanation:
Prefix sum array and dequestore up to n elements.Edge Cases
- No valid subarray
- Single element valid
- Negative numbers present
- Large K value
- Entire array required
Why This Problem is Important
Shortest Subarray with Sum ≥ K helps in understanding:
- Prefix sums
- Monotonic deque
- Sliding range optimization
- Efficient subarray processing
- Advanced deque logic
It is one of the most important advanced deque interview problems.
Real-World Applications
Prefix sum and deque concepts are used in:
- Streaming analytics
- Financial monitoring
- Traffic analysis
- Resource allocation
- Real-time threshold systems
Common Mistakes
- Incorrect prefix sum usage
- Wrong deque ordering
- Forgetting larger prefix removal
- Missing no-answer case
Interview Tips
Interviewers often expect:
- Prefix sum explanation
- Monotonic deque reasoning
- O(n) optimization understanding
Always explain:
- why increasing prefix sums matter
- how shortest range is detected
- why deque removes useless indices
Related Questions
- Sliding Window Maximum
- First Negative Integer in Window
- Constrained Subsequence Sum
- Daily Temperatures
- Maximum Sum Circular Subarray
Final Takeaway
The Shortest Subarray with Sum ≥ K problem is a fundamental advanced deque problem that teaches prefix sums and monotonic queue optimization techniques. Understanding this problem builds a strong foundation for advanced range-query and sliding-window interview problems.