The Wayback Machine - https://web.archive.org/web/20241001034501/https://www.geeksforgeeks.org/boggle-find-possible-words-board-characters/
Open In App

Boggle (Find all possible words in a board of characters) | Set 1

Last Updated : 15 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same cell.

Example: 

Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};
boggle[][] = {{'G', 'I', 'Z'},
{'U', 'E', 'K'},
{'Q', 'S', 'E'}};
isWord(str): returns true if str is present in dictionary
else false.

Output: Following words of dictionary are present
GEEKS
QUIZ

Boggle

We strongly recommend that you click here and practice it, before moving on to the solution.

The idea is to consider every character as a starting character and find all words starting with it. All words starting from a character can be found using Depth First Traversal. We do depth-first traversal starting from every cell. We keep track of visited cells to make sure that a cell is considered only once in a word.

C++
// C++ program for Boggle game
#include <cstring>
#include <iostream>
using namespace std;

#define M 3
#define N 3

// Let the given dictionary be following
string dictionary[] = { "GEEKS", "FOR", "QUIZ", "GO" };
int n = sizeof(dictionary) / sizeof(dictionary[0]);

// A given function to check if a given string is present in
// dictionary. The implementation is naive for simplicity. As
// per the question dictionary is given to us.
bool isWord(string& str)
{
    // Linearly search all words
    for (int i = 0; i < n; i++)
        if (str.compare(dictionary[i]) == 0)
            return true;
    return false;
}

// A recursive function to print all words present on boggle
void findWordsUtil(char boggle[M][N], bool visited[M][N], int i,
                   int j, string& str)
{
    // Mark current cell as visited and append current character
    // to str
    visited[i][j] = true;
    str = str + boggle[i][j];

    // If str is present in dictionary, then print it
    if (isWord(str))
        cout << str << endl;

    // Traverse 8 adjacent cells of boggle[i][j]
    for (int row = i - 1; row <= i + 1 && row < M; row++)
        for (int col = j - 1; col <= j + 1 && col < N; col++)
            if (row >= 0 && col >= 0 && !visited[row][col])
                findWordsUtil(boggle, visited, row, col, str);

    // Erase current character from string and mark visited
    // of current cell as false
    str.erase(str.length() - 1);
    visited[i][j] = false;
}

// Prints all words present in dictionary.
void findWords(char boggle[M][N])
{
    // Mark all characters as not visited
    bool visited[M][N] = { { false } };

    // Initialize current string
    string str = "";

    // Consider every character and look for all words
    // starting with this character
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            findWordsUtil(boggle, visited, i, j, str);
}

// Driver program to test above function
int main()
{
    char boggle[M][N] = { { 'G', 'I', 'Z' },
                          { 'U', 'E', 'K' },
                          { 'Q', 'S', 'E' } };

    cout << "Following words of dictionary are present\n";
    findWords(boggle);
    return 0;
}
Java
// Java program for Boggle game
class GFG {
    // Let the given dictionary be following
    static final String dictionary[] = { "GEEKS", "FOR", "QUIZ", "GUQ", "EE" };
    static final int n = dictionary.length;
    static final int M = 3, N = 3;

    // A given function to check if a given string is present in
    // dictionary. The implementation is naive for simplicity. As
    // per the question dictionary is given to us.
    static boolean isWord(String str)
    {
        // Linearly search all words
        for (int i = 0; i < n; i++)
            if (str.equals(dictionary[i]))
                return true;
        return false;
    }

    // A recursive function to print all words present on boggle
    static void findWordsUtil(char boggle[][], boolean visited[][], int i,
                              int j, String str)
    {
        // Mark current cell as visited and append current character
        // to str
        visited[i][j] = true;
        str = str + boggle[i][j];

        // If str is present in dictionary, then print it
        if (isWord(str))
            System.out.println(str);

        // Traverse 8 adjacent cells of boggle[i][j]
        for (int row = i - 1; row <= i + 1 && row < M; row++)
            for (int col = j - 1; col <= j + 1 && col < N; col++)
                if (row >= 0 && col >= 0 && !visited[row][col])
                    findWordsUtil(boggle, visited, row, col, str);

        // Erase current character from string and mark visited
        // of current cell as false
        str = "" + str.charAt(str.length() - 1);
        visited[i][j] = false;
    }

    // Prints all words present in dictionary.
    static void findWords(char boggle[][])
    {
        // Mark all characters as not visited
        boolean visited[][] = new boolean[M][N];

        // Initialize current string
        String str = "";

        // Consider every character and look for all words
        // starting with this character
        for (int i = 0; i < M; i++)
            for (int j = 0; j < N; j++)
                findWordsUtil(boggle, visited, i, j, str);
    }

    // Driver program to test above function
    public static void main(String args[])
    {
        char boggle[][] = { { 'G', 'I', 'Z' },
                            { 'U', 'E', 'K' },
                            { 'Q', 'S', 'E' } };

        System.out.println("Following words of dictionary are present");
        findWords(boggle);
    }
}
Python3
# Python3 program for Boggle game
# Let the given dictionary be following

dictionary = ["GEEKS", "FOR", "QUIZ", "GO"]
n = len(dictionary)
M = 3
N = 3

# A given function to check if a given string
# is present in dictionary. The implementation is
# naive for simplicity. As per the question
# dictionary is given to us.
def isWord(Str):
  
    # Linearly search all words
    for i in range(n):
        if (Str == dictionary[i]):
            return True
    return False

# A recursive function to print all words present on boggle
def findWordsUtil(boggle, visited, i, j, Str):
    # Mark current cell as visited and
    # append current character to str
    visited[i][j] = True
    Str = Str + boggle[i][j]
    
    # If str is present in dictionary,
    # then print it
    if (isWord(Str)):
        print(Str)
    
    # Traverse 8 adjacent cells of boggle[i,j]
    row = i - 1
    while row <= i + 1 and row < M:
        col = j - 1
        while col <= j + 1 and col < N:
            if (row >= 0 and col >= 0 and not visited[row][col]):
                findWordsUtil(boggle, visited, row, col, Str)
            col+=1
        row+=1
    
    # Erase current character from string and
    # mark visited of current cell as false
    Str = "" + Str[-1]
    visited[i][j] = False

# Prints all words present in dictionary.
def findWords(boggle):
  
    # Mark all characters as not visited
    visited = [[False for i in range(N)] for j in range(M)]
    
    # Initialize current string
    Str = ""
    
    # Consider every character and look for all words
    # starting with this character
    for i in range(M):
      for j in range(N):
        findWordsUtil(boggle, visited, i, j, Str)

# Driver Code
boggle = [["G", "I", "Z"], ["U", "E", "K"], ["Q", "S", "E"]]

print("Following words of", "dictionary are present")
findWords(boggle)

#  This code is contributed by divyesh072019.
C#
// C# program for Boggle game
using System;
using System.Collections.Generic;

class GFG 
{
    // Let the given dictionary be following
    static readonly String []dictionary = { "GEEKS", "FOR", 
                                            "QUIZ", "GUQ", "EE" };
    static readonly int n = dictionary.Length;
    static readonly int M = 3, N = 3;

    // A given function to check if a given string 
    // is present in dictionary. The implementation is 
    // naive for simplicity. As per the question 
    // dictionary is given to us.
    static bool isWord(String str)
    {
        // Linearly search all words
        for (int i = 0; i < n; i++)
            if (str.Equals(dictionary[i]))
                return true;
        return false;
    }

    // A recursive function to print all words present on boggle
    static void findWordsUtil(char [,]boggle, bool [,]visited, 
                              int i, int j, String str)
    {
        // Mark current cell as visited and
        // append current character to str
        visited[i, j] = true;
        str = str + boggle[i, j];

        // If str is present in dictionary,
        // then print it
        if (isWord(str))
            Console.WriteLine(str);

        // Traverse 8 adjacent cells of boggle[i,j]
        for (int row = i - 1; row <= i + 1 && row < M; row++)
            for (int col = j - 1; col <= j + 1 && col < N; col++)
                if (row >= 0 && col >= 0 && !visited[row, col])
                    findWordsUtil(boggle, visited, row, col, str);

        // Erase current character from string and 
        // mark visited of current cell as false
        str = "" + str[str.Length - 1];
        visited[i, j] = false;
    }

    // Prints all words present in dictionary.
    static void findWords(char [,]boggle)
    {
        // Mark all characters as not visited
        bool [,]visited = new bool[M, N];

        // Initialize current string
        String str = "";

        // Consider every character and look for all words
        // starting with this character
        for (int i = 0; i < M; i++)
            for (int j = 0; j < N; j++)
                findWordsUtil(boggle, visited, i, j, str);
    }

    // Driver Code
    public static void Main(String []args)
    {
        char [,]boggle = { { 'G', 'I', 'Z' },
                           { 'U', 'E', 'K' },
                           { 'Q', 'S', 'E' } };

        Console.WriteLine("Following words of " +  
                          "dictionary are present");
        findWords(boggle);
    }
}

// This code is contributed by PrinciRaj1992
JavaScript
<script>
      // JavaScript program for Boggle game
      // Let the given dictionary be following
      var dictionary = ["GEEKS", "FOR", "QUIZ", "GO"];
      var n = dictionary.length;
      var M = 3,
        N = 3;

      // A given function to check if a given string
      // is present in dictionary. The implementation is
      // naive for simplicity. As per the question
      // dictionary is given to us.
      function isWord(str)
      {
      
        // Linearly search all words
        for (var i = 0; i < n; i++) if (str == dictionary[i]) return true;
        return false;
      }

      // A recursive function to print all words present on boggle
      function findWordsUtil(boggle, visited, i, j, str)
      {
      
        // Mark current cell as visited and
        // append current character to str
        visited[i][j] = true;
        str = str + boggle[i][j];

        // If str is present in dictionary,
        // then print it
        if (isWord(str)) document.write(str + "<br>");

        // Traverse 8 adjacent cells of boggle[i,j]
        for (var row = i - 1; row <= i + 1 && row < M; row++)
          for (var col = j - 1; col <= j + 1 && col < N; col++)
            if (row >= 0 && col >= 0 && !visited[row][col])
              findWordsUtil(boggle, visited, row, col, str);

        // Erase current character from string and
        // mark visited of current cell as false
        str = "" + str[str.length - 1];
        visited[i][j] = false;
      }

      // Prints all words present in dictionary.
      function findWords(boggle) 
      {
      
        // Mark all characters as not visited
        var visited = Array.from(Array(M), () => new Array(N).fill(0));

        // Initialize current string
        var str = "";

        // Consider every character and look for all words
        // starting with this character
        for (var i = 0; i < M; i++)
          for (var j = 0; j < N; j++) findWordsUtil(boggle, visited, i, j, str);
      }

      // Driver Code
      var boggle = [
        ["G", "I", "Z"],
        ["U", "E", "K"],
        ["Q", "S", "E"],
      ];

      document.write("Following words of " + "dictionary are present <br>");
      findWords(boggle);
      
      // This code is contributed by rdtank.
    </script>

Output
Following words of dictionary are present
GEEKS
QUIZ

Note that the above solution may print the same word multiple times. For example, if we add “SEEK” to the dictionary, it is printed multiple times. To avoid this, we can use hashing to keep track of all printed words.
To improve time complexity, we can use unordered_set(in C++) or dictionary(in Python) which takes constant search time. Now Time Complexity, Since we are doing depth-first traversal for every position in the array so n*m( time for one DFS) = n*m( |V| + |E|) where |V| is the total number of nodes and |E| is the total number of edges which are equal to n*m. So,

Time Complexity:  O(N2 *M2)
Auxiliary Space:   O(N*M)

Optimized Approach : 

Instead of generating all strings from the grid and then checking whether it exists in dictionary or not , we can simply run a DFS on all words present in dictionary and check whether we can make that word from grid or not. This Approach is more optimised then the previous one.

Below is the implementation of above Approach.

C++
// C++ program for Boggle game
#include<bits/stdc++.h>
using namespace std;
#define M 3
#define N 3

 bool dfs(vector<vector<char> >& board, string &s, int i, int j, int n, int m, int idx){
       
       if(i<0 || i>=n||j<0||j>=m){
           return false;
       }
       
       if(s[idx]!= board[i][j]){
           return false;
       }
       if(idx == s.size()-1){
           return true;
       }
       
       char temp = board[i][j];
       board[i][j]='*';
       
       bool a = dfs(board,s,i,j+1,n,m,idx+1);
       bool b= dfs(board,s,i,j-1,n,m,idx+1);
       bool c = dfs(board,s,i+1,j,n,m,idx+1);
       bool d = dfs(board,s,i-1,j,n,m,idx+1);
       bool e = dfs(board,s,i+1,j+1,n,m,idx+1);
       bool f = dfs(board,s,i-1,j+1,n,m,idx+1);
       bool g = dfs(board,s,i+1,j-1,n,m,idx+1);
       bool h = dfs(board,s,i-1,j-1,n,m,idx+1);
       
       board[i][j]=temp;
       return a||b||c||e||f||g||h||d;
       
       
   }
void wordBoggle(vector<vector<char> >& board, vector<string>& dictionary) {
           int n= board.size();
           int m = board[0].size();
           vector<string> ans;
           set<string> store;
            for(int i=0;i<dictionary.size();i++){
                string s = dictionary[i];
                int l = s.size();
                for(int j = 0 ; j < n;j++){
                    for(int k=0;k<m;k++){
                        if(dfs(board,s,j,k,n,m,0)){
                            store.insert(s);
                        }
                    }
                }
            }
            
            for(auto i:store){
                cout<<i<<"\n"; 
            }
           
            return ;
    
}

// Driver program to test above function
int main()
{
    vector<vector<char>> boggle{ { 'G', 'I', 'Z' },
                          { 'U', 'E', 'K' },
                          { 'Q', 'S', 'E' } };
    //     Let the given dictionary be following
    vector<string> dictionary{ "GEEKS", "FOR", "QUIZ", "GO" };
   
    cout << "Following words of dictionary are present\n";
    wordBoggle(boggle,dictionary);
    return 0;
}
// This code is contributed by Arpit Jain
Java
// Java program for Boggle game
import java.util.*;

public class BoggleGame {
    private static final int M = 3;
    private static final int N = 3;

    private static boolean dfs(char[][] board, String s, int i, int j, int n, int m, int idx) {
        if (i < 0 || i >= n || j < 0 || j >= m) {
            return false;
        }
        if (s.charAt(idx) != board[i][j]) {
            return false;
        }
        if (idx == s.length() - 1) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = '*';

        boolean a = dfs(board, s, i, j + 1, n, m, idx + 1);
        boolean b = dfs(board, s, i, j - 1, n, m, idx + 1);
        boolean c = dfs(board, s, i + 1, j, n, m, idx + 1);
        boolean d = dfs(board, s, i - 1, j, n, m, idx + 1);
        boolean e = dfs(board, s, i + 1, j + 1, n, m, idx + 1);
        boolean f = dfs(board, s, i - 1, j + 1, n, m, idx + 1);
        boolean g = dfs(board, s, i + 1, j - 1, n, m, idx + 1);
        boolean h = dfs(board, s, i - 1, j - 1, n, m, idx + 1);

        board[i][j] = temp;
        return a || b || c || e || f || g || h || d;
    }

    private static void wordBoggle(char[][] board, String[] dictionary) {
        int n = board.length;
        int m = board[0].length;
        Set<String> ans = new HashSet<>();
        Set<String> store = new HashSet<>();
        for (String s : dictionary) {
            int l = s.length();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (dfs(board, s, i, j, n, m, 0)) {
                        store.add(s);
                    }
                }
            }
        }
        for (String i : store) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        char[][] boggle = {
            {'G', 'I', 'Z'},
            {'U', 'E', 'K'},
            {'Q', 'S', 'E'}
        };
        // Let the given dictionary be following
        String[] dictionary = {"GEEKS", "FOR", "QUIZ", "GO"};

        System.out.println("Following words of dictionary are present");
        wordBoggle(boggle, dictionary);
    }
}

// This code is contributed by shivamsharma215
Python3
def dfs(board, s, i, j, n, m, idx):
    if i < 0 or i >= n or j < 0 or j >= m:
        return False
    if s[idx] != board[i][j]:
        return False
    if idx == len(s) - 1:
        return True
    temp = board[i][j]
    board[i][j] = '*'
    a = dfs(board, s, i, j+1, n, m, idx+1)
    b = dfs(board, s, i, j-1, n, m, idx+1)
    c = dfs(board, s, i+1, j, n, m, idx+1)
    d = dfs(board, s, i-1, j, n, m, idx+1)
    e = dfs(board, s, i+1, j+1, n, m, idx+1)
    f = dfs(board, s, i-1, j+1, n, m, idx+1)
    g = dfs(board, s, i+1, j-1, n, m, idx+1)
    h = dfs(board, s, i-1, j-1, n, m, idx+1)
    board[i][j] = temp
    return a or b or c or e or f or g or h or d

def wordBoggle(board, dictionary):
    n = len(board)
    m = len(board[0])
    store = set()
    
    #     Let the given dictionary be following
    for word in dictionary:
        for i in range(n):
            for j in range(m):
                if dfs(board, word, i, j, n, m, 0):
                    store.add(word)
    for word in store:
        print(word)

boggle = [['G', 'I', 'Z'],
          ['U', 'E', 'K'],
          ['Q', 'S', 'E']]
dictionary = ["GEEKS", "FOR", "QUIZ", "GO"]
print("Following words of dictionary are present:")
wordBoggle(boggle, dictionary)

# This code is contributed by vikramshirsath177
C#
// C# program for Boggle game
using System;
using System.Collections.Generic;

class Boggle
{
static int M = 3;
static int N = 3;
static bool dfs(char[][] board, string s, int i, int j, int n, int m, int idx)
{

    if (i < 0 || i >= n || j < 0 || j >= m)
    {
        return false;
    }

    if (s[idx] != board[i][j])
    {
        return false;
    }
    if (idx == s.Length - 1)
    {
        return true;
    }

    char temp = board[i][j];
    board[i][j] = '*';

    bool a = dfs(board, s, i, j + 1, n, m, idx + 1);
    bool b = dfs(board, s, i, j - 1, n, m, idx + 1);
    bool c = dfs(board, s, i + 1, j, n, m, idx + 1);
    bool d = dfs(board, s, i - 1, j, n, m, idx + 1);
    bool e = dfs(board, s, i + 1, j + 1, n, m, idx + 1);
    bool f = dfs(board, s, i - 1, j + 1, n, m, idx + 1);
    bool g = dfs(board, s, i + 1, j - 1, n, m, idx + 1);
    bool h = dfs(board, s, i - 1, j - 1, n, m, idx + 1);

    board[i][j] = temp;
    return a || b || c || e || f || g || h || d;


}
static void wordBoggle(char[][] board, string[] dictionary)
{
    int n = board.Length;
    int m = board[0].Length;
    List<string> ans = new List<string>();
    HashSet<string> store = new HashSet<string>();
    for (int i = 0; i < dictionary.Length; i++)
    {
        string s = dictionary[i];
        int l = s.Length;
        for (int j = 0; j < n; j++)
        {
            for (int k = 0; k < m; k++)
            {
                if (dfs(board, s, j, k, n, m, 0))
                {
                    store.Add(s);
                }
            }
        }
    }

    foreach (string i in store)
    {
        Console.WriteLine(i);
    }

    return;

}

// Driver program to test above function
public static void Main()
{
    char[][] boggle = new char[][] {
    new char[] { 'G', 'I', 'Z' },
    new char[] { 'U', 'E', 'K' },
    new char[] { 'Q', 'S', 'E' }
    };
    // Let the given dictionary be following
    string[] dictionary = new string[] {"GEEKS", "FOR", "QUIZ", "GO"};
Console.WriteLine("Following words of dictionary are present");  
wordBoggle(boggle, dictionary);
}
}

//This code is contributed by shivamsharma215
JavaScript
// Javascript program for Boggle game

      function dfs(board, s, i, j, n, m, idx) {
        if (i < 0 || i >= n || j < 0 || j >= m) {
          return false;
        }

        if (s[idx] != board[i][j]) {
          return false;
        }
        if (idx == s.length - 1) {
          return true;
        }

        temp = board[i][j];
        board[i][j] = "*";

        a = dfs(board, s, i, j + 1, n, m, idx + 1);
        b = dfs(board, s, i, j - 1, n, m, idx + 1);
        c = dfs(board, s, i + 1, j, n, m, idx + 1);
        d = dfs(board, s, i - 1, j, n, m, idx + 1);
        e = dfs(board, s, i + 1, j + 1, n, m, idx + 1);
        f = dfs(board, s, i - 1, j + 1, n, m, idx + 1);
        g = dfs(board, s, i + 1, j - 1, n, m, idx + 1);
        h = dfs(board, s, i - 1, j - 1, n, m, idx + 1);

        board[i][j] = temp;
        return a || b || c || e || f || g || h || d;
      }
      function wordBoggle(board, dictionary) {
        n = board.length;
        m = board[0].length;
        let ans = new Array();
        let store = new Set();
        for (let i = 0; i < dictionary.length; i++) {
          s = dictionary[i];
          for (let j = 0; j < n; j++) {
            for (let k = 0; k < m; k++) {
              if (dfs(board, s, j, k, n, m, 0)) {
                store.add(s);
              }
            }
          }
        }

        console.log(store);

        return;
      }

      // Driver program to test above function

      boggle = [
        ["G", "I", "Z"],
        ["U", "E", "K"],
        ["Q", "S", "E"],
      ];
      //Let the given dictionary be following
      dictionary = ["GEEKS", "FOR", "QUIZ", "GO"];

      console.log("Following words of dictionary are present");
      wordBoggle(boggle, dictionary);

Output
Following words of dictionary are present
GEEKS
QUIZ

Time Complexity: O(N*W + R*C^2)

Auxiliary Space: O(N*W + R*C)

In below set 2, we have discussed Trie based optimized solution: 
Boggle | Set 2 (Using Trie)



Previous Article
Next Article

Similar Reads

Boggle using Trie
Given a dictionary, a method to do a lookup in the dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of the same cell.Example: Input: dictionary[] = {"GE
15+ min read
Print all valid words from given dictionary that are possible using Characters of given Array
Given a dictionary of strings dict[] and a character array arr[]. 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: Only all the characters
5 min read
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 Trie data structure to store dictionary, then search
13 min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 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 problem has existing solution please refer Print all
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 can be used at most once and each word arr[i] can b
15+ min read
Print all possible words from phone digits
Given a keypad as shown in the diagram, and an n digit number, list all words which are possible by pressing these numbers. Before the advent of QWERTY keyboards, texts and numbers were placed on the same key. For example, 2 has "ABC", so if we wanted to write anything starting with 'A' we need to type key 2 once. If we wanted to type 'B', press ke
10 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Capitalize 1st character of all words having at least K characters
Given string str representing a sentence, and an integer K, the task is to capitalize all the words in the given sentence having at least K characters. Example: Input: str = "geeks for geeks", K = 4Output: Geeks for GeeksExplanation: The word "for" does not contain 4 characters, hence its 1st character is not capitalize. Input: str = "geeksforgeeks
5 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Print all possible strings of length k that can be formed from a set of n characters
Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set. Examples: Input: set[] = {'a', 'b'}, k = 3 Output: aaa aab aba abb baa bab bba bbb Input: set[] = {'a', 'b', 'c', 'd'}, k = 1 Output: a b c d For a given set of size n, there will be n^k possible strings of length k. The
6 min read
Find all the possible mappings of characters in a sorted order
Given a number find all the possible mappings of the characters in sorted order.Examples: Input: 123 Output: ABC AW LC Explanation: 1 = A; 2 = B; 3 = C; 12 = L; 23 = W {1, 2, 3} / \ / \ "A"{2, 3} "L"{3} / \ / \ / \ / \ "AB"{3} "A"{23} "LC" null / \ / \ / \ / \ "ABC" null "AW" null Input : 2122 Output : BABB BAV BLB UBB UV Approach : A recursive fun
7 min read
Print all unique combinations of setting N pieces on an NxN board
Given an integer N, the task is to print all the unique combinations of putting N pieces in an NxN board. Note: Print ("*") for pieces and ("-") for an empty space. Example: Input: N = 2Output:* *- - * -* - * -- * - ** - - *- * - -* *Explanation: The total number of empty spaces are 2*2=4 and the pieces to be set is 2 so there are 4C2 combinations
8 min read
Minimum queens required to cover all the squares of a chess board
Given the dimension of a chess board (N x M), determine the minimum number of queens required to cover all the squares of the board. A queen can attack any square along its row, column or diagonals. Examples: Input : N = 8, M = 8Output : 5Layout : Q X X X X X X X X X Q X X X X X X X X X Q X X X X Q X X X X X X X X X Q X X X X X X X X X X X X X X X
14 min read
Group words with same set of characters
Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set. Example: Input: words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodle"}; Output : looped, poodle, lambs, balms, flow,
8 min read
Find minimum time to board taxi from current position
Given that there is an infinite number of points 1, 2, 3... on the X axis and your current position is cur. There are N taxis near you, and the position of those taxis is given as an array pos[]. Where pos[i] denotes the position of the ith taxi. You are also given an array of time[], where time[i] denotes the time taken by the ith taxi to cover 1
4 min read
Minimum LCM and GCD possible among all possible sub-arrays
Given an array arr[] of N positive integers, the task is to find the minimum LCM and GCD between elements of all possible sub-array.Examples: Input: arr[] = {4, 4, 8} Output: LCM = 4, GCD = 4 All possible sub-arrays are: {4} -> LCM = 4, GCD = 4 {8} -> LCM = 8, GCD = 8 {4, 8} -> LCM = 8, GCD = 4Input: arr[] = {2, 66, 14, 521} Output: LCM =
6 min read
Sum of all possible expressions of a numeric string possible by inserting addition operators
Given a numeric string str of length N, the task is to find the sum of all possible expressions by inserting the '+' operator between the characters of the string any number of times. Examples: Input: str = "125" Output: 176 Explanation: Inserting "+" after 1st index modifies str to "1+25" and value = 26 Inserting "+" after 2nd index modifies str t
8 min read
Generate all possible combinations of at most X characters from a given array
Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ? X ? N). Examples: Input: N = 3, X = 2, arr[] = {'a', 'b', 'a'}Output: a b c bc ca ab cb ac baExplanation: All possible combinations using 1 character is 3 {'a', 'b', 'c'}. All possible combinations using 2 characters are {"
6 min read
Shortest string possible after removal of all pairs of similar adjacent characters
Given a string S, the task is to find the resultant smallest string possible, formed by repeatedly removing pairs of adjacent characters which are equal. Examples: Input: S = "aaabccddd"Output: abdExplanation: Following sequence of removal of pairs of adjacent characters minimizes the length of the string: aaabccddd ? abccddd ? abddd ? abd. Input:
8 min read
Replace minimal number of characters to make all characters pair wise distinct
Given a string consisting of only lowercase English alphabets. The task is to find and replace the minimal number of characters with any lower case character in the given string such that all pairs of characters formed from the string are distinct. If it is impossible to do so, print "IMPOSSIBLE". Note: If there is more than one answer possible, pr
10 min read
Minimum characters to be replaced to make frequency of all characters same
Given a string S consisting of alphabets ['A' - 'Z'], the task is to find the minimum number of operations required to make frequency of every character equal. In one operation any character of the string can be chosen and replaced with another valid character.Examples: Input: S = "ABCB" Output: 1 Explanation: In the given string character 'C' can
6 min read
Modify string by replacing all occurrences of given characters by specified replacing characters
Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1]. Examples: Input: S = "aabbgg", P[][2] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation:Replace 'a' by 'b' in the original string. Now t
12 min read
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings
Given a binary string S, and two integers A, which denotes the cost of reversing a substring, and B, which denotes the cost of flipping all characters of a substring, the task is to find the minimum cost to reduce the string S to 1s only. Examples: Input: S = "01100", A = 1, B = 5Output: 6Explanation: One possible way to make all characters equal t
8 min read
Minimum characters to be replaced in given String to make all characters same
Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the characters except 'e' of the string with 'e'. Inp
7 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input : 010101100011Output : 4Method 1 (Change in value
8 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Python | Toggle characters in words having same case
Given a string, toggle the characters of those words who have all their characters in the same case. Examples: Input : Geeks for Geeks Output : Geeks FOR Geeks Explanation: The string contains three words "Geeks", "for", "Geeks" out of which the word "for" contains all its characters as lower cases, therefore, toggle the case of the word. Print the
4 min read
K length words that can be formed from given characters without repetition
Given an integer k and a string str consisting of lowercase English alphabets, the task is to count how many k-character words (with or without meaning) can be formed from the characters of str when repetition is not allowed. Examples: Input: str = "cat", k = 3 Output: 6 Required words are "cat", "cta", "act", "atc", "tca" and "tac". Input: str = "
6 min read
Find all the possible remainders when N is divided by all positive integers from 1 to N+1
Given a large integer N, the task is to find all the possible remainders when N is divided by all the positive integers from 1 to N + 1. Examples: Input: N = 5 Output: 0 1 2 5 5 % 1 = 0 5 % 2 = 1 5 % 3 = 2 5 % 4 = 1 5 % 5 = 0 5 % 6 = 5 Input: N = 11 Output: 0 1 2 3 5 11 Naive approach: Run a loop from 1 to N + 1 and return all the unique remainders
5 min read
Article Tags :
Practice Tags :