#3707

Equal Score Substrings

Easy
StringPrefix SumHash MapArray
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)

We can use a prefix sum to calculate scores efficiently. By maintaining a running total, we can quickly determine if a split yields equal scores.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total score of the string.
  2. 2Step 2: Iterate through the string, maintaining a running score for the left substring.
  3. 3Step 3: At each index, check if twice the left score equals the total score minus the score of the character at the current index.
solution.py8 lines
1def equal_score_substrings(s):
2    total_score = sum(ord(c) - ord('a') + 1 for c in s)
3    left_score = 0
4    for i in range(len(s) - 1):
5        left_score += ord(s[i]) - ord('a') + 1
6        if 2 * left_score == total_score - (ord(s[i + 1]) - ord('a') + 1):
7            return True
8    return False

Complexity note: We calculate the total score in O(n) and use a single pass to check splits, leading to O(n) overall.

  • 1Prefix sums can optimize score calculations.
  • 2Equal score condition can be checked with simple arithmetic.

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