#3392
Count Subarrays of Length Three With a Condition
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach is still straightforward but leverages the fact that we can check the condition in a single pass through the array, reducing the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Loop through the array from index 1 to nums.length - 2 (to ensure we can access nums[i - 1] and nums[i + 1]).
- 3Step 3: For each index i, check if nums[i - 1] + nums[i + 1] equals 0.5 * nums[i].
- 4Step 4: If the condition is met, increment the counter.
- 5Step 5: Return the counter after checking all relevant indices.
solution.py6 lines
1def countSubarrays(nums):
2 count = 0
3 for i in range(1, len(nums) - 1):
4 if nums[i - 1] + nums[i + 1] == 0.5 * nums[i]:
5 count += 1
6 return countℹ
Complexity note: The time complexity is O(n) because we only loop through the array once. The space complexity is O(1) since we are using a constant amount of extra space.
- 1The condition can be simplified to a single check for each valid middle element.
- 2Understanding the structure of the problem helps in optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.