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 withwords[j]ifwords[i]equals the reverse ofwords[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
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)!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code