FastPrepDictionary Words With a Prefix

Dictionary Words With a Prefix

Google logoGoogle● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given an array of unique lowercase English words dictionary and a lowercase string prefix, return every dictionary word that starts with prefix.

Return matching words in lexicographic order. An empty prefix matches every word.

Function

wordsWithPrefix(dictionary: String[], prefix: String) → String[]

Examples

Example 1

dictionary = ["apple","app","bat"]prefix = "app"return = ["app","apple"]

Both app and apple begin with app, and lexicographic order places the shorter word first.

Example 2

dictionary = ["dog","cat","door"]prefix = "z"return = []

No word begins with z.

Example 3

dictionary = ["beta","alpha","alpine"]prefix = ""return = ["alpha","alpine","beta"]

The empty prefix matches every word, so all words are sorted.

Constraints

  • 0 <= dictionary.length <= 100000.
  • 1 <= dictionary[i].length <= 100.
  • 0 <= prefix.length <= 100.
  • All words are unique and all strings contain only lowercase English letters.

More Google problems

See Google hiring insights
public String[] wordsWithPrefix(String[] dictionary, String prefix) {
    // write your code here
}
dictionary["apple","app","bat"]
prefix"app"
expected["app", "apple"]
Checking account…