call(back)
Algorithms & Data Structureseasy

First Word Containing a Prefix

You are given words, sorted ascending (duplicates allowed), and a prefix. Return the index of the first word that starts with prefix, or -1. Aim for O(log n) string comparisons.

words = ["a", "apple", "appz", "b"]
prefix "ap"  => 1
prefix "b"   => 3
prefix "c"   => -1
prefix ""    => 0     (every word starts with "")

Up to 10^5 words of lowercase a-z, lengths up to 100.

Follow-ups (these carry the round)

  • Return the whole inclusive range [first, last] of matching indexes, or [-1, -1]: matchRange(words, prefix).
  • Many queries against one list — preprocess so each query costs O(len(prefix)) regardless of n. (A trie storing first index and count per node.)

Asked at