Number of Centered Subarrays

You are given an integer array nums.

A subarray of nums is considered centered if the sum of all its elements is equal to at least one element present within that exact same subarray.

Return the total number of centered subarrays in nums.

Example 1:

Input: nums = [1, -1, 2]

Output: 4

Explanation:

Single elements [1], [-1], and [2] are naturally centered (sum equals the element itself).

The subarray [1, -1, 2] has a sum of 2, which is present in the subarray.

Total valid subarrays = 4.

Example 2:

Input: nums = [0, 0]

Output: 3

Explanation:

[0] (index 0) is centered. [0] (index 1) is centered.

[0, 0] has a sum of 0, which is present in the subarray. Total valid subarrays = 3.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [3, -3, 3]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 500
  • -105 <= nums[i] <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int centeredSubarrays(vector<int>& nums) {
// Write your code here
}
};
Test Case

Input:

Nums