Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Word Search

Medium Acceptance 32.69% Points 30.00

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).

Hints
Hint 1
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
Hint 2
Expected Space Compelxity: O(L), L is length of word.
Constraints
  • 1 <= N, M <= 100
  • 1 <= L <= N*M
Companies
Amazon Microsoft Apple
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions