15% off all plans & roadmaps Use code

See plans

Find the Power of K-Size Subarrays I

Updated

TL;DR: For every window of length k, report its maximum if the window is strictly consecutive and ascending, and -1 otherwise. The winning idea is one pass that tracks how long the current run of +1 steps is.

Problem

You get an integer array 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.

Find the power of every subarray of nums with 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 size 3.

- [1, 2, 3] has maximum element 3.
- [2, 3, 4] has maximum element 4.
- [3, 4, 3] is not consecutive.
- [4, 3, 2] is not sorted.
- [3, 2, 5] is 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 <= 500
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= n

Constraints that matter

  • n is at most 500, so O(n * k) work passes the limit. At worst that is about 62,500 pair checks when k is near n / 2. Still aim for O(n), because an interviewer may raise n.
  • Values are at most 10^5, so nums[i] + 1 fits in a 32-bit int. Java and C# need no wider type.
  • A valid window has every step equal to +1, so its values strictly increase. The maximum is always the last element, which removes the need for any max structure.
  • k can be 1 or equal to n. The code must handle a single window and windows of length one.

View on LeetCode

Hints

Hint 1

A window is valid only when each adjacent pair inside it steps up by exactly 1.

Hint 2

For each window, check its adjacent pairs from left to right.

Solution

Intuition

A window is valid only when each adjacent pair inside it steps up by exactly 1. This is fixed-size sliding window work: every window has the same length, and each window shares most of its elements with the one before it.

Picture a tower of plates where each plate must be exactly one size larger than the plate below it. The streak is the height of the correctly stacked tower, and one misfit plate knocks it back to a height of one.

Validity is a property of adjacent pairs, not of the whole window. Any run of +1 steps that is at least k elements long contains a valid window ending at each later position. So you only need the length of the run that ends at the current index.

You can track that length in one pass. Extend the run when the step is +1, and restart it at length 1 otherwise. When the run reaches length k at index i, the window ending at i is valid, and its power is nums[i].

Watch the pattern animation

Worked example

Input: nums = [1, 2, 3, 4, 3, 2, 5], k = 3
Output: [3, 4, -1, -1, -1]
Explanation: Window 1 is [1, 2, 3], a run of +1 steps, so its power is 3. Window 2 is [2, 3, 4], so its power is 4. Windows 3 to 5 each contain a step that is not +1: 4 to 3, 3 to 2, and 2 to 5. Each of them has power -1.

Approach 1: Brute force

For each window, check its adjacent pairs from left to right. Stop at the first pair that does not step up by 1. If every pair passes, the power is the last element of the window. This is the direct reading of the definition, so write it first.

What is slow: consecutive windows share k - 2 adjacent pairs, but the loop checks all of them again for each window. The same pairs are read over and over.

Steps

  1. Set n to the length of nums and create results with n - k + 1 slots.
  2. For each start index i from 0 to n - k, look at the window that starts at i.
  3. Check each adjacent pair nums[j], nums[j + 1] inside the window. If nums[j + 1] is not nums[j] + 1, the window fails.
  4. If the window passes, store its last element. Otherwise store -1.
  5. Return results.

Dry run

Window at i = 0 is [1, 2, 3]. Pair 1 to 2 steps by +1, and pair 2 to 3 does too. The window passes, so store 3.

Window at i = 1 is [2, 3, 4]. Both pairs step by +1, so store 4.

Window at i = 2 is [3, 4, 3]. Pair 3 to 4 passes, but pair 4 to 3 fails, so store -1.

Window at i = 3 is [4, 3, 2]. The first pair 4 to 3 fails at once, so store -1.

Window at i = 4 is [3, 2, 5]. The first pair 3 to 2 fails, so store -1.

Results are [3, 4, -1, -1, -1], which matches the expected output.

Complexity

TimeO(n * k)
SpaceO(1) extra, not counting the output list

Let n be the length of nums. There are n - k + 1 windows, and each window checks at most k - 1 adjacent pairs, so the work is at most (n - k + 1) * (k - 1), which is O(n * k). This bound is reached when most windows pass, such as one long run of +1 steps. The method keeps only a few integer variables beyond the output list, so extra space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        results = []
        for i in range(n - k + 1):
            valid = True
            for j in range(i, i + k - 1):
                if nums[j + 1] != nums[j] + 1:
                    valid = False
                    break
            results.append(nums[i + k - 1] if valid else -1)
        return results

The Fixed Size (Subarray Calculation) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Fixed Size (Subarray Calculation)

Part of Sliding Window

Approach 2: One-pass streak counterOptimalFixed Size (Subarray Calculation)

What is slow in the brute force: it re-reads the same pairs for every window. Each window's validity depends on its pairs, and most of those pairs were already read for the previous window.

The insight that fixes it: a window ending at index i is valid exactly when the run of +1 steps ending at i has length at least k. Moving from one index to the next changes that run by one step, so one counter can track it for every window at once.

The power of a valid window is its last element. A strictly ascending run ends at its maximum, so no extra comparison is needed.

Why it is correct. The streak always equals the length of the longest run of +1 steps that ends at index i. A window ending at i is valid exactly when its last k-1 steps are all +1, meaning the run ending at i has length at least k. A bad step breaks every window that contains it, so restarting the count at 1 never drops a valid window.

Steps

  1. Create results with n - k + 1 slots, each set to -1.
  2. Set streak to 0. Walk i from 0 to n - 1.
  3. If i > 0 and nums[i] == nums[i - 1] + 1, add 1 to streak. Otherwise set streak = 1, because nums[i] starts a new run.
  4. If i >= k - 1 and streak >= k, set results[i - k + 1] = nums[i].
  5. After the loop, return results.

Dry run

The table traces nums = [1, 2, 3, 4, 3, 2, 5] with k = 3. The window column shows the last three values at each index.

inums[i]step checkstreakwindow ending at iresults
01no previous value, start a run1not full yet[-1, -1, -1, -1, -1]
122 = 1 + 1, extend2not full yet[-1, -1, -1, -1, -1]
233 = 2 + 1, extend3[1, 2, 3][3, -1, -1, -1, -1]
344 = 3 + 1, extend4[2, 3, 4][3, 4, -1, -1, -1]
433 is not 4 + 1, reset1[3, 4, 3][3, 4, -1, -1, -1]
522 is not 3 + 1, reset1[4, 3, 2][3, 4, -1, -1, -1]
655 is not 2 + 1, reset1[3, 2, 5][3, 4, -1, -1, -1]

At i = 4 the streak is 1, which is below k = 3, so the slot for that window stays -1. The final results are [3, 4, -1, -1, -1].

Complexity

TimeO(n)
SpaceO(1) extra, not counting the output list

Let n be the length of nums. The loop runs n times, and each iteration does a fixed amount of work: one comparison, one update of streak, and at most one write into results. Each slot of results is written at most once, so the writes total at most n - k + 1. Only streak, i and a few temporaries live outside the output, so the extra space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        results = [-1] * (n - k + 1)
        streak = 0
        for i in range(n):
            # Extend the +1 run, or restart it at length 1
            if i > 0 and nums[i] == nums[i - 1] + 1:
                streak += 1
            else:
                streak = 1
            # The window ending at i is valid when the run covers k elements
            if i >= k - 1 and streak >= k:
                results[i - k + 1] = nums[i]
        return results

Common mistakes

  • streak = 0 in the reset branch. The current element already forms a run of length 1, so the reset must set streak = 1. With 0, every count is one short, and k = 1 never passes.
  • results[i] = ... in place of results[i - k + 1]. The output has n - k + 1 slots, and the window ending at i starts at i - k + 1. Map the window end to its slot.
  • Reading nums[i - 1] when i is 0. Python silently reads nums[-1], while Java and C++ fail at runtime. Put the i > 0 check before the comparison.
  • Writing results[i - k + 1] before checking i >= k - 1. In Python a negative index writes from the end of the list and corrupts a valid slot. Check the bound first.
  • streak == k in place of streak >= k. A run of 4 with k = 2 still has a valid window ending at each later position. Test [1, 2, 3, 4] with k = 2 to catch this.

Edge cases

  • k = 1. Each window holds one element, which is always consecutive and sorted, so the output equals nums. For [5] with k = 1, expect [5].
  • k = n. There is one window. The answer is the last element if the whole array is a +1 run, and -1 otherwise.
  • All equal values, such as [2, 2, 2, 2, 2] with k = 4. Equal neighbours do not step by 1, so every window gives -1.
  • Duplicates that break a run, such as [1, 2, 2, 3] with k = 2. The windows are [1, 2] giving 2, [2, 2] giving -1, and [2, 3] giving 3, so expect [2, -1, 3].
  • A run longer than k, such as [1, 2, 3, 4] with k = 2. Expect [2, 3, 4], which checks the >= comparison.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find the Power of K-Size Subarrays I, with how to answer them.

Unlock the follow-ups

Find the Power of K-Size Subarrays I FAQ

What is the time complexity of Find the Power of K-Size Subarrays I?

The one-pass streak solution runs in O(n) time with O(1) extra space. The brute force checks each window's pairs and runs in O(n * k) time. With n at most 500, both pass, but the O(n) version is the one to give in an interview.

Why use a sliding window for Find the Power of K-Size Subarrays I?

Every window has the same length and overlaps the previous one, so the brute force repeats work. A sliding window carries state from one window to the next. Here that state is the length of the current run of +1 steps.

Can Find the Power of K-Size Subarrays I be solved in O(1) extra space?

Yes. The solution uses a few integer variables beyond the output list. The output list itself has n - k + 1 entries, and the problem requires it, so it cannot be avoided.

Do I need a deque or a heap for this problem?

No. Deques and heaps help when the maximum of a window is not its last element. Here a valid window is strictly ascending, so its maximum is its last element, and one counter is enough.

Why does my Python code write to the wrong slot?

A negative index in Python does not raise an error. When i is less than k - 1, the expression i - k + 1 is negative and writes from the end of the list. Check i >= k - 1 before writing.

Asked at

See which companies ask this — Pro

Practise it