Longest Period Where Balance Stays Within a Band
Last updated: November 29, 2026
Quick Overview
Given a sequence of end-of-day balances and a tolerance k, find the longest contiguous period in which the maximum balance minus the minimum balance is at most k. Return its length and start index.
SoFi
November 29, 20260
0
0 solved
Given a sequence of end-of-day balances and a tolerance k, find the longest contiguous period in which the maximum balance minus the minimum balance is at most k. Return its length and start index.
A feature like 'your balance has been stable for N days' or a risk signal for erratic cash flow in lending decisions both reduce to this window problem. The interviewer checks monotonic deques for sliding max and min, and that you can argue why each index is pushed and popped once.
What the Interviewer Expects
- Maintains a decreasing deque for the max and an increasing deque for the min
- Shrinks the left edge while the band exceeds k
- Drops deque heads that fall out of the window
- Shows O(n) amortized time
- Validates with a brute-force cross-check on small inputs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you count all valid windows instead of finding the longest?
- What if balances arrive as a stream and you only keep the last 90 days?
- How would you use a sorted multiset instead, and what does it cost?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list of integer balances and k >= 0. Output: (length, start) of the longest window with max - min <= k, earliest on ties, (0, 0) for empty input....
High-Level Design
For a fixed right edge, the valid windows form a suffix: if [l, r] is valid then [l+1, r] is too, so two pointers apply. The challenge is knowing the window's max and min quickly. A deque of indic...