#3804

Number of Centered Subarrays

Medium
ArrayHash TableEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a hashmap to track the sums of subarrays and check if any sum matches an element in the subarray efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hashmap to store the frequency of sums and a variable to count centered subarrays.
  2. 2Step 2: Iterate through the array while maintaining a running sum and check if this sum exists in the hashmap.
  3. 3Step 3: For each element, check if the current sum matches any previous sums stored in the hashmap.
solution.py10 lines
1def count_centered_subarrays(nums):
2    count = 0
3    sum_map = {0: 1}
4    current_sum = 0
5    for num in nums:
6        current_sum += num
7        if current_sum in sum_map:
8            count += sum_map[current_sum]
9        sum_map[current_sum] = sum_map.get(current_sum, 0) + 1
10    return count

Complexity note: This complexity is due to a single pass through the array and the use of a hashmap for constant time lookups.

  • 1Single-element subarrays are always centered.
  • 2The sum of a subarray can be efficiently tracked using a hashmap.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.