Open In App

Print all valid words from given dictionary that are possible using Characters of given Array

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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();

Output
go me goal 

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[].



Next Article
Article Tags :
Practice Tags :

Similar Reads