Problem 2744

Abstract / Summary

Find the largest number of pairs of strings that can be formed where each pair has identical strings.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
9 lines | 301 bytes | submitted December 11, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.78 | σ = 0.96

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
20 links | 9 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

13 solutions   December 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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