Python 2744.py
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
words = set(words) # faster lookup
result = 0
for w in words:
other = w[::-1]
if other > w and other in words:
result += 1
return result
Difficulty
and has an acceptance rate of about 83% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Simulation
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method maximumNumberOfStringPairs. The method receives a list of strings and returns the count of distinct pairs where one string is the reverse of the other. The algorithm first converts the input list into a set to enable constant-time membership checks, then iterates over each unique word, computes its reversed form, and increments a counter when a qualifying reverse exists that is lexicographically greater than the original word. The final count is returned.
Key Steps
The first important operation is the conversion of the input list to a set:
words = set(words) # faster lookup
By eliminating duplicates and providing O(1) average-case lookup, this step prepares the data for efficient pair detection.
Next, the method initializes a result accumulator:
result = 0
The core loop iterates over each word in the deduplicated collection:
for w in words:
other = w[::-1]
if other > w and other in words:
result += 1
Inside the loop, the reversed string other is produced using Python’s slice syntax w[::-1]. The conditional other > w ensures that each unordered pair is counted only once, preventing double counting when both w and its reverse appear in the set. The membership test other in words confirms the existence of the reverse counterpart. When both conditions hold, the accumulator is incremented.
Finally, the method returns the accumulated count:
return result
Edge Cases
The algorithm gracefully handles several edge conditions without additional code. When the input list contains duplicate strings, converting to a set removes the duplicates, guaranteeing that each word is examined only once. If a word is a palindrome (identical to its reverse), the condition other > w evaluates to false because the strings are equal, so such words are never counted as a pair, which aligns with the definition of distinct reverse pairs. An empty input list results in an empty set, the loop body never executes, and the method correctly returns zero. Likewise, a list containing a single word yields a set of size one; the loop runs once, but the reverse either does not exist or fails the lexicographic comparison, leading to a zero result.
Performance Optimizations
The primary optimization is the use of a set for words. This data structure provides average-case constant-time membership checks, turning what would be an O(n²) scan with a list into an O(n) traversal over unique elements. The lexicographic guard other > w eliminates the need for an auxiliary structure to track already counted pairs, thereby avoiding extra memory overhead. The slice operation w[::-1] creates the reversed string in linear time relative to the length of w, but because each word is processed only once, the total work remains proportional to the sum of the lengths of all distinct words. The algorithm’s design ensures that each word contributes at most one increment to the result, preventing redundant work and keeping the runtime tightly bound to the size of the input.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of blocks with letters written on them. Some of the blocks are special because they are the reverse of another block. For example, if one block says top, another block might say pot.
Think of this code as a helper who walks through the bucket to find all these matching pairs. First, the helper puts all the blocks into a neat pile where no two blocks look the same to make them easier to check. Then, the helper picks up each block one by one and turns it around in their head to see what it would look like backward.
The helper then checks the other blocks in the pile to see if the backward version is hiding there. If a match is found, the helper makes a little tick mark on a piece of paper to keep count. By doing this for every block, the helper eventually finds out exactly how many pairs are hiding in the bucket.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | Java | Python | C++ | TS | |||
| WalkCCC | Java | Python | C++ | |||||
| leetcode.ca | Java | Python | C++ | Go | TS | |||
| Progiez | Java | Python | C++ | |||||
| github | chandansgowda | Python | ||||||
| charles-wangkai | Java | |||||||
| fsq | Rust | |||||||
| JoshCrozier | JS | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| chandansgowda | Python | |||||||
| charles-wangkai | Java | |||||||
| fsq | Rust | |||||||
| JoshCrozier | JavaScript | |||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 336: Palindrome Pairs
Solved On The Same Day
- problem 1287: Element Appearing More Than 25% In Sorted Array
- problem 2363: Merge Similar Items
- problem 2418: Sort the People
- problem 2441: Largest Positive Integer That Exists With Its Negative
- problem 2506: Count Pairs Of Similar Strings
- problem 2716: Minimize String Length
- problem 2374: Node With Highest Edge Score
- problem 2442: Count Number of Distinct Integers After Reverse Operations
- problem 2491: Divide Players Into Teams of Equal Skill
- problem 2554: Maximum Number of Integers to Choose From a Range I
- problem 2780: Minimum Index of a Valid Split
- problem 2933: High-Access Employees
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality