Skip to main content

Number of Centered Subarrays - Solution & Explanation

Practice this problem

Problem Statement

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

Approach Overview

Problem Overview: You are given an integer array and need to count how many subarrays are centered. A subarray is centered if there exists an index inside it that acts as the center and the elements around it balance in a way that keeps the center as the median of the subarray.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

Enumerate every possible subarray using two nested loops. For each subarray, test every index as a potential center and verify whether it remains the median of the elements inside that subarray. This requires scanning the subarray and counting elements smaller and larger than the candidate center. The approach is straightforward but expensive: generating all subarrays costs O(n^2) and validating the center takes O(n). It works only for very small inputs and mainly helps you reason about the centered property before optimizing.

Approach 2: Hash Table + Enumeration (O(n^2) time, O(n) space)

Fix each index i as the center and expand outward. Track the balance between numbers greater than nums[i] and numbers smaller than it. Define a running balance such as +1 for greater elements and -1 for smaller ones. When the balance of the left and right sides cancel out, the center behaves like the median of that subarray.

A hash table stores frequencies of balance values observed on one side while expanding. As you enumerate elements on the other side, look up complementary balances that form a valid centered configuration. This converts repeated scans into constant‑time lookups. The outer loop enumerates every possible center (O(n)), while expansions and hash lookups take another O(n), giving O(n^2) time overall and O(n) extra space.

This strategy combines array traversal with hash table frequency counting to avoid recomputing comparisons for every candidate subarray. Instead of validating each subarray independently, you reuse balance information around the center.

Recommended for interviews: The hash table + enumeration method is the expected solution. Interviewers want to see that you first reason about the brute force definition of a centered subarray, then convert repeated checks into prefix balance counts with constant‑time hash lookups. That shift from repeated scanning to balance tracking demonstrates strong problem‑solving and familiarity with enumeration patterns.

Solution

We enumerate all starting indices i of subarrays, then starting from index i, we enumerate the ending index j of the subarray, calculate the sum s of elements in the subarray nums[i ldots j], and add all elements in the subarray to the hash table st. After each enumeration, we check if s appears in the hash table st. If it does, it means the subarray nums[i ldots j] is a centered subarray, and we increment the answer by 1.

The time complexity is O(n^2) and the space complexity is O(n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(n^3)O(1)Understanding the centered condition or validating small inputs
Hash Table + EnumerationO(n^2)O(n)General case. Uses balance counting and hash lookups for efficient centered subarray counting

Video Solution

3804. Number of Centered Subarrays | Weekly Contest 484 | Leetcode • Rapid Syntax • 262 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Number of Centered Subarrays easy or hard?
Number of Centered Subarrays is generally rated Medium difficulty. The main challenge is recognizing that brute force enumeration is too slow and that the centered condition can be represented using a balance value and hash map lookups.
Number of Centered Subarrays Python/Java solution
The solution is typically implemented by iterating over each index as a center, maintaining a running balance for elements greater or smaller than that center, and storing balance frequencies in a hash map. The same algorithm translates directly across Python, Java, C++, Go, and TypeScript with identical O(n^2) time complexity.
How to solve Number of Centered Subarrays in O(n)?
Most implementations solve it in O(n^2) by enumerating each possible center and using a hash table to match balance values. Achieving O(n) for the fully general version is difficult because every element can potentially serve as a center. The hash-based enumeration method is typically considered optimal for this formulation.
What is the best approach for Number of Centered Subarrays?
The most practical approach uses hash table + enumeration. Fix each index as the potential center and track the balance between elements greater and smaller than the center while expanding the subarray. A hash map stores previously seen balances so complementary states can be matched quickly. This reduces repeated scanning and runs in O(n^2) time with O(n) space.
Is Number of Centered Subarrays asked at Google/Amazon/Meta?
Problems involving median-based subarrays and balance counting appear frequently in interviews at companies like Google, Amazon, and Meta. Variants often require counting subarrays where a particular element behaves like a median, which uses the same hash map and balance-difference technique.
What data structure is used in Number of Centered Subarrays?
The key data structure is a hash table (hash map). It stores frequency counts of balance values representing how many elements are greater or smaller than the chosen center. This allows constant-time lookups to determine whether a valid centered configuration exists.
What is the time complexity of Number of Centered Subarrays?
The optimized solution runs in O(n^2) time and O(n) space. Each index is treated as a center and the algorithm expands around it while updating a balance value. Hash table lookups allow constant-time matching of valid configurations, avoiding the O(n^3) brute force check.

Ready to solve this problem?

Practice Number of Centered Subarrays with our built-in code editor and test cases.

Practice on FleetCode