Find the Power of K-Size Subarrays II Problem
Description
LeetCode Problem 3255.
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)].
Example 1:
Input: nums = [1,2,3,4,3,2,5], k = 3
Output: [3,4,-1,-1,-1]
Explanation:
There are 5 subarrays of nums of size 3:
- [1, 2, 3] with the maximum element 3.
- [2, 3, 4] with the maximum element 4.
- [3, 4, 3] whose elements are not consecutive.
- [4, 3, 2] whose elements are not sorted.
- [3, 2, 5] whose elements are not consecutive.
Example 2:
Input: nums = [2,2,2,2,2], k = 4
Output: [-1,-1]
Example 3:
Input: nums = [3,2,3,2,3,2], k = 2
Output: [-1,3,-1,3,-1]
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^61 <= k <= n
Solution
Approach: Consecutive Run Length
A window is consecutive and ascending exactly when every adjacent pair in it differs by +1. Let f[i] be the length of the run of such pairs that ends at index i: f[i] = f[i-1] + 1 if nums[i] == nums[i-1] + 1, otherwise 1.
The window ending at i (for i >= k - 1) is good when f[i] >= k, and its power is its last element nums[i]. Otherwise the power is -1. One pass is enough, so this is the same solution as Part I and scales to the larger limits.
Complexity: O(n) time and O(n) space.
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1] * n
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
f[i] = f[i - 1] + 1
return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]