Subarray With Elements Greater Than Varying Threshold - Problem

You are given an integer array nums and an integer threshold.

Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.

Return the size of any such subarray. If there is no such subarray, return -1.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,3,3], threshold = 6
Output: 3
💡 Note: For k=3, threshold/k = 6/3 = 2. The subarray [3,3,3] has all elements > 2, so return 3.
Example 2 — Single Element
$ Input: nums = [6,5,6,5,8], threshold = 7
Output: 1
💡 Note: For k=1, threshold/k = 7/1 = 7. Element 8 > 7, so return 1.
Example 3 — No Valid Subarray
$ Input: nums = [1,1,1,1], threshold = 8
Output: -1
💡 Note: No subarray satisfies the condition since all elements are 1 and 1 ≤ 8/k for any k ≥ 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ threshold ≤ 109

Visualization

Tap to expand
Subarray With Varying Threshold INPUT nums array: 1 i=0 3 i=1 3 i=2 3 i=3 Input Values nums = [1, 3, 3, 3] threshold = 6 Condition For subarray length k: Each element must be > threshold / k ALGORITHM STEPS 1 Sort by value Process elements smallest to largest with indices 2 Union-Find Connect adjacent valid elements into groups 3 Check condition For each element, check if group_size > threshold/val 4 Return result Return valid subarray size or -1 if none Threshold Check k=3: 6/3 = 2 Elements [3,3,3] all > 2 OK - Valid! FINAL RESULT Valid Subarray Found: 1 3 3 3 k = 3 Output 3 Verification Subarray: [3, 3, 3] threshold/k = 6/3 = 2 All elements > 2 -- OK Key Insight: Use Union-Find to efficiently track connected components of valid elements. Process elements in sorted order (smallest first). For each element with value v, merge with neighbors and check if component size k satisfies: v > threshold/k. This achieves O(n log n) time complexity. TutorialsPoint - Subarray With Elements Greater Than Varying Threshold | Optimal Solution (Union-Find)
Asked in
Google 12 Facebook 8 Amazon 6
18.5K Views
Medium Frequency
~35 min Avg. Time
412 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