Problem Description
Given a 0-indexed array of distinct two-letter strings, determine the maximum number of pairs where one string is the reverse of the other. A pair is valid if for indices i < j, words[i] is equal to the reversed string of words[j]. Each string can be used at most once.
Key Insights
- Since every word has exactly two characters, reversing it is straightforward.
- Use a hash set (or dictionary) to record words that have not yet been paired.
- When processing a word, check if its reverse is already in the set.
- Once a pair is found, remove the reverse from the set to avoid reuse.
- Because the array contains distinct words, there is no risk of pairing the same string with itself unless it is palindromic; however, a palindromic string cannot be paired because it appears only once in the array.
Space and Time Complexity
Time Complexity: O(n), where n is the number of words. Space Complexity: O(n), for storing unpaired words in the set.
Solution
We iterate through the list of words and for each word, generate its reversed version. We maintain a set to track words that are waiting to be paired. If the reversed word is found in the set, it means a valid pair exists. We then remove the reversed word from the set and increase the count of pairs. If the reversed word isn’t found, we add the current word to the set to potentially be paired with a future word. This approach ensures each word is processed only once, achieving an optimal solution in linear time.