The Indian Engineer

Problem 3255 Find the Power of K-Size Subarrays II

Posted on 6 mins

Array Sliding Window

Problem Statement

Link - Problem 3255

Question

You are given an array of integers nums of length n and a positive integer k.

The power of an array is defined as:

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:

Solution

class Solution {
public:
    vector<int> resultsArray(const vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> result(n - k + 1, -1);
        deque<int> dq;

        vector<int> diff(n - 1);
        for (int i = 0; i < n - 1; ++i) {
            diff[i] = nums[i + 1] - nums[i];
        }


        int consecutive_count = 0;
        for (int i = 0; i < k - 1; ++i) {
            if (diff[i] == 1) consecutive_count++;
        }

        for (int i = 0; i < n; ++i) {

            if (!dq.empty() && dq.front() <= i - k) {
                dq.pop_front();
            }

            while (!dq.empty() && nums[i] >= nums[dq.back()]) {
                dq.pop_back();
            }
            dq.push_back(i);

            if (i >= k - 1) {
                if (consecutive_count == k - 1) {
                    result[i - k + 1] = nums[dq.front()];
                }

                if (i - k + 1 < n - 1) {
                    if (diff[i - k + 1] == 1) consecutive_count--;
                    if (i < n - 1 && diff[i] == 1) consecutive_count++;
                }
            }
        }

        return result;
    }
};

Complexity Analysis

| Algorithm                 | Time Complexity | Space Complexity |
| ------------------------- | --------------- | ---------------- |
| Sliding Window with Deque | O(n)            | O(n)             |

Explanation

Intial Thoughts

My initial approach would be to identify that checking every subarray for being consecutive and sorted would result in O(n^2 log n) complexity which is inefficient for large inputs. I’d also think that the key here lies in finding a relation between each subarray. Then, consider using some sort of caching to reduce the number of computations required, for example the difference array, and a deque to keep track of maximum elements for each subarray. Consider starting by identifying when a subarray is a contiguous sequence of numbers and use the information from the last subarray to efficiently calculate the next one.

Intuitive Analysis

To intuitively solve the problem, notice that all you need to do is keep track of whether the differences between the current subarray’s elements are always equal to 1 and also track the max element for each subarray in O(1) time. After you’ve found the first subarray that’s a contiguous sequence, then notice that adding one element and removing another for the next subarray would only change the result by adding one or removing one element from the consecutive count if the differences are 1. To further optimize the algorithm, consider that each subarray’s max value must also be calculated in O(1) time. You can use a deque for this, it’s similar to a sliding window approach in other problems, where the deque holds the indices of elements in the current subarray, ordered by the value at each index, from largest to smallest. This way, you’re always able to find the max element in O(1) time and be able to efficiently calculate the max of the next subarray.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Let dp[i] denote the length of the longest subarray ending at index i that has consecutive and sorted elements.

Use a TreeMap with a sliding window to check if there are k elements in the subarray ending at index i.

If TreeMap has less than k elements and dp[i] < k, the subarray has power equal to -1.

Is it possible to achieve O(nums.length) using a Stack?


Similar Questions:

Title URL Difficulty
Maximum Sum of Distinct Subarrays With Length K https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k Medium