The Indian Engineer

Problem 3254 Find the Power of K-Size Subarrays I

Posted on 4 mins

Array Sliding Window

Problem Statement

Link - Problem 3254

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(vector<int>& nums, int k) {
        if(k==1)
            return nums;

        int size = nums.size();
        vector<int>result(size-k+1,-1);
        int count = 1;
        for(int i=0;i<size-1;i++){

            if(nums[i]+1 == nums[i+1])
                count++;
            else
                count =1;

            if(count >= k)
                result[i+2-k] = nums[i+1];
        }
        return result;

    }
};

Complexity Analysis

| Algorithm                                  | Time Complexity | Space Complexity |
| ------------------------------------------ | --------------- | ---------------- |
| Single-pass traversal with auxiliary array | O(n)            | O(n)             |

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Can we use a brute force solution with nested loops and HashSet?


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