Word Search
JavaScript
medium
15 mins
You are given a 2D board of characters and a list of words. Your task is to find all the words from the list that can be constructed from letters of sequentially adjacent cells in the board.
You can move in all 8 directions:
- Horizontally: left โ right
- Vertically: up โ down
- Diagonally: all 4 diagonal directions
You cannot use the same cell more than once for the same word.
๐งช Example
Input:
const board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ]; const words = ["oath", "pea", "eat", "rain"];
Output:
["oath", "eat"]
Explanation:
- "oath" and "eat" are found in the board following valid directions.
- "pea" and "rain" are not present in any valid path.
โ Constraints
- The board contains only lowercase English letters.
- The same cell may not be reused within a word path.
- The words list may contain up to 3 * 10โด words.
- The board dimensions can be up to 12 x 12.
โ ๏ธ Edge Cases to Consider
- If the
boardis empty, return an empty array. - If the
wordslist is empty, return an empty array. - Words may appear more than once via different paths, but should only be added once in the result.
- Words can appear diagonally as well โ all 8 directions must be supported.
Companies:
amazon
meta
google
Solve Similar questions ๐ฅ
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
