Talentd
FleetCode

3804. Number of Centered Subarrays

Medium66.5% acceptance

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
  • -105 <= nums[i] <= 105

Hints open one at a time

Hint 1
Generate all subarrays and use a hashmap to check whether the sum exists in the generated subarrays.
11:30
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def centeredSubarrays(self, nums: List[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[-1,1,0]
Input
[2,-3]
Your code is saved on this device.Solution