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
Find Power of K-Size Subarrays (k=3)Input:12356Window 1:123Consecutive ✓ → Power = 3Window 2:235Not consecutive ✗ → Power = -1Window 3:356Not consecutive ✗ → Power = -1Output: [3, -1, -1]
Understanding the Visualization
1
Input Array
Given array nums and window size k
2
Check Windows
For each k-size subarray, verify if consecutive ascending
3
Output Powers
Return max element if valid, -1 otherwise
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently track consecutive count and avoid redundant checks
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