Subarray With Elements Greater Than Varying Threshold - Problem

You're given an integer array nums and an integer threshold. Your mission is to find any subarray of length k where every single element is greater than threshold / k.

The twist? The threshold varies based on the subarray length! For a subarray of length k, each element must exceed threshold / k. This means longer subarrays have more lenient per-element requirements, while shorter subarrays demand higher individual values.

Goal: Return the size of any such valid subarray, or -1 if none exists.

Example: If threshold = 10 and you're checking a subarray of length 2, each element must be > 5. For length 5, each element must be > 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 3, 4, 3, 1], threshold = 6
โ€บ Output: 3
๐Ÿ’ก Note: Subarray [3, 4, 3] has length 3. Each element must be > 6/3 = 2. All elements (3, 4, 3) are greater than 2, so this is valid.
example_2.py โ€” No Valid Subarray
$ Input: nums = [1, 1, 1, 1], threshold = 8
โ€บ Output: -1
๐Ÿ’ก Note: For any length k, we need each element > 8/k. Since max element is 1, and 8/4 = 2 > 1, no valid subarray exists.
example_3.py โ€” Length 1 Solution
$ Input: nums = [2, 1, 5, 1, 3, 2], threshold = 3
โ€บ Output: 1
๐Ÿ’ก Note: Element 5 > 3/1 = 3, so subarray [5] of length 1 is valid. This is the smallest valid subarray we can find.

Visualization

Tap to expand
๐Ÿ† Team Performance Budget = 12Find largest team where each player > budget/team_sizeTeam Size 2Each needs > 687Team Size 3Each needs > 4835Team Size 4Each needs > 38215โœ“ Validโœ— Invalid (3 < 4)โœ— Invalid (2,1 < 3)๐ŸŽฏ Optimal: Team Size 2Binary search efficiently finds this without checking all possibilities
Understanding the Visualization
1
Budget Distribution
Total budget (threshold) must be distributed among k team members
2
Individual Requirement
Each member must exceed their allocated budget: threshold/k
3
Find Optimal Team
Binary search finds the largest team size that meets requirements
Key Takeaway
๐ŸŽฏ Key Insight: Binary search on the answer combined with sliding window validation transforms an O(nยณ) brute force into an efficient O(n log n) solution by intelligently narrowing the search space.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

O(nยฒ) subarrays, each requiring O(n) time to validate

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค threshold โ‰ค 1015
  • Note: The threshold can be very large, requiring careful handling of integer division
Asked in
Google 23 Meta 18 Amazon 15 Microsoft 12
22.9K Views
Medium-High Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen