The Wayback Machine - https://web.archive.org/web/20240930174650/https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/
Open In App

Word Search in a 2D Grid of characters

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

Given a 2D grid m*n of characters and a word, the task is to find all occurrences of the given word in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form).
The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonal directions.

Note: The returning list should be lexicographically smallest. If the word can be found in multiple directions starting from the same coordinates, the list should contain the coordinates only once. 

Examples: 

Input:
grid = {{G,E,E,K,S,F,O,R,G,E,E,K,S}, {G,E,E,K,S,Q,U,I,Z,G,E,E,K}, {I,D,E,Q,A,P,R,A,C,T,I,C,E}}
word = “GEEKS”
Output: {{0,0}, {0,8}, {1,0}}

ex-3_1

Input:
grid = {{a,b,a,b},{a,b,e,b},{e,b,e,b}}
word = “abe”
Output:
{{0,0},{0,2},{1,0}}

2222

[Naive Approach] Using Recursion – O(m*n*k) Time and O(k) Space

The idea is to search for a specified word in a 2D grid of characters by exploring all eight possible straight-line directions from each starting character. It first checks if a coordinate is valid and then uses a recursive function to check for the word in a specified direction. For each character that matches the first letter of the word, the program initiates a search in all directions. If the word is found, the starting coordinates are recorded. The results are stored into a vector and returned, ensuring that the search is conducted without zig-zagging, thereby efficiently identifying all occurrences of the word in the grid.
C++
// C++ program to search a word in a 2D grid
#include <bits/stdc++.h>
using namespace std;


// This function checks if the given 
// coordinate is valid
bool validCoord(int x, int y, int m, int n) {
    if (x>=0 && x<m && y>=0 && y<n)
        return true;
    return false;
}

// This function searches for the given word
// in a given direction from the coordinate.
bool findWord(int index, string word, vector<vector<char>> &grid, int x, int y, int dirX, int dirY) {
    
    // if word has been found
    if (index == word.length()) return true;
    
    // if the current coordinate is 
    // valid and characters match, then
    // check the next index
    if (validCoord(x, y, grid.size(), grid[0].size()) && word[index] == grid[x][y])
        return findWord(index+1, word, grid, x+dirX, y+dirY, dirX, dirY);
        
    return false;
}

// This function calls search2D for each coordinate
vector<vector<int>>searchWord(vector<vector<char>>grid, string word){
    int m = grid.size();
    int n = grid[0].size();
    
    vector<vector<int>>ans;
    
    // x and y are used to set the direction in which
    // word needs to be searched.
    vector<int>x = { -1, -1, -1, 0, 0, 1, 1, 1 };
    vector<int>y = { -1, 0, 1, -1, 1, -1, 0, 1 };
    
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            
            // Search in all 8 directions
            for (int k=0; k<8; k++) {
                
                // If word is found, then append the 
                // coordinates into answer and break.
                if (findWord(0, word, grid, i, j, x[k], y[k])) {
                    ans.push_back({i,j});
                    break;
                }
            }
        }
    }
    
    return ans;
}

void printResult(vector<vector<int>> ans) {
    for (int i=0; i<ans.size(); i++) {
        cout << ans[i][0] << "," << ans[i][1] << " ";
    }
    cout<<endl;
}

int main() {
    vector<vector<char>> grid = {{'a','b','a','b'},
                                 {'a','b','e','b'},
                                 {'e','b','e','b'}};
    string word = "abe";
    
    vector<vector<int>> ans = searchWord(grid, word);
    
    printResult(ans);
}
Java
// Java program to search a word in a 2D grid
import java.util.*;

class GfG {

    // This function checks if the given
    // coordinate is valid
    static boolean validCoord(int x, int y, int m, int n) {
        if (x >= 0 && x < m && y >= 0 && y < n)
            return true;
        return false;
    }

    // This function searches for the given word
    // in a given direction from the coordinate.
    static boolean findWord(int index, String word, char[][] grid, int x, int y, int dirX, int dirY) {

        // if word has been found
        if (index == word.length()) return true;

        // if the current coordinate is
        // valid and characters match, then
        // check the next index
        if (validCoord(x, y, grid.length, grid[0].length) && 
        word.charAt(index) == grid[x][y])
            return findWord(index + 1, word, grid, x + dirX, y + dirY, dirX, dirY);

        return false;
    }

    // This function calls search2D for each coordinate
    static int[][] searchWord(char[][] grid, String word) {
        int m = grid.length;
        int n = grid[0].length;

        List<int[]> ans = new ArrayList<>();

        // x and y are used to set the direction in which
        // word needs to be searched.
        int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {

                // Search in all 8 directions
                for (int k = 0; k < 8; k++) {

                    // If word is found, then append the
                    // coordinates into answer and break.
                    if (findWord(0, word, grid, i, j, x[k], y[k])) {
                        ans.add(new int[] { i, j });
                        break;
                    }
                }
            }
        }

        return ans.toArray(new int[0][]);
    }

    static void printResult(int[][] ans) {
        for (int[] a : ans) {
            System.out.print(a[0] + "," + a[1] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        char[][] grid = { { 'a', 'b', 'a', 'b' },
                { 'a', 'b', 'e', 'b' },
                { 'e', 'b', 'e', 'b' } };
        String word = "abe";

        int[][] ans = searchWord(grid, word);

        printResult(ans);
    }
}
Python
# Python program to search a word in a 2D grid

# This function checks if the given
# coordinate is valid
def isValid(x, y, sizeX, sizeY):
    return 0 <= x < sizeX and 0 <= y < sizeY

def findWordInDirection(grid, n, m, word, index, x, y, dirX, dirY):
    if index == len(word):
        return True

    if isValid(x, y, n, m) and word[index] == grid[x][y]:
        return findWordInDirection(grid, n, m, word, index + 1, x + dirX, y + dirY, dirX, dirY)

    return False

def searchWord(grid, word):
    ans = []
    n = len(grid)
    m = len(grid[0])

    # Directions for 8 possible movements
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1),
                  (1, 1), (1, -1), (-1, 1), (-1, -1)]

    for i in range(n):
        for j in range(m):
          
            # Check if the first character matches
            if grid[i][j] == word[0]:  
                for dirX, dirY in directions:
                    if findWordInDirection(grid, n, m, word, 0, i, j, dirX, dirY):
                        ans.append([i, j])
                        break

    return ans

def printResult(ans):
    for a in ans:
        print(f"{a[0]},{a[1]}", end=" ")
    print()

if __name__ == "__main__":
    grid = [['a', 'b', 'a', 'b'],
            ['a', 'b', 'e', 'b'],
            ['e', 'b', 'e', 'b']]
    word = "abe"

    ans = searchWord(grid, word)
    printResult(ans)
C#
// C# program to search a word in a 2D grid
using System;
using System.Collections.Generic;

class GfG {

    // This function checks if the given
    // coordinate is valid
    static bool validCoord(int x, int y, int m, int n) {
        if (x >= 0 && x < m && y >= 0 && y < n)
            return true;
        return false;
    }

    // This function searches for the given word
    // in a given direction from the coordinate.
    static bool findWord(int index, string word, char[,] grid, int x, int y, int dirX, int dirY) {

        // if word has been found
        if (index == word.Length) return true;

        // if the current coordinate is
        // valid and characters match, then
        // check the next index
        if (validCoord(x, y, grid.GetLength(0), grid.GetLength(1)) && word[index] == grid[x, y])
            return findWord(index + 1, word, grid, x + dirX, y + dirY, dirX, dirY);

        return false;
    }

    // This function calls search2D for each coordinate
    static int[][] searchWord(char[,] grid, string word) {
        int m = grid.GetLength(0);
        int n = grid.GetLength(1);

        List<int[]> ans = new List<int[]>();

        // x and y are used to set the direction in which
        // word needs to be searched.
        int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {

                // Search in all 8 directions
                for (int k = 0; k < 8; k++) {

                    // If word is found, then append the
                    // coordinates into answer and break.
                    if (findWord(0, word, grid, i, j, x[k], y[k])) {
                        ans.Add(new int[] { i, j });
                        break;
                    }
                }
            }
        }

        return ans.ToArray();
    }

    static void printResult(int[][] ans) {
        foreach (var a in ans) {
            Console.Write(a[0] + "," + a[1] + " ");
        }
        Console.WriteLine();
    }

    static void Main() {
        char[,] grid = {
            { 'a', 'b', 'a', 'b' },
            { 'a', 'b', 'e', 'b' },
            { 'e', 'b', 'e', 'b' }
        };
        string word = "abe";

        int[][] ans = searchWord(grid, word);

        printResult(ans);
    }
}
JavaScript
// JavaScript program to search a word in a 2D grid

// This function checks if the given 
// coordinate is valid
function validCoord(x, y, m, n) {
    return (x >= 0 && x < m && y >= 0 && y < n);
}

// This function searches for the given word
// in a given direction from the coordinate.
function findWord(index, word, grid, x, y, dirX, dirY) {

    // if word has been found
    if (index === word.length) return true;

    // if the current coordinate is 
    // valid and characters match, then
    // check the next index
    if (validCoord(x, y, grid.length, grid[0].length) 
    && word[index] === grid[x][y])
        return findWord(index + 1, word, grid, x + dirX, y + dirY, dirX, dirY);

    return false;
}

// This function calls search2D for each coordinate
function searchWord(grid, word) {
    let m = grid.length;
    let n = grid[0].length;

    let ans = [];

    // x and y are used to set the direction in which
    // word needs to be searched.
    let x = [-1, -1, -1, 0, 0, 1, 1, 1];
    let y = [-1, 0, 1, -1, 1, -1, 0, 1];

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {

            // Search in all 8 directions
            for (let k = 0; k < 8; k++) {

                // If word is found, then append the 
                // coordinates into answer and break.
                if (findWord(0, word, grid, i, j, x[k], y[k])) {
                    ans.push([i, j]);
                    break;
                }
            }
        }
    }

    return ans;
}

function printResult(ans) {
    for (let i = 0; i < ans.length; i++) {
        console.log(ans[i][0] + "," + ans[i][1]);
    }
}

const grid = [
    ['a', 'b', 'a', 'b'],
    ['a', 'b', 'e', 'b'],
    ['e', 'b', 'e', 'b']
];
const word = "abe";

const ans = searchWord(grid, word);

printResult(ans);

Output
0,0 0,2 1,0 

Time Complexity: O(m*n*k), where m is the number of rows, n is the number of columns and k is the length of word.
Auxiliary Space: O(k), recursion stack space.

[Expected Approach] Using Iteration – O(m*n*k) Time and O(1) Space

The iterative approach for searching a word in a 2D grid is similar to the recursive method. It checks each cell that matches the first character of the word and explores all eight possible directions—up, down, left, right, and the four diagonals. For each direction, the algorithm continues checking characters in a straight line, stopping if a mismatch occurs or if it goes out of bounds. This ensures the word must be contiguous and prevents zig-zagging.

C++
// C++ program to search a word in a 2D grid
#include <bits/stdc++.h>
using namespace std;

// This function searches for the given word
// in all 8 directions from the coordinate.
bool search2D(vector<vector<char>> grid, int row, int col, string word) {
    int m = grid.size();
    int n = grid[0].size();
    
    // return false if the given coordinate
    // does not match with first index char.
    if (grid[row][col] != word[0])
      return false;
 
    int len = word.size();
    
    // x and y are used to set the direction in which
    // word needs to be searched.
    vector<int>x = { -1, -1, -1, 0, 0, 1, 1, 1 };
    vector<int>y = { -1, 0, 1, -1, 1, -1, 0, 1 };
 
    // This loop will search in all the 8 directions
    // one by one. It will return true if one of the 
    // directions contain the word.
    for (int dir = 0; dir < 8; dir++) {
      
        // Initialize starting point for current direction
        int k, currX = row + x[dir], currY = col + y[dir];
 
        // First character is already checked, match remaining
        // characters
        for (k = 1; k < len; k++) {
          
            // break if out of bounds
            if (currX >= m || currX < 0 || currY >= n || currY < 0)
                break;
 
            if (grid[currX][currY] != word[k])
                break;
 
            //  Moving in particular direction
            currX += x[dir], currY += y[dir];
        }
 
        // If all character matched, then value of must
        // be equal to length of word
        if (k == len)
            return true;
    }
    
    // if word is not found in any direction,
    // then return false
    return false;
}

// This function calls search2D for each coordinate
vector<vector<int>>searchWord(vector<vector<char>>grid, string word){
    int m = grid.size();
    int n = grid[0].size();
    
    vector<vector<int>>ans;
    
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            
            // if the word is found from this coordinate,
            // then append it to result.
            if(search2D(grid, i, j, word)){
                ans.push_back({i, j});
            }
        }
    }
    
    return ans;
}

void printResult(vector<vector<int>> ans) {
    for (int i=0; i<ans.size(); i++) {
        cout << ans[i][0] << "," << ans[i][1] << " ";
    }
    cout<<endl;
}

int main() {
    vector<vector<char>> grid = 
    {{'a','b','a','b'},{'a','b','e','b'},{'e','b','e','b'}};
    string word = "abe";
    
    vector<vector<int>> ans = searchWord(grid, word);
    
    printResult(ans);
}
Java
// Java program to search word in 2D
// grid in 8 directions
import java.util.*;

class GfG {

    // This function searches for the given word
    // in all 8 directions from the coordinate.
    static boolean search2D(char[][] grid, int row, int col,String word) {
        int m = grid.length;
        int n = grid[0].length;

        // return false if the given coordinate
        // does not match with first index char.
        if (grid[row][col] != word.charAt(0))
            return false;

        int len = word.length();

        // x and y are used to set the direction in which
        // word needs to be searched.
        int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };

        // This loop will search in all the 8 directions
        for (int dir = 0; dir < 8; dir++) {
            int k, currX = row + x[dir],
                   currY = col + y[dir];

            // First character is already checked, match
            // remaining
            for (k = 1; k < len; k++) {
                if (currX >= m || currX < 0 || currY >= n
                    || currY < 0)
                    break;

                if (grid[currX][currY] != word.charAt(k))
                    break;

                currX += x[dir];
                currY += y[dir];
            }

            if (k == len)
                return true;
        }

        return false;
    }

    // This function calls search2D for each coordinate
    static int[][] searchWord(char[][] grid, String word) {
        int m = grid.length;
        int n = grid[0].length;

        // Max possible occurrences
        int[][] ans = new int[m * n][2];
        int count = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (search2D(grid, i, j, word)) {
                    ans[count][0] = i;
                    ans[count][1] = j;
                    count++;
                }
            }
        }

        // Resize the array to fit the actual number of
        // found coordinates
        int[][] result = new int[count][2];
        for (int i = 0; i < count; i++) {
            result[i] = ans[i];
        }

        return result;
    }

    static void printResult(int[][] ans) {
        for (int[] coords : ans) {
            System.out.print(coords[0] + "," + coords[1]
                             + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
      
        char[][] grid = { { 'a', 'b', 'a', 'b' },
                          { 'a', 'b', 'e', 'b' },
                          { 'e', 'b', 'e', 'b' } };
        String word = "abe";

        int[][] ans = searchWord(grid, word);

        printResult(ans);
    }
}
Python
# Python program to search word in 2D grid in 8 directions

# This function searches for the given word
# in all 8 directions from the coordinate.


def search2D(grid, row, col, word):
    m = len(grid)
    n = len(grid[0])

    # return false if the given coordinate
    # does not match with first index char.
    if grid[row][col] != word[0]:
        return False

    lenWord = len(word)

    # x and y are used to set the direction in which
    # word needs to be searched.
    x = [-1, -1, -1, 0, 0, 1, 1, 1]
    y = [-1, 0, 1, -1, 1, -1, 0, 1]

    # This loop will search in all the 8 directions
    # one by one. It will return true if one of the
    # directions contain the word.
    for dir in range(8):

        # Initialize starting point for current direction
        currX, currY = row + x[dir], col + y[dir]
        k = 1

        while k < lenWord:

            # break if out of bounds
            if currX >= m or currX < 0 or currY >= n or currY < 0:
                break

            # break if characters dont match
            if grid[currX][currY] != word[k]:
                break

            # Moving in particular direction
            currX += x[dir]
            currY += y[dir]
            k += 1

        # If all character matched, then value of must
        # be equal to length of word
        if k == lenWord:
            return True

    # if word is not found in any direction,
    # then return false
    return False

# This function calls search2D for each coordinate


def searchWord(grid, word):
    m = len(grid)
    n = len(grid[0])

    ans = []

    for i in range(m):
        for j in range(n):

            # if the word is found from this coordinate,
                    # then append it to result.
            if search2D(grid, i, j, word):
                ans.append((i, j))

    return ans


def printResult(ans):
    for coord in ans:
        print(f"{coord[0]},{coord[1]} ", end="")
    print()


if __name__ == "__main__":
    grid = [['a', 'b', 'a', 'b'],
            ['a', 'b', 'e', 'b'],
            ['e', 'b', 'e', 'b']]
    word = "abe"

    ans = searchWord(grid, word)

    printResult(ans)
C#
// C# program to search word in 2D grid in 8 directions
using System;
using System.Collections.Generic;

class GfG {
    
    // This function searches for the given word
    // in all 8 directions from the coordinate.
    static bool search2D(char[][] grid, int row, int col, string word) {
        int m = grid.Length;
        int n = grid[0].Length;
        
        // return false if the given coordinate
        // does not match with first index char.
        if (grid[row][col] != word[0])
            return false;
        
        int len = word.Length;
        
        // x and y are used to set the direction in which
        // word needs to be searched.
        int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };
        
        // This loop will search in all the 8 directions
        // one by one. It will return true if one of the 
        // directions contain the word.
        for (int dir = 0; dir < 8; dir++) {
            
            // Initialize starting point for current direction
            int k, currX = row + x[dir], currY = col + y[dir];
            
            // First character is already checked, match remaining
            // characters
            for (k = 1; k < len; k++) {
                
                // break if out of bounds
                if (currX >= m || currX < 0 || currY >= n || currY < 0)
                    break;
                
                // break if characters dont match
                if (grid[currX][currY] != word[k])
                    break;
                
                // Moving in particular direction
                currX += x[dir];
                currY += y[dir];
            }
            
            // If all character matched, then value of must
            // be equal to length of word
            if (k == len)
                return true;
        }
        
        // if word is not found in any direction,
        // then return false
        return false;
    }
    
    // This function calls search2D for each coordinate
    static List<int[]> searchWord(char[][] grid, string word) {
        int m = grid.Length;
        int n = grid[0].Length;
        List<int[]> ans = new List<int[]>();
        
        // if the word is found from this coordinate,
        // then append it to result.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (search2D(grid, i, j, word)) {
                    ans.Add(new int[] { i, j });
                }
            }
        }
        
        return ans;
    }

    static void printResult(List<int[]> ans) {
        foreach (var coord in ans) {
            Console.Write($"{coord[0]},{coord[1]} ");
        }
        Console.WriteLine();
    }

    static void Main() {
        char[][] grid = new char[][] {
            new char[] { 'a', 'b', 'a', 'b' },
            new char[] { 'a', 'b', 'e', 'b' },
            new char[] { 'e', 'b', 'e', 'b' }
        };
        string word = "abe";
        
        List<int[]> ans = searchWord(grid, word);
        
        printResult(ans);
    }
}
JavaScript
// JavaScript program to search word in 2D grid in 8 directions

// This function searches for the given word
// in all 8 directions from the coordinate.
function search2D(grid, row, col, word) {
    let m = grid.length;
    let n = grid[0].length;
    
    // return false if the given coordinate
    // does not match with first index char.
    if (grid[row][col] !== word[0]) return false;
    
    let len = word.length;
    
    // x and y are used to set the direction in which
    // word needs to be searched.
    let x = [-1, -1, -1, 0, 0, 1, 1, 1];
    let y = [-1, 0, 1, -1, 1, -1, 0, 1];
    
    // This loop will search in all the 8 directions
    // one by one. It will return true if one of the 
    // directions contain the word.
    for (let dir = 0; dir < 8; dir++) {
        
        // Initialize starting point for current direction
        let currX = row + x[dir], currY = col + y[dir], k = 1;
        
        // First character is already checked, match remaining
        // characters
        for (k = 1; k < len; k++) {
            
            // break if out of bounds
            if (currX >= m || currX < 0 || currY >= n || currY < 0) break;
            
            // break if characters dont match
            if (grid[currX][currY] !== word[k]) break;
            
            //  Moving in particular direction
            currX += x[dir];
            currY += y[dir];
        }
        
        // If all character matched, then value of must
        // be equal to length of word
        if (k === len) return true;
    }
    
    // if word is not found in any direction,
    // then return false
    return false;
}

// This function calls search2D for each coordinate
function searchWord(grid, word) {
    let m = grid.length;
    let n = grid[0].length;
    let ans = [];
    
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            
            // if the word is found from this coordinate,
            // then append it to result.
            if (search2D(grid, i, j, word)) {
                ans.push([i, j]);
            }
        }
    }
    
    return ans;
}

function printResult(ans) {
    ans.forEach(coord => {
        console.log(`${coord[0]},${coord[1]} `);
    });
}

let grid = [
    ['a', 'b', 'a', 'b'],
    ['a', 'b', 'e', 'b'],
    ['e', 'b', 'e', 'b']
];
let word = "abe";

let ans = searchWord(grid, word);
printResult(ans);

Output
0,0 0,2 1,0 

Time complexity: O(m*n*k), where m is the number of rows, n is the number of columns and k is the length of word.
Auxiliary Space: O(1). 



Previous Article
Next Article

Similar Reads

Print the indices for every row of a grid from which escaping from the grid is possible
Given a binary 2D array arr[] of dimension M * N representing a grid where '0' represents that there is a wall on the main diagonal of the cell and '1' represents that there is a wall on cross diagonal of the cell. The task is for every ith row is to print the index of the row from which one can escape the grid, given that one cannot escape from th
15 min read
Maximize median of a KxK sub-grid in an NxN grid
Given a square matrix arr[][] of size N consisting of non-negative integers and an integer K, the task is to find the maximum median value of the elements of a square submatrix of the size K. Examples: Input: arr[][] = {{1, 5, 12}, {6, 7, 11}, {8, 9, 10}}, N = 3, K = 2Output: 9Explanation: The median of all subsquare of size 2*2 are: The subsquare
14 min read
Check if a word exists in a grid or not
Given a 2D grid of characters and a word/ multiple words, the task is to check if that word/words exist in the grid or not. A word can be matched in 4 directions at any point.The 4 directions are Horizontally Left and Right, Vertically Up and Down. Examples: Input: grid[][] = {"axmy", "bgdf", "xeet", "raks"}; Output: Yes a x m y b g d f x e e t r a
15+ min read
Find the word from a given sentence having given word as prefix
Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1. Examples: Input: S = "Welcome to Geeksforgeeks", word="Gee"Output: GeeksforgeeksExplanation:The word "Geeksforgeeks" in the sentence has the prefix "Gee". In
8 min read
Longest Common Prefix using Word by Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended PracticeLongest Common Prefix in an ArrayTry It! We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest co
15 min read
Word Ladder (Length of shortest chain to reach a target word)
Given a dictionary, and two words 'start' and 'target' (both of same length). Find length of the smallest chain from 'start' to 'target' if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the 'target' word exists in dic
15+ min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Convert a String into a square matrix grid of characters
Given a string of length L. The task is to convert the string into a grid.Examples: Input : str = "haveaniceday" Output : have anic eday Explanation: k is the separator. If k is 4 then the output will be "have anic eday" Input :str = "geeksforgeeks" Output : geek sfor geek s Note: & l = length of the string Approach: Without using an inbuilt fu
5 min read
Longest word in ternary search tree
Given a set of words represented in a ternary search tree, find the length of largest word among them. Examples: Input : {"Prakriti", "Raghav", "Rashi", "Sunidhi"} Output : Length of largest word in ternary search tree is: 8 Input : {"Boats", "Boat", "But", "Best"} Output : Length of largest word in ternary search tree is: 5 Prerequisite : Ternary
11 min read
Add and Search Word - Data Structure Design
Design a data structure GFGDictionary that enables to support the feature of adding new words and searching for words. The GFGDictionary class should have the following implementation: GFGDictionary(): constructor to initialize the objectvoid insertWord(word): function to insert word into the data structure.bool findWord(word): function to return t
4 min read
Print list items containing all characters of a given word
There is a list of items. Given a specific word, e.g., "sun", print out all the items in list which contain all the characters of "sun". For example if the given word is "sun" and the items are "sunday", "geeksforgeeks", "utensils", ""just" and "sss", then the program should print "sunday" and "utensils". Algorithm: Thanks to geek4u for suggesting
7 min read
Next word that does not contain a palindrome and has characters from first k
Given a string and a limit k, find lexicographically next word which contains characters from a set of first K letters of the English alphabet and does not contain a palindrome as it's substring of length more than one. It may be assumed that the input string does not contain a palindromic substring. Examples: Input : s = "cba" k = 4 Output : cbd I
7 min read
Arrangement of the characters of a word such that all vowels are at odd places
Given a string 'S' containing vowels and consonants of lowercase English alphabets. The task is to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions. Examples: Input: geeks Output: 36 [Tex]3_P_2 \times 3_P_3 = 36 [/Tex] Input: publish Output: 1440 [Tex]4_P_2 \times 5_P_5 =
9 min read
Find the count of sub-strings whose characters can be rearranged to form the given word
Given a string str, the task is to find the count of all the sub-strings of length four whose characters can be rearranged to form the word "clap".Examples: Input: str = "clapc" Output: 2 "clap" and "lapc" are the required sub-strings Input: str = "abcd" Output: 0 Approach: For every sub-string of length four, count the occurrences of the character
6 min read
Check if characters of each word can be rearranged to form an Arithmetic Progression (AP)
Given string str, the task is to check if it is possible to rearrange the string such that the characters of each word of the given string are in Arithmetic Progression. Examples: Input: str = "ace yzx fbd"Output: trueExplanation: Rearrange the given string to "ace xyz bdf".All the characters of the word "ace" are in AP with a common difference of
7 min read
Word matching by swapping and incrementing characters
Given two strings A and B, determine if string A can be made equal to string B by performing some operations on string A any number of times. Before starting the operations, we have to choose an integer K > 1. The operations that can be performed on String A are: Type 1: Select any index i (0 ≤ i< length(A)-1) and swap(A[i], A[i+1]).Type 2: S
10 min read
Find largest word in dictionary by deleting some characters of given string
Giving a dictionary and a string 'str', find the longest string in dictionary which can be formed by deleting some characters of the given 'str'. Examples: Input : dict = {"ale", "apple", "monkey", "plea"} str = "abpcplea" Output : apple Input : dict = {"pintu", "geeksfor", "geeksgeeks", " forgeek"} str = "geeksforgeeks" Output : geeksgeeks Asked I
14 min read
Possibility of a word from a given set of characters
Given two strings 's' and 'q', check if all characters of q are present in 's'. Examples: Example: Input: s = "abctd" q = "cat" Output: Yes Explanation: All characters of "cat" are present in "abctd" Input: s = dog hod Output: No Explanation: Given query 'hod' hod has the letter 'h' which is not available in set 'dog', hence the output is no. A sim
5 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Anagram Substring Search (Or Search for all permutations) | Set 2
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Input: txt[] = "AAABABAA" p
10 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
Sublist Search (Search a linked list in another list)
Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input: list1 = 10->20 list2 = 5->10->20 Output : LIST FOUNDInput: list1 = 1->2->3->4 list2 = 1->2->1->2->3->4 Output: LIST FOUNDInput: list1 = 1->2->3->4 list2 = 1->2->2->1->2->3 Outpu
15+ min read
Best First Search (Informed Search)
In BFS and DFS, when we are at a node, we can consider any of the adjacent as the next node. So both BFS and DFS blindly explore paths without considering any cost function.  The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuri
9 min read