Number of Centered Subarrays Problem
#3804
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3804.
You are given an integer array nums.
A subarray of nums is called centered if the sum of its elements is equal to at least one element within that same subarray.
Return the number of centered subarrays of nums.
Example 1:
Input: nums = [-1,1,0]
Output: 5
Explanation:
- All single-element subarrays ([-1], [1], [0]) are centered.
- The subarray [1, 0] has a sum of 1, which is present in the subarray.
- The subarray [-1, 1, 0] has a sum of 0, which is present in the subarray.
- Thus, the answer is 5.
Example 2:
Input: nums = [2,-3]
Output: 2
Explanation:
Only single-element subarrays ([2], [-3]) are centered.
Constraints:
1 <= nums.length <= 500-10^5 <= nums[i] <= 10^5
Solution
Approach: Hash Set + Enumeration
Enumerate every start index i. Then extend the end index j, keeping the running sum of the subarray and a set of its elements. After each extension, if the sum is in the set, the subarray is centered, so count it.
Complexity: Time O(n^2), space O(n), where n is the length of nums.
class Solution:
def centeredSubarrays(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
st = set()
s = 0
for j in range(i, n):
s += nums[j]
st.add(nums[j])
if s in st:
ans += 1
return ans