#3412

Find Mirror Score of a String

Medium
Hash TableStringStackSimulationHash 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)

Using a stack allows us to efficiently track the indices of characters that can potentially form a mirror pair. This reduces the need to repeatedly check all previous characters.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a score variable to 0 and a stack to keep track of indices.
  2. 2Step 2: For each character at index i, check if the stack is not empty and if the character at the top of the stack is the mirror of s[i].
  3. 3Step 3: If a match is found, pop the index from the stack, mark both indices, and add the difference (i - j) to the score. Otherwise, push the current index onto the stack.
solution.py11 lines
1# Full working Python code
2score = 0
3s = 'aczzx'
4stack = []
5for i in range(len(s)):
6    if stack and s[stack[-1]] == chr(219 - ord(s[i])):
7        j = stack.pop()
8        score += i - j
9    else:
10        stack.append(i)
11print(score)

Complexity note: The time complexity is O(n) because we process each character once. The space complexity is O(n) due to the stack that may store all indices in the worst case.

  • 1Using a stack helps in efficiently finding mirror pairs.
  • 2Understanding character encoding can simplify mirror calculations.

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