Find Maximum Number of String Pairs — LeetCode 2744 Python Solution
- Problem
- #2744
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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].
Example
- Input
- words = ["cd","ac","dc","ca","zz"]
- Output
- 2
- Explanation
- In this example, we can form 2 pair of strings in the following way:
Python solution
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
cnt = Counter()
ans = 0
for w in words:
ans += cnt[w[::-1]]
cnt[w] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2744. Find Maximum Number of String Pairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2744. Find Maximum Number of String Pairs?
- LeetCode 2744. Find Maximum Number of String Pairs is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2744. Find Maximum Number of String Pairs?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2744. Find Maximum Number of String Pairs?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2744. Find Maximum Number of String Pairs cover?
- LeetCode 2744. Find Maximum Number of String Pairs is tagged Array, Hash Table, String and Simulation on LeetCode.