Replace Words

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Replace Words

Approach

Insert all roots in trie. For each word, walk characters until a terminal root node appears and replace immediately.

Complexity Analysis

Time
O(D * R + S * L)
Space
O(D * R)

Pattern

Trie Prefix Replacement

Why It Works

First terminal reached in the trie walk is the shortest matching root because we process from left to right in a single pass.

Updated Mar 2026