Similar Problems

Similar Problems not available

Count Number Of Texts - Leetcode Solution

Companies:

LeetCode:  Count Number Of Texts Leetcode Solution

Difficulty: Medium

Topics: math hash-table dynamic-programming string  

Problem:

Given a list of strings words representing an English Dictionary, find the number of different ways that two words could be concatenated to form a palindrome.

Example:

Input: words = ["abcd","dcba","lls","s","sssll"] Output: 5 Explanation: The palindromes formed are "dcbaabcd", "abcddcba", "slls", "llssssll", "ssllss", some are repeated.

Solution:

To solve this problem, we need to find all pairs of words from the given list that could be concatenated to form a palindrome. For each pair of words, we need to check if the concatenation is a palindrome. We can do this efficiently by using a hash map to store the indices of all words in the list. For each word, we can check if its reverse exists in the hash map. If it does, and it is not the same as the current word, we can add the pair to the result.

One important thing to note is that we need to consider both the cases of concatenation. That is, we need to check if word1+word2 and word2+word1 are palindromes.

Let's see the Python implementation of the above approach.

Code:

class Solution: def palindromePairs(self, words: List[str]) -> List[List[int]]: res = [] d = {word: i for i, word in enumerate(words)} for i, word in enumerate(words): for j in range(len(word)+1): prefix, suffix = word[:j], word[j:] rev_prefix, rev_suffix = prefix[::-1], suffix[::-1] if rev_prefix in d and d[rev_prefix] != i and suffix == rev_suffix: res.append([i, d[rev_prefix]]) if j > 0 and rev_suffix in d and d[rev_suffix] != i and prefix == rev_prefix: res.append([d[rev_suffix], i]) return res

Time Complexity:

The above algorithm uses nested loops to iterate over all pairs of words and all possible prefixes and suffixes. Therefore, the time complexity of the algorithm is O(n^2*k), where n is the number of words and k is the average length of a word.

Space Complexity:

The algorithm uses a hash map to store the indices of words. Therefore, the space complexity of the algorithm is O(n*k).

Count Number Of Texts Solution Code

1