Find First Prefix-Matching Word
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in string processing and prefix-matching within arrays, testing the ability to identify the first occurrence and handle cases such as empty inputs or no matches.
Constraints
- 0 <= len(words) <= 100000
- 1 <= len(words[i]) <= 100
- 1 <= len(prefix) <= 100
- All strings may contain lowercase English letters
Examples
Input: (["a", "apple", "appz", "b"], "ap")
Expected Output: 1
Explanation: "apple" is the first word that starts with "ap".
Input: (["hello", "world"], "wor")
Expected Output: 1
Explanation: "world" starts with "wor", and it appears at index 1.
Input: (["dog", "cat", "fish"], "bir")
Expected Output: -1
Explanation: No word in the array starts with "bir".
Input: ([], "a")
Expected Output: -1
Explanation: The array is empty, so there cannot be any matching word.
Input: (["solo"], "solo")
Expected Output: 0
Explanation: The only word exactly matches the prefix, so the answer is index 0.
Hints
- You only need the first matching word, so scan the array from left to right.
- Use a direct prefix check on each word instead of comparing entire strings.