Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
BFS instead of DFS?

Murtuza Chhatriwala

Feb 6, 2024

Wouldn't BFS be needed instead of DFS in order to comply with - "If there are more than 3 matching products, return 3 lexicographically smallest products. These product names should be returned in lexicographical (alphabetical) order."

0

0

Comments
Comments
J
Jimmy a year ago

DFS is correct. Assume "aa", "ab", and "aaa" are valid prefixes. If the search term is "a", using DFS, you will visit nodes "aa", "aaa", "ab" in that order. That is lexicographical order. With BFS, you will visit "aa" and "ab" before visiting "aaa". You are essentially ...

Steve Ochoa
Steve Ochoaa year ago

The Trie is built on DFS (insert(word)) so you need to run a DFS to recall the word. Path of DFS from the root to the leaf (isEnd=True) represents one full word.

On this page