Find the Power of K-Size Subarrays II - Problem
Find the Power of K-Size Subarrays II

You are given an array of integers nums of length n and a positive integer k. Your task is to analyze the "power" of every possible subarray of size k.

The power of an array is defined as:
• Its maximum element if all elements are consecutive integers in ascending order
-1 otherwise

For example:
[1, 2, 3] has power 3 (consecutive ascending)
[2, 1, 3] has power -1 (not consecutive ascending)
[5, 6, 7, 8] has power 8 (consecutive ascending)

Return an array results where results[i] is the power of the subarray starting at index i.

Input & Output

example_1.py — Basic consecutive sequence
$ Input: nums = [1,2,3,4], k = 3
Output: [3,4]
💡 Note: Subarray [1,2,3] is consecutive ascending with max 3. Subarray [2,3,4] is consecutive ascending with max 4.
example_2.py — Mixed valid/invalid subarrays
$ Input: nums = [2,2,2,2,2], k = 4
Output: [-1,-1]
💡 Note: All elements are the same, so no subarray has consecutive ascending elements.
example_3.py — Large gap between consecutive
$ Input: nums = [3,2,3,2,3,2], k = 2
Output: [-1,-1,-1,-1,-1]
💡 Note: No adjacent pair forms a consecutive ascending sequence.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ k ≤ n
  • -109 ≤ nums[i] ≤ 109
  • Follow-up: Can you solve this in O(n) time?

Visualization

Tap to expand
Sliding Window: Track Consecutive Count123567Window 1: [1,2,3] → Count=3 → Power=3Consecutive Count Tracker3[1,2,3]2[2,3,5]2[3,5,6]3[5,6,7]Final Result: [3, -1, -1, 7]
Understanding the Visualization
1
Initialize Window
Set up first k-size window and count consecutive elements
2
Slide and Check
Move window one position, check if new element extends sequence
3
Update Counter
Increment consecutive count or reset to 1 based on continuity
4
Record Power
If count ≥ k, record max element; otherwise record -1
Key Takeaway
🎯 Key Insight: By tracking the consecutive count as we slide the window, we avoid redundant checks and achieve O(n) time complexity instead of O(n×k).
Asked in
Google 28 Amazon 22 Microsoft 18 Meta 15
23.4K 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