Possible Words using given characters in Python
Last Updated :
10 Apr, 2023
Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples:
Input : Dict = ["go","bat","me","eat","goal","boy", "run"]
arr = ['e','o','b', 'a','m','g', 'l']
Output : go, me, goal.
This problem has existing solution please refer Print all valid words that are possible using Characters of Array link. We will this problem in python very quickly using Dictionary Data Structure. Approach is very simple :
- Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module.
- Check if all keys of any string lies within given set of characters that means this word is possible to create.
Python
# Function to print words which can be created
# using given set of characters
def charCount(word):
dict = {}
for i in word:
dict[i] = dict.get(i, 0) + 1
return dict
def possible_words(lwords, charSet):
for word in lwords:
flag = 1
chars = charCount(word)
for key in chars:
if key not in charSet:
flag = 0
else:
if charSet.count(key) != chars[key]:
flag = 0
if flag == 1:
print(word)
if __name__ == "__main__":
input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
possible_words(input, charSet)
Output:
go
me
goal
Time complexity: O(n^2)
Space complexity: O(n)
Recursive approach:
First, we define a function find_words(dictionary, characters, word='') that takes in three arguments:
- dictionary: a list of strings representing the valid words that can be formed from the given characters
- characters: a list of characters that can be used to form the words
- word: a string representing the current combination of characters being checked (initially empty)
The function has two cases:
- The base case: if word is in the dictionary, it means that we have found a valid word, so we print it.
- The recursive case: for each character in the characters list, we create a copy of the characters list called new_characters and remove the current character from it. We then call find_words again with the new_characters list and the current word appended with the current character. This will recursively check all possible combinations of characters to see if they form a word in the dictionary.
Finally, we have an example of how to use the find_words function, where we define the dictionary and characters lists and call find_words with those lists as arguments.
Python3
def find_words(dictionary, characters, word=''):
# base case: if the word is in the dictionary, print it
if word in dictionary:
print(word)
# recursive case: for each character in the characters list, make a new list of characters
# with that character removed, and call find_words with the new list of characters and the
# current word appended with the current character
for char in characters:
new_characters = characters.copy()
new_characters.remove(char)
find_words(dictionary, new_characters, word + char)
# example usage
dictionary = ["go","bat","me","eat","goal","boy", "run"]
characters = ['e','o','b', 'a','m','g', 'l']
find_words(dictionary, characters)
The time complexity of the recursive approach to solving this problem is dependent on the number of valid words that can be formed from the given characters and the length of those words.
In the worst case, the time complexity is O(n^m), where n is the number of characters in the characters list and m is the maximum length of the words in the dictionary. This is because the recursive function generates and checks all possible combinations of characters of length up to m, and there are n choices for each character in the combination.
For example, if the dictionary contains all words of length m that can be formed from the characters list, and the characters list has n elements, then the function will generate and check a total of n^m combinations.
On the other hand, if the dictionary is small and the words in the dictionary are short, the time complexity will be much lower. For example, if the dictionary contains only one word of length 1, the time complexity will be O(n).
It's worth noting that the time complexity of the recursive approach may not be as efficient as the approach provided in the original article, which only needs to check each word in the dictionary individually and does not generate and check all possible combinations of characters.
Approach#3: Using set and subsets
This approach takes a list of words (Dict) and a list of characters (arr) as input. It first creates a set of characters from the input list. Then, it iterates over each word in the dictionary, and checks if the set of characters in that word is a subset of the input set of characters. If it is, then the word is added to the result list. Finally, the function returns the list of words that can be formed using the input characters.
Algorithm
1. Convert the array into a set.
2. Initialize an empty list result to store the possible words.
3. Loop through each word in the given dictionary Dict.
4. Convert the word into a set.
If the set of the word is a subset of the given set arr, append the word to the result list.
5. Return the result list.
Python3
def possible_words(Dict, arr):
arr_set = set(arr)
result = []
for word in Dict:
if set(word).issubset(arr_set):
result.append(word)
return result
Dict = ["go", "bat", "me", "eat", "goal", "boy", "run"]
arr = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
print(possible_words(Dict, arr))
Output['go', 'me', 'goal']
Time Complexity: O(n*m), where n is the length of the dictionary Dict and m is the length of the longest word in the dictionary. In the worst case, we may have to check all the letters in the longest word in the dictionary against the letters in the given array arr.
Space Complexity: O(m), where m is the length of the longest word in the dictionary. We are using an extra set to store the letters of each word in the dictionary.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read