Find the Power of K-Size Subarrays I - Problem
Find the Power of K-Size Subarrays I
You are given an array of integers
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
Goal: Return an array
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
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code