Find the Power of K-Size Subarrays II - Problem
You are given an array of integers nums of length n and a positive integer k.
The power of an array is defined as:
- Its maximum element if all of its elements are consecutive and sorted in ascending order.
- -1 otherwise.
You need to find the power of all subarrays of nums of size k.
Return an integer array results of size n - k + 1, where results[i] is the power of nums[i..(i + k - 1)].
Input & Output
Example 1 — Basic Consecutive Sequence
$
Input:
nums = [1,2,3,4], k = 4
›
Output:
[4]
💡 Note:
The subarray [1,2,3,4] has all elements consecutive and sorted in ascending order. The maximum element is 4, so the power is 4.
Example 2 — Mixed Consecutive and Non-consecutive
$
Input:
nums = [2,2,2,2,5,5,5,8], k = 3
›
Output:
[-1,-1,-1,-1,-1,-1]
💡 Note:
No subarray of size 3 has consecutive ascending elements. All duplicates or gaps prevent consecutive sequences.
Example 3 — Partial Consecutive Sequence
$
Input:
nums = [3,2,3,2,3,2], k = 2
›
Output:
[-1,-1,-1,-1,-1]
💡 Note:
No consecutive pair exists - elements alternate between 3 and 2, so all powers are -1.
Constraints
- 1 ≤ n ≤ 105
- 1 ≤ k ≤ n
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,4,5] with k=3
2
Process
Check each k-sized subarray for consecutive ascending order
3
Output
Return max element if consecutive, -1 otherwise
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently track consecutive element count without rechecking overlaps
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code