Find the Power of K-Size Subarrays I - 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 Case
$ Input: nums = [1,2,3,4], k = 3
Output: [3,4]
💡 Note: First subarray [1,2,3] is consecutive ascending, power = 3. Second subarray [2,3,4] is consecutive ascending, power = 4.
Example 2 — Non-consecutive Elements
$ Input: nums = [2,2,2,2,2], k = 4
Output: [-1,-1]
💡 Note: All elements are the same (not ascending), so no subarray has power. Both [2,2,2,2] subarrays return -1.
Example 3 — Gap in Sequence
$ Input: nums = [3,2,3,2,3], k = 2
Output: [-1,-1,-1,-1]
💡 Note: No 2-element subarray has consecutive ascending elements: [3,2], [2,3], [3,2], [2,3] all have gaps or are not ascending.

Constraints

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

Visualization

Tap to expand
Power of K-Size Subarrays INPUT nums array: 1 i=0 2 i=1 3 i=2 4 i=3 k = 3 Subarrays of size k: [1, 2, 3] at i=0..2 [2, 3, 4] at i=1..3 n - k + 1 = 2 subarrays ALGORITHM STEPS 1 Slide Window Track consecutive count 2 Check Consecutive nums[i] = nums[i-1] + 1? 3 Update Counter count++ or reset to 1 4 Compute Power count >= k ? max : -1 Processing: [1,2,3]: 1-->2-->3 All consecutive! max=3 [2,3,4]: 2-->3-->4 All consecutive! max=4 FINAL RESULT Output Array: 3 4 results = [3, 4] results[0] = 3 [1,2,3] is consecutive Power = max = 3 results[1] = 4 [2,3,4] is consecutive Power = max = 4 Key Insight: Use a sliding window with a consecutive counter. When nums[i] = nums[i-1] + 1, increment counter; otherwise reset to 1. If counter >= k, the window has k consecutive numbers, so power = nums[i]. Time: O(n), Space: O(1). No need to check entire subarray each time - just track running count! TutorialsPoint - Find the Power of K-Size Subarrays I | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
456 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