#2744

Find Maximum Number of String Pairs

Easy
ArrayHash TableStringSimulationHash 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)

We can use a hash map to store the reversed strings and check for matches in a single pass, which is much more efficient than comparing every pair.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash map to store the reversed strings and their counts.
  2. 2Step 2: Iterate through the words and for each word, check if its reverse exists in the hash map.
  3. 3Step 3: If it exists, increment the pair count and remove both from the map to ensure they are not reused.
solution.py16 lines
1# Full working Python code
2words = ["cd", "ac", "dc", "ca", "zz"]
3
4def maxPairs(words):
5    count = 0
6    word_map = {}
7    for word in words:
8        rev = word[::-1]
9        if rev in word_map:
10            count += 1
11            del word_map[rev]
12        else:
13            word_map[word] = True
14    return count
15
16print(maxPairs(words))

Complexity note: The time complexity is O(n) because we only pass through the list of words once. The space complexity is O(n) due to the hash map storing the words.

  • 1Each string can only be paired once.
  • 2Reversing a string is a key operation in this problem.

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