#3254
Medium Algorithms Find the power of k size subarrays i
Array Sliding Window
62.1% acceptance
Feb 25, 2026
671
57
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)].
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn results_array(nums: Vec<i32>, k: i32) -> Vec<i32> {
let n = nums.len();
let k = k as usize;
// streak[i] = number of consecutive valid "nums[j+1]==nums[j]+1" edges ending at i
// streak[0] = 0 (no left edge)
let mut streak = vec![0usize; n];
for i in 1..n {
if nums[i] == nums[i - 1] + 1 {
streak[i] = streak[i - 1] + 1;
}
}
// window [l, l+k-1] is valid iff streak[l+k-1] >= k-1
(0..=(n - k))
.map(|l| {
if streak[l + k - 1] >= k - 1 {
nums[l + k - 1]
} else {
-1
}
})
.collect()
}
}