Problem Description
Given an array of integers nums and a positive integer k, you need to find the "power" for every contiguous subarray of size k. A subarray’s power is defined as its maximum element if all elements in the subarray are consecutive and sorted in ascending order; otherwise, the power is -1. Return an array where each element corresponds to the power of the respective subarray.
Key Insights
- The condition "consecutive and sorted" implies that for any valid subarray, each adjacent element difference must be exactly 1.
- For a subarray of length k, check that every adjacent pair satisfies (nums[i+1] - nums[i] == 1). This is equivalent to ensuring that the sum of these "differences-satisfied" flags is k - 1.
- Use a sliding window (or prefix sum array on a differences array) to efficiently compute this for each subarray.
- When the subarray meets the criteria, the maximum value (because the array is sorted ascending) is the last element of the subarray.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array, since we make a single pass to compute the differences and another pass to evaluate each window. Space Complexity: O(n), primarily for the differences array (or prefix sum array).
Solution
We first precompute a differences array where each element is 1 if the difference between consecutive elements in nums is exactly 1, and 0 otherwise. For k = 1, every single element is trivially valid. Then, we construct a prefix sum array of the differences. For each subarray starting at index i, the sum of differences over that window (which spans indices from i to i+k-2) should equal k - 1 if it is a valid subarray. If valid, the power is the last element in the subarray; otherwise, the power is -1. This approach ensures that each subarray is checked in constant time after the preprocessing step.