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
Power of K-Size SubarraysInput: nums = [1,2,3,4,5], k = 312345Subarray [1,2,3]1→2→3 consecutive ✓ Power = 3234Subarray [2,3,4]2→3→4 consecutive ✓ Power = 4Output: [3, 4, 5]
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
Asked in
Google 25 Microsoft 18 Amazon 15
26.5K Views
Medium Frequency
~25 min Avg. Time
856 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