#3254
Find the Power of K-Size Subarrays I
MediumArraySliding WindowHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n)Space O(k)
The optimal solution uses a sliding window approach to efficiently check each subarray of size k. We maintain a set to track the elements and their count, ensuring they are unique and consecutive.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a sliding window of size k and a HashSet to track unique elements.
- 2Step 2: As you slide the window, add the new element and remove the old one, updating the HashSet.
- 3Step 3: Check if the maximum element minus the minimum element equals k-1 and if the size of the HashSet equals k. If true, store the maximum element; otherwise, store -1.
solution.py13 lines
1# Full working Python code
2results = []
3window = set()
4for i in range(len(nums)):
5 window.add(nums[i])
6 if i >= k:
7 window.remove(nums[i - k])
8 if i >= k - 1:
9 if max(window) - min(window) == k - 1 and len(window) == k:
10 results.append(max(window))
11 else:
12 results.append(-1)
13ℹ
Complexity note: The time complexity is O(n) because we only traverse the array once, and the operations on the HashSet (add, remove, max, min) are average O(1). The space complexity is O(k) due to the storage of elements in the HashSet.
- 1Using a sliding window allows for efficient checking of subarrays without redundant calculations.
- 2Maintaining a set helps track unique elements and their relationships easily.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.