Apply sliding window techniques
Company: NVIDIA
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Apply sliding window techniques states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Minimum Size Subarray Sum
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^4
- 1 <= s <= 10^9
- All integers in nums are positive (this is what makes the shrink-while-valid invariant correct).
Examples
Input: ([2, 3, 1, 2, 4, 3], 7)
Expected Output: 2
Explanation: The subarray [4, 3] has sum 7 >= 7 and length 2, which is the minimum.
Input: ([1, 4, 4], 4)
Expected Output: 1
Explanation: A single element 4 already reaches the target, so the minimal length is 1.
Hints
- Use two pointers forming a window. Move the right pointer to include elements and grow the running sum.
- Whenever the running sum is >= s, the current window is valid: record its length, then shrink from the left to look for a shorter valid window.
- Because all numbers are positive, removing from the left strictly decreases the sum, so the while-shrink loop is safe and the total pointer movement is O(n).
Longest Substring with At Most K Distinct Characters
Constraints
- 0 <= s.length <= 10^5
- 0 <= k <= 50 (or up to the size of the character set)
- s consists of arbitrary characters; an empty string or k = 0 should return 0.
Examples
Input: ("eceba", 2)
Expected Output: 3
Explanation: The substring "ece" uses exactly 2 distinct characters and has length 3, the longest possible.
Input: ("aa", 1)
Expected Output: 2
Explanation: Only one distinct character, so the whole string of length 2 qualifies.
Hints
- Maintain a window [left, right] and a hash map from character to its count inside the window.
- Extend the right edge each step. When the map has more than k distinct keys, shrink from the left, decrementing counts and deleting a key when its count hits zero.
- After every adjustment the window is valid (at most k distinct), so update the best length with right - left + 1. Handle k = 0 and the empty string by returning 0.