Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1858: Longest Word With All Prefixes

In this guide, we solve Leetcode #1858 Longest Word With All Prefixes in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given an array of strings words, find the longest string in words such that every prefix of it is also in words. For example, let words = ["a", "app", "ap"].

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Depth-First Search, Trie, Array, String

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: words = ["k","ki","kir","kira", "kiran"] Output: "kiran" Explanation: "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.

Python Solution

class Trie: __slots__ = ["children", "is_end"] def __init__(self): self.children: List[Trie | None] = [None] * 26 self.is_end: bool = False def insert(self, w: str) -> None: node = self for c in w: idx = ord(c) - ord("a") if not node.children[idx]: node.children[idx] = Trie() node = node.children[idx] node.is_end = True def search(self, w: str) -> bool: node = self for c in w: idx = ord(c) - ord("a") node = node.children[idx] if not node.is_end: return False return True class Solution: def longestWord(self, words: List[str]) -> str: trie = Trie() for w in words: trie.insert(w) ans = "" for w in words: if (len(w) > len(ans) or len(w) == len(ans) and w < ans) and trie.search(w): ans = w return ans

Complexity

The time complexity is O(∑w∈words∣w∣)O(\sum_{w \in words} |w|)O(∑w∈words​∣w∣), and the space complexity is O(∑w∈words∣w∣)O(\sum_{w \in words} |w|)O(∑w∈words​∣w∣). The space complexity is O(∑w∈words∣w∣)O(\sum_{w \in words} |w|)O(∑w∈words​∣w∣).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy