Magicsheet logo

Find the Power of K-Size Subarrays I

Medium
25%
Updated 8/1/2025

Asked by 3 Companies

Find the Power of K-Size Subarrays I

1. What is this problem about?

The Find the Power of K-Size Subarrays I interview question involves evaluating specific segments of an array. The "power" of a subarray of size kk is defined as its maximum element IF the elements are consecutive and sorted in ascending order. If the subarray is not consecutive or not sorted, its power is -1. Your task is to return an array of power values for all contiguous subarrays of length kk.

2. Why is this asked in interviews?

Companies like Meta and Bloomberg ask the Find the Power of K-Size Subarrays I coding problem to test a candidate's proficiency with Sliding Window interview patterns. It evaluates whether you can maintain a property (consecutiveness) efficiently as the window moves across the array, rather than re-checking the entire window from scratch at every step.

3. Algorithmic pattern used

This problem is solved using the Sliding Window pattern with a Counter.

  • Consecutive Check: Maintain a counter of "how many adjacent elements are consecutive so far."
  • Logic: Two elements nums[i-1] and nums[i] are consecutive if nums[i] == nums[i-1] + 1.
  • Window Property: A window of size kk is valid if it contains k1k-1 consecutive pairs.
  • Linear Scan: Traverse the array. Every time you find a consecutive pair, increment the counter. If not, reset it. If the counter is k1\geq k-1, the current window ending at ii is valid, and its power is nums[i].

4. Example explanation

Array: [1, 2, 3, 5, 6], k=3k = 3.

  • index 0-2: [1, 2, 3]. Sorted and consecutive. Power = 3.
  • index 1-3: [2, 3, 5]. 3 and 5 are not consecutive. Power = -1.
  • index 2-4: [3, 5, 6]. 3 and 5 are not consecutive. Power = -1. Result: [3, -1, -1].

5. Common mistakes candidates make

  • O(NK)O(N \cdot K) Brute Force: Checking every window of size kk independently. While okay for small kk, it's not optimal.
  • Incorrect "Consecutive" definition: Missing the requirement that the values must increase exactly by 1.
  • Off-by-one: Mistakes in resetting the consecutive counter when a gap is found.

6. Interview preparation tip

Practice using "Running Count" optimizations. Many sliding window problems that look for a specific sequence property can be solved by tracking the number of valid "links" or "pairs" currently inside the window. This is a core Array interview pattern.

Similar Questions