Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Word Search

Medium Acceptance 32.69% Points 30

Given a 2D grid of letters and a target word, determine if the word can be formed by sequentially connecting letters in adjacent cells. The word can only be constructed by using horizontal or vertical neighboring cells, and each cell can be used at most once.

Your task is to implement the function isWordExist(), which takes a 2D board and a word as input parameters. The function should return true if the word can be formed from the board, and false otherwise.

Examples
Example 1

Example 1

Input: board = {{a,b,c,e}, {s,f,c,s}, {a,d,e,e}}, word = "abcd"

Output: 0

Explanation: The board is- a b c e , s f c s , a d e e. The word "abcd" cannot be formed because there is no adjacent path that includes the letter 'd' after 'c'. Therefore, the output is 0 (false).

Example 2

Example 2

Input: board = {{a,b,c,e}, {s,f,c,s}, {a,d,e,e}}, word = "see"

Output: 1

Explanation: The board is- a b c e , s f c s, a d e e. The word "see" can be constructed by using the adjacent cells: Starting at (2,3) -> 'e', (2,2) -> 'e', and (1,3) -> 's'. Hence, the output is 1 (true).

Constraints
  • 1 <= N, M <= 100
  • 1 <= L <= N*M
Hints
  • Expected Time Complexity: O(N * M * 4^L) where N = No. of rows in board, M = No. of columns in board, L = Length of word
  • Expected Space Compelxity: O(L), L is length of word.
Topics
Recursion
Companies
Amazon Microsoft Apple
Added 11 Apr 2025 32.69% acceptance
Ln 1, Col 1Sign in to save your code
3 4
a b c e
s f c s
a d e e
abcd
0