Blind 75
37 / 75Free practice

Design Add and Search Words Data Structure

Medium · Tries

Jump to code

Support adding lowercase words and searching patterns where a dot matches exactly one arbitrary letter. A search succeeds if any stored word matches the entire pattern.

Examples

Example 1

operations = ["addWord","addWord","addWord","search","search","search","search"]
words = ["bad","dad","mad","pad","bad",".ad","b.."]

Output: [false,true,true,true]

Example 2

operations = ["addWord","search","search"]
words = ["a",".","b"]

Output: [true,false]

Constraints

  • 1 <= word.length <= 20
  • word in addWord consists of lowercase English letters.
  • word in search consist of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 10,000 calls will be made to addWord and search.

Function contract

Implement WordDictionary with addWord(word) and search(pattern), where . matches exactly one letter. Each case starts a new dictionary. Only search calls produce output.

Need a hint?

A normal character chooses one edge; a wildcard may branch.

Real trie interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 10 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    "addWord",
    "addWord",
    "addWord",
    "search",
    "search",
    "search",
    "search"
  ],
  [
    "bad",
    "dad",
    "mad",
    "pad",
    "bad",
    ".ad",
    "b.."
  ]
]
Expected
[
  false,
  true,
  true,
  true
]
Case 2
Input
[
  [
    "addWord",
    "search",
    "search"
  ],
  [
    "a",
    ".",
    "b"
  ]
]
Expected
[
  true,
  false
]
Case 3
Input
[
  [
    "addWord",
    "addWord",
    "search"
  ],
  [
    "at",
    "bat",
    ".at"
  ]
]
Expected
[
  true
]
Case 4
Input
[
  [
    "addWord",
    "search",
    "search"
  ],
  [
    "abc",
    "a.c",
    "ab."
  ]
]
Expected
[
  true,
  true
]
Case 5
Input
[
  [
    "addWord",
    "search"
  ],
  [
    "abcd",
    "ab..e"
  ]
]
Expected
[
  false
]

Drafts are saved per language in this browser when storage is available.