Find Maximum Number of String Pairs - Problem

You are given a 0-indexed array words consisting of distinct strings.

The string words[i] can be paired with the string words[j] if:

  • The string words[i] is equal to the reversed string of words[j].
  • 0 <= i < j < words.length.

Return the maximum number of pairs that can be formed from the array words.

Note that each string can belong in at most one pair.

Input & Output

Example 1 — Basic Case
$ Input: words = ["lc","cl","gg"]
Output: 1
💡 Note: The string "lc" can be paired with "cl" since "lc" equals the reverse of "cl". We have 1 pair.
Example 2 — Multiple Pairs
$ Input: words = ["ab","ba","cc"]
Output: 1
💡 Note: "ab" can pair with "ba" (reverse match). "cc" is its own reverse but needs another "cc" to pair, so it remains unpaired. Total: 1 pair.
Example 3 — No Pairs
$ Input: words = ["aa","ab"]
Output: 0
💡 Note: "aa" is palindrome but needs another "aa" to pair. "ab" would need "ba" but it doesn't exist. No pairs possible.

Constraints

  • 1 ≤ words.length ≤ 50
  • words[i].length == 2
  • words consists of distinct strings
  • words[i] contains only lowercase English letters

Visualization

Tap to expand
Find Maximum String PairsInput ArraylcclggPair!No pairlc reverses to cl → Valid pairgg reverses to gg → Needs another ggOutput: 1
Understanding the Visualization
1
Input
Array of distinct strings: ["lc","cl","gg"]
2
Find Pairs
Match strings with their reverses: lc ↔ cl
3
Count
Return maximum pairs possible: 1
Key Takeaway
🎯 Key Insight: Each string pairs only with its exact reverse - use hash map for efficient reverse lookups
Asked in
Amazon 15 Google 12
12.5K Views
Medium Frequency
~15 min Avg. Time
324 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