#3255
Find the Power of K-Size Subarrays II
MediumArraySliding WindowSliding WindowHash Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a sliding window approach allows us to efficiently track the maximum element and check for consecutive elements without needing to sort each subarray. We can maintain a frequency map to ensure the elements are consecutive.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a frequency map to count occurrences of elements in the current window of size k.
- 2Step 2: Slide the window across the array, updating the frequency map as elements enter and exit the window.
- 3Step 3: Check if the window contains k unique elements and if the maximum element minus the minimum element equals k - 1. If true, return the maximum element; otherwise, return -1.
solution.py19 lines
1from collections import defaultdict
2
3def findPower(nums, k):
4 results = []
5 freq = defaultdict(int)
6 left = 0
7 for right in range(len(nums)):
8 freq[nums[right]] += 1
9 if right - left + 1 > k:
10 freq[nums[left]] -= 1
11 if freq[nums[left]] == 0:
12 del freq[nums[left]]
13 left += 1
14 if right - left + 1 == k:
15 if len(freq) == k and max(freq.keys()) - min(freq.keys()) == k - 1:
16 results.append(max(freq.keys()))
17 else:
18 results.append(-1)
19 return resultsℹ
Complexity note: The time complexity is O(n) because we process each element of the array once while maintaining a sliding window. The space complexity is O(n) due to the frequency map that can store up to n unique elements in the worst case.
- 1Using a sliding window can significantly reduce the time complexity compared to checking each subarray individually.
- 2Maintaining a frequency map allows for efficient checks on the uniqueness and consecutive nature of elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.