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

You are given an array of integers nums and a positive integer k. Your task is to find the power of every subarray of size k.

The power of an array is defined as:
โ€ข Maximum element if all elements are consecutive and sorted in ascending order
โ€ข -1 otherwise

For example, the array [1, 2, 3] has power 3 (consecutive ascending), while [1, 3, 5] has power -1 (not consecutive).

Goal: Return an array results where results[i] is the power of the subarray starting at index i with length k.

Input & Output

example_1.py โ€” Basic consecutive sequence
$ Input: nums = [1,2,3,4], k = 3
โ€บ Output: [3,4]
๐Ÿ’ก Note: Subarray [1,2,3] has consecutive ascending elements, so power = 3. Subarray [2,3,4] has consecutive ascending elements, so power = 4.
example_2.py โ€” Mixed valid/invalid subarrays
$ Input: nums = [2,2,2,2,5,4,3,8], k = 3
โ€บ Output: [-1,-1,-1,-1,-1,-1]
๐Ÿ’ก Note: No subarray of size 3 has consecutive ascending elements. [2,2,2] has duplicates, [2,5,4] is not ascending, [5,4,3] is descending, etc.
example_3.py โ€” Single element window
$ Input: nums = [3,2,3,2,3,2], k = 1
โ€บ Output: [3,2,3,2,3,2]
๐Ÿ’ก Note: Every single element forms a valid consecutive sequence of length 1, so power equals the element itself.

Constraints

  • 1 โ‰ค n โ‰ค 500
  • 1 โ‰ค nums[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค n
  • All elements in nums are distinct

Visualization

Tap to expand
Conveyor Belt: [1, 2, 3, 5, 4, 5, 6, 7]12354567Inspector Window (k=3)โœ“ Consecutive: 1โ†’2โ†’3, Power = 3QCNext Positionโœ— Break at 5: 2โ†’3โ†’5, Power = -1
Understanding the Visualization
1
Initialize Window
Set up first k-size window and count consecutive elements
2
Slide and Update
Move window right, check if new element continues sequence
3
Determine Power
If consecutive count โ‰ฅ k, power = max element, else -1
Key Takeaway
๐ŸŽฏ Key Insight: Track consecutive count as window slides to avoid redundant checks and achieve O(n) time complexity
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
28.4K Views
Medium Frequency
~18 min Avg. Time
847 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