Similar Problems

Similar Problems not available

Count Pairs Of Similar Strings - Leetcode Solution

Companies:

LeetCode:  Count Pairs Of Similar Strings Leetcode Solution

Difficulty: Easy

Topics: string hash-table array  

Problem Statement:

Given a list of strings words, write a function to count the number of pairs (i, j) where i < j and words[i] and words[j] are similar. Similarity is defined as having the same length and the same set of characters, but not necessarily in the same order: for example, “stressed” and “desserts” are similar.

Example:

Input: words = ["tangram", "anagram", "pikachu", "back", "kabab"] Output: 2 Explanation: There are 2 pairs of words that are similar:

  • (words[0], words[1]) = ("tangram", "anagram")
  • (words[3], words[4]) = ("back", "kabab")

Solution:

We are given a list of strings, and we need to count all the pairs of similar strings.

To solve this problem, we can use a hash table to store the set of characters in each string. Then, we can loop through all the pairs of strings and check if their sets of characters are the same.

Here’s the detailed approach to solve the problem:

  1. Create a hash table where the key is the sorted set of characters in each string and the value is the number of occurrences of that set.

  2. Loop through all the pairs of strings and check if their sets of characters are equal and not empty.

  3. If the sets of characters are equal, add the count of occurrences of the set to the answer.

  4. Return the final answer.

Here’s the Python implementation of the above approach:

def count_pairs_of_similar_strings(words):

freq = {}
for word in words:
    key = tuple(sorted(set(word)))
    freq[key] = freq.get(key, 0) + 1
    
ans = 0
for i in range(len(words)):
    for j in range(i + 1, len(words)):
        key1 = tuple(sorted(set(words[i])))
        key2 = tuple(sorted(set(words[j])))
        if key1 == key2 and key1:
            ans += freq[key1]
            
return ans

Testing the solution on the given example

print(count_pairs_of_similar_strings(["tangram", "anagram", "pikachu", "back", "kabab"]))

Output: 2

Time Complexity: The time complexity of the solution is O(n^2 * m log m), where n is the length of the list and m is the maximum length of a string in the list. This is because we are using nested loops to loop through all pairs of strings, and then we are sorting the set of characters in each string, which takes O(m log m) time.

Space Complexity: The space complexity of the solution is O(n * m) because we are storing the set of characters for each string in a hash table with a maximum size of n and a maximum length of m.

Count Pairs Of Similar Strings Solution Code

1