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 Number of String Pairs INPUT words array: "lc" i=0 "cl" i=1 "gg" i=2 Pair Condition: words[i] == reverse(words[j]) where i < j "lc" --> "cl" reverse("lc") = "cl" Input Values: ["lc", "cl", "gg"] ALGORITHM STEPS 1 Create HashMap Store each word in set Set: {"lc","cl","gg"} for lookup 2 For each word Compute its reverse 3 Check HashMap If reverse exists in set "lc" --> rev="cl" --> Found! "cl" --> (already paired) "gg" --> rev="gg" --> skip self 4 Count Pairs Mark used, increment count Time: O(n*k) Space: O(n) FINAL RESULT Valid Pairs Found: Pair 1: ("lc", "cl") "lc" reversed = "cl" Both exist in array "gg" --> no valid pair (can't pair with itself) Output: 1 OK - Maximum pairs = 1 Key Insight: Using a HashMap/Set allows O(1) lookup to check if the reverse of a string exists in the array. For each word, compute its reverse and check the set. Count pairs where i < j to avoid duplicates. TutorialsPoint - Find Maximum Number of String Pairs | Hash Map Optimization
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