Find Maximum Number of String Pairs - Problem

You're given an array of distinct strings and need to find the maximum number of pairs you can form where each pair consists of a string and its reverse.

Rules for forming pairs:

  • A string words[i] can be paired with words[j] if words[i] equals the reverse of words[j]
  • Only consider pairs where i < j (avoid counting the same pair twice)
  • Each string can belong to at most one pair

Goal: Return the maximum number of valid pairs you can form.

Example: Given ["abc", "cba", "def", "fed"], you can form 2 pairs: ("abc", "cba") and ("def", "fed").

Input & Output

example_1.py โ€” Basic Case
$ Input: ["lc", "cl", "gg"]
โ€บ Output: 1
๐Ÿ’ก Note: Only one pair can be formed: ("lc", "cl") since "lc" is the reverse of "cl". The string "gg" cannot form a pair with any other string.
example_2.py โ€” Multiple Pairs
$ Input: ["ab", "ba", "cc"]
โ€บ Output: 1
๐Ÿ’ก Note: We can form one pair: ("ab", "ba"). The string "cc" is its own reverse, but since all strings are distinct, it cannot form a pair with itself.
example_3.py โ€” No Pairs
$ Input: ["aa", "bb"]
โ€บ Output: 0
๐Ÿ’ก Note: No pairs can be formed since "aa" reversed is "aa" and "bb" reversed is "bb", but all strings in the input are distinct, so no valid pairs exist.

Constraints

  • 1 โ‰ค words.length โ‰ค 50
  • 1 โ‰ค words[i].length โ‰ค 300
  • words[i] consists of only lowercase English letters
  • All strings are distinct

Visualization

Tap to expand
๐Ÿ•บ The Dance Partner Matching Problem ๐Ÿ’ƒDancer AabcForward movesDancer BcbaReverse movesPerfect Match!Dancer CdefForward movesDancer DfedReverse movesAnother Match!Algorithm Insight1. Keep track of seen dancers2. For each new dancer, check iftheir reverse is already seen3. If yes: pair them up! โœจResult: 2 Perfect Dance Pairs! ๐ŸŽ‰
Understanding the Visualization
1
Setup the Dance Floor
We have dancers with move sequences: 'abc', 'cba', 'def', 'fed'
2
Find Compatible Partners
Check if each dancer's reverse sequence matches any other dancer
3
Form Dance Pairs
'abc' pairs with 'cba', and 'def' pairs with 'fed'
4
Count Successful Pairs
We successfully formed 2 dancing pairs from our group!
Key Takeaway
๐ŸŽฏ Key Insight: Instead of comparing every dancer with every other dancer (O(nยฒ)), we can use a 'memory book' to instantly recall if we've seen the perfect reverse partner before - making it O(n)!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
12.4K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen