Connect with us

LeetCode

LeetCode 2942: Find Words Containing Character Solution in Python

This Python solution iterates over a list of strings, using list comprehension and the enumerate function to identify indices of words containing a specified character.

Published

on

The LeetCode 2942 problem Find Words Containing Character is an easy coding question that can be solved in Python with a single line of code. Before we dive into to Python solution for this LeetCode problem, let us understand the task at hand.

Given a 0-indexed array words of strings and a character x, the task is to return an array of indices. These indices correspond to the positions of the words within words that include the character x. The order of indices in the returned array is not specified.

class Solution:
    def findWordsContaining(self, words: List[str], x: str) -> List[int]:
      return [i for i, word in enumerate(words) if x in word]

My Python solution for this LeetCode problem defines a class Solution with a method findWordsContaining. The method takes two parameters: words, a list of strings, and x, a single character string. It employs a list comprehension to iterate over words while simultaneously keeping track of each word’s index i using the enumerate function.

The condition if x in word filters the words, including only those that contain the character x. For each word meeting this criterion, its index i is included in the output list. The method returns this list of indices, which represent the positions of words in the original list that contain the specified character x.

Find Words Containing Character code submission.
Successful submission of my Python solution to Find Words Containing Character on LeetCode.

Complexity Analysis

Time Complexity

The time complexity of the provided Python solution code is O(nm), where n represents the total number of words in the input list and m signifies the average length of these words. This is because of the iteration over each word in the list to check if it contains the specified character, which is an operation that depends on the length of the individual words.

Space Complexity

Regarding space complexity, the solution has an O(n) complexity, primarily influenced by the size of the output list, which holds the indices of words containing the given character. In the worst-case scenario, where every word includes the character, the output list’s size directly correlates with the input list’s size.

Trending