HardNo. 2302
Count Subarrays With Score Less Than K — LeetCode 2302 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Binary Search, Prefix Sum, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
The score of an array is defined as the product of its sum and its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
Example
- Input
- nums = [2,1,4,3,5], k = 10
- Output
- 6
- Explanation
- The 6 subarrays having scores less than 10 are:
Python solution
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
s = list(accumulate(nums, initial=0))
ans = 0
for i in range(1, len(s)):
l, r = 0, i
while l < r:
mid = (l + r + 1) >> 1
if (s[i] - s[i - mid]) * mid < k:
l = mid
else:
r = mid - 1
ans += l
return ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)where n is the length of the array nums
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2302. Count Subarrays With Score Less Than K is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0209 | Minimum Size Subarray Sum | Medium |
| 0713 | Subarray Product Less Than K | Medium |
| 0862 | Shortest Subarray with Sum at Least K | Hard |
| 1004 | Max Consecutive Ones III | Medium |
| 2106 | Maximum Fruits Harvested After at Most K Steps | Hard |
| 2398 | Maximum Number of Robots Within Budget | Hard |
Frequently asked questions
- How hard is LeetCode 2302. Count Subarrays With Score Less Than K?
LeetCode 2302. Count Subarrays With Score Less Than K is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2302. Count Subarrays With Score Less Than K?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2302. Count Subarrays With Score Less Than K?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 2302. Count Subarrays With Score Less Than K cover?
LeetCode 2302. Count Subarrays With Score Less Than K is tagged Array, Binary Search, Prefix Sum and Sliding Window on LeetCode.