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,3,-1,3,-1]
💡 Note: Windows are [3,2]→-1 (not ascending), [2,3]→3 (consecutive ascending), [3,2]→-1, [2,3]→3, [3,2]→-1.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ k ≤ n
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Find the Power of K-Size Subarrays II INPUT Array nums: 1 i=0 2 i=1 3 i=2 4 i=3 k = 4 Window size = 4 Subarray [1,2,3,4] nums = [1, 2, 3, 4] k = 4, n = 4 ALGORITHM STEPS 1 Track Consecutive Count consecutive elements 2 Sliding Window Move window of size k 3 Check Ascending Verify nums[i+1]=nums[i]+1 4 Compute Power Return max or -1 Consecutive Check: 1 --> 2: 2-1=1 OK 2 --> 3: 3-2=1 OK 3 --> 4: 4-3=1 OK All consecutive! Power=4 FINAL RESULT Only 1 subarray of size 4: [1, 2, 3, 4] Consecutive: YES Ascending: YES Power = max = 4 Output: [4] results.length = n-k+1 = 1 OK - Verified! Key Insight: Use a counter to track consecutive ascending elements. At each position, check if nums[i] = nums[i-1] + 1. If count >= k, the window is valid and power = nums[i]. Otherwise, power = -1. This achieves O(n) time. The optimal approach avoids re-checking each window by maintaining running count of consecutive elements. TutorialsPoint - Find the Power of K-Size Subarrays II | Optimal Solution O(n)
Asked in
Google 25 Microsoft 18 Amazon 15
26.6K 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