Grokking LinkedIn Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
E H
BFS Implementation

E H

Apr 2, 2025

I found it a bit more easier and understandable to do this in a BFS way. Time and space complexity remains the same.

// class TrieNode { // TrieNode[] children = new TrieNode[26]; // Representing each character of the alphabet. // boolean isEnd = false; // To determine if the current TrieNode marks the end of a word. // } public class Solution { private TrieNode root; public Solution() { // ToDo: Write Your Code Here. this.root = new TrieNode(); } // Function to add a word into the trie structure. public void addWord(String word) { // ToDo: Write Your Code Here. TrieNode start = root; for (char c : word.toCharArray()) { if (start.children[c - 'a'] == null) { start.children[c - 'a'] = new TrieNode(); } start = start.children[c - 'a']; } start.isEnd = true; } // Function to search a word, considering '.' as a wildcard. public boolean search(String word) { // ToDO: Write Your Code Here. TrieNode start = root; Queue<TrieNode> queue = new LinkedList<>(); queue.offer(start); for (char c : word.toCharArray()) { int queueSize = queue.size(); for (int i = 0; i < queueSize; i++) { TrieNode popped = queue.poll(); if (c == '.') { for (int j = 0; j < popped.children.length; j++) { if (popped.children[j] != null) { queue.offer(popped.children[j]); } } } else { if (popped.children[c - 'a'] == null) continue; queue.offer(popped.children[c - 'a']); } } } while (!queue.isEmpty()) { TrieNode popped = queue.poll(); if (popped.isEnd) return true; } return false; } }

0

0

Comments
Comments

On this page