Print all valid words from given dictionary that are possible using Characters of given Array
Last Updated :
11 Feb, 2025
Given a dictionary of strings dict[] and a character array arr[]. The task is to print all valid words of the dictionary that are possible using characters from the given character array.
Examples:
Input: dict[] = ["go", "bat", "me", "eat", "goal", boy", "run"] , arr[] = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
Output: "go", "me", "goal"
Explanation: All characters of these three strings are present in the dictionary.
Input: dict[] = ["goa", "bait", "mess", "ate", "goal", "girl", "rain"], arr[]= ['s', 'o', 't', 'a', 'e', 'g', 'l', 'i', 'r']
Output: "goa", "ate", "goal", "girl"
Explanation: All characters of these four strings are present in the dictionary.
Approach:
The idea is to check if words from a given dictionary can be formed using the characters in a provided array arr[]. It uses a frequency map to count the occurrences of each character in arr[]. For each word in the dictionary, it compares the characters' counts from the word against the counts in the frequency map. If all characters in the word are available (with enough count), the word can be formed and is added to the result.
Follow the steps below to implement the above idea:
- Create a frequency map for the characters in
arr[]
. - Iterate over each word in the dictionary.
- For each word, check if it can be formed by comparing its character counts with the frequency map.
- If the word can be formed, add it to the result array.
- Print the valid words at the end.
C++
// C++ implementation to print all words
// that can be formed
#include <bits/stdc++.h>
using namespace std;
// Function to check if the word can be formed
bool canFormWord(string &word,
unordered_map<char, int> &freq) {
// Temporary map for checking characters
unordered_map<char, int> tempFreq = freq;
// Check each character in the word
for (char ch : word) {
// If character is missing or exhausted
if (tempFreq[ch] == 0) {
return false;
}
tempFreq[ch]--;
}
return true;
}
vector<string> findWords(vector<string> &dict,
vector<char> &arr) {
// Frequency map for the array characters
unordered_map<char, int> freq;
// Populate the frequency map
for (char ch : arr) {
freq[ch]++;
}
vector<string> validWords;
// Check each word in the dictionary
for (string &word : dict) {
// If word can be formed, add to result
if (canFormWord(word, freq)) {
validWords.push_back(word);
}
}
return validWords;
}
int main() {
// Input dictionary and character array
vector<string> dict = {"go", "bat", "me", "eat",
"goal", "boy", "run"};
vector<char> arr = {'e', 'o', 'b', 'a', 'm',
'g', 'l'};
// Get all valid words
vector<string> result = findWords(dict, arr);
// Print the valid words
for (string &word : result) {
cout << word << " ";
}
cout << endl;
return 0;
}
Java
// Java implementation to print all words
// that can be formed
import java.util.*;
class GfG {
// Function to check if the word can be formed
static boolean canFormWord(String word,
Map<Character, Integer> freq) {
// Temporary map for checking characters
Map<Character, Integer> tempFreq = new HashMap<>(freq);
// Check each character in the word
for (char ch : word.toCharArray()) {
// If character is missing or exhausted
if (!tempFreq.containsKey(ch) || tempFreq.get(ch) == 0) {
return false;
}
tempFreq.put(ch, tempFreq.get(ch) - 1);
}
return true;
}
static ArrayList<String> findWords(ArrayList<String> dict,
ArrayList<Character> arr) {
// Frequency map for the array characters
Map<Character, Integer> freq = new HashMap<>();
// Populate the frequency map
for (char ch : arr) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
ArrayList<String> validWords = new ArrayList<>();
// Check each word in the dictionary
for (String word : dict) {
// If word can be formed, add to result
if (canFormWord(word, freq)) {
validWords.add(word);
}
}
return validWords;
}
public static void main(String[] args) {
// Input dictionary and character array
ArrayList<String> dict = new ArrayList<>(
Arrays.asList("go", "bat", "me", "eat", "goal", "boy", "run"));
ArrayList<Character> arr = new ArrayList<>(
Arrays.asList('e', 'o', 'b', 'a', 'm', 'g', 'l'));
// Get all valid words
ArrayList<String> result = findWords(dict, arr);
// Print the valid words
for (String word : result) {
System.out.print(word + " ");
}
System.out.println();
}
}
Python
# Python implementation to print all words
# that can be formed
# Function to check if the word can be formed
def canFormWord(word, freq):
# Temporary map for checking characters
tempFreq = freq.copy()
# Check each character in the word
for ch in word:
# If character is missing or exhausted
if tempFreq.get(ch, 0) == 0:
return False
tempFreq[ch] -= 1
return True
def findWords(dict, arr):
# Frequency map for the array characters
freq = {}
# Populate the frequency map
for ch in arr:
freq[ch] = freq.get(ch, 0) + 1
validWords = []
# Check each word in the dictionary
for word in dict:
# If word can be formed, add to result
if canFormWord(word, freq):
validWords.append(word)
return validWords
if __name__ == "__main__":
# Input dictionary and character array
dict = ["go", "bat", "me", "eat", "goal", "boy", "run"]
arr = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
# Get all valid words
result = findWords(dict, arr)
# Print the valid words
for word in result:
print(word, end=" ")
print()
C#
// C# implementation to print all words
// that can be formed
using System;
using System.Collections.Generic;
class GfG {
// Function to check if the word can be formed
public static bool CanFormWord(string word,
Dictionary<char, int> freq) {
// Temporary map for checking characters
Dictionary<char, int> tempFreq
= new Dictionary<char, int>(freq);
// Check each character in the word
foreach (char ch in word) {
// If character is missing or exhausted
if (!tempFreq.ContainsKey(ch) || tempFreq[ch] == 0) {
return false;
}
tempFreq[ch]--;
}
return true;
}
public static List<string> FindWords(List<string> dict,
List<char> arr) {
// Frequency map for the array characters
Dictionary<char, int> freq
= new Dictionary<char, int>();
// Populate the frequency map
foreach (char ch in arr) {
if (freq.ContainsKey(ch)) {
freq[ch]++;
} else {
freq[ch] = 1;
}
}
List<string> validWords = new List<string>();
// Check each word in the dictionary
foreach (string word in dict) {
// If word can be formed, add to result
if (CanFormWord(word, freq)) {
validWords.Add(word);
}
}
return validWords;
}
public static void Main() {
// Input dictionary and character array
List<string> dict = new List<string> { "go", "bat", "me",
"eat", "goal",
"boy", "run" };
List<char> arr = new List<char> { 'e', 'o', 'b',
'a', 'm', 'g', 'l' };
// Get all valid words
List<string> result = FindWords(dict, arr);
// Print the valid words
foreach (string word in result) {
Console.Write(word + " ");
}
Console.WriteLine();
}
}
JavaScript
// Function to check if the word can be formed
function canFormWord(word, freq) {
// Temporary map for checking characters
let tempFreq = { ...freq };
// Check each character in the word
for (let ch of word) {
// If character is missing or exhausted
if ((tempFreq[ch] || 0) === 0) {
return false;
}
tempFreq[ch]--;
}
return true;
}
function findWords(dictionary, charArray) {
// Frequency map for the array characters
let freq = {};
// Populate the frequency map
for (let ch of charArray) {
freq[ch] = (freq[ch] || 0) + 1;
}
let validWords = [];
// Check each word in the dictionary
for (let word of dictionary) {
// If word can be formed, add to result
if (canFormWord(word, freq)) {
validWords.push(word);
}
}
return validWords;
}
// Driver Code
let dictionary = ["go", "bat", "me", "eat",
"goal", "boy", "run"];
let charArray = ['e', 'o', 'b', 'a',
'm', 'g', 'l'];
// Get all valid words
let result = findWords(dictionary, charArray);
// Print the valid words
for (let word of result) {
process.stdout.write(word + " ");
}
console.log();
Time Complexity: O(n * m), where n is the number of words in dict[], and m is the average length of each word.
Space Complexity: O(n), where n is the number of unique characters in the arr[].
Similar Reads
Print all valid words that are possible using Characters of Array Given a dictionary and a character array, print all valid words that are possible using characters from the array. Examples: Input : Dict - {"go","bat","me","eat","goal", "boy", "run"} arr[] = {'e','o','b', 'a','m','g', 'l'} Output : go, me, goal. Asked In : Microsoft Interview The idea is to use Tr
13 min read
Possible Words using given characters in Python 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 pr
5 min read
Maximize cost of forming a set of words using given set of characters Given an array arr[] consisting of N strings, an array letter[] consisting of M lowercase characters, and an array score[] such that score[i] is the cost of ith English alphabets, the task is to find the maximum cost of any valid set of words formed by using the given letters such that each letter c
15+ min read
Number of words that can be made using exactly P consonants and Q vowels from the given string Given a string str and two integers P and Q. The task is to find the total count of words that can be formed by choosing exactly P consonants and Q vowels from the given string.Examples: Input: str = "geek", P = 1, Q = 1 Output: 8 "ge", "ge", "eg", "ek", "eg", "ek", "ke" and "ke" are the possible wo
7 min read
Boggle (Find all possible words in a board of characters) | Set 1 You are given a list of strings, words[], and an n à m matrix of characters, letters[][]. The objective is to locate all the words from words[] that can be constructed by consecutively linking adjacent characters in the matrix. You are allowed to move in any of the 8 possible directions (horizontall
15+ min read