#3833

Count Dominant Indices

Easy
ArrayEnumerationArrayPrefix Sum
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Use a running sum to calculate the average efficiently without nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter and a running sum of elements to the right.
  2. 2Step 2: Traverse the array from right to left, updating the sum and checking dominance.
  3. 3Step 3: For each index, calculate the average using the running sum and the count of elements.
solution.py13 lines
1def countDominantIndices(nums):
2    count = 0
3    total_sum = 0
4    n = len(nums)
5    for i in range(n-1, 0, -1):
6        total_sum += nums[i]
7    right_count = n - 1
8    for i in range(n-1):
9        if nums[i] > total_sum / right_count:
10            count += 1
11        total_sum -= nums[i+1]
12        right_count -= 1
13    return count

Complexity note: Single pass to calculate the total sum and another pass to check dominance leads to linear time complexity.

  • 1Dominance requires comparing with averages of subsequent elements.
  • 2Using a running sum can optimize average calculations.

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