00:00

Problem Statement

Input/Output Examples

Visual Explanation

search and startsWith walk the same path; the only difference is that search also requires the end-of-word flag on the last node.

Approaches

Both approaches store the same tree. One gives each node an array of 26 children; the other a map.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here L is the length of the word or prefix. Every operation walks one path of length L, independent of how many words are stored.

Interview Tips and Recommended Approach

  • Use an end-of-word flag. Without it, prefixes are indistinguishable from words.
  • Reuse the walk helper for both search and startsWith.
  • Know the applications: autocomplete, spell checking, IP routing and word games.
  • Discuss memory. Arrays are fast but large; maps are compact but slower.

Recommended Approach: Array of 26 Children

Why: it gives constant-time child access for lowercase words and the simplest code for insert, search and prefix queries.