Predict the output
What does this print?
words = ["car", "card", "care", "cat", "dog"]
three = sum(w.startswith("car") for w in words)
print(three, sum(w.startswith("ca") for w in words))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3 4
Right: car, card and care; then cat as well.
The scan is O(total letters) per question; a trie answers the same question in O(prefix length) after one build.
Why not the others?
- B 1 4. startswith counts every word with that start, not just exact matches.
- C 3 3. cat also starts with 'ca'.
Steps come from running the Python solution.
Text version
prefix 'ca':
Trie (✓ = word ends here):
- root
- c
- a
- r ✓
- d ✓
- e ✓
- t ✓
- r ✓
- a
- d
- o
- g ✓
- o
- c
- Walk to root
- Walk to c
- Walk to a
Result: 4
prefix 'car':
Trie (✓ = word ends here):
- root
- c
- a
- r ✓
- d ✓
- e ✓
- t ✓
- r ✓
- a
- d
- o
- g ✓
- o
- c
- Walk to root
- Walk to c
- Walk to a
- Walk to r (word ends here)
Result: 3