Find Common Prefix Across Strings
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in string manipulation and array processing, focusing on identifying common prefixes, handling edge cases such as empty inputs, and reasoning about algorithmic time and space complexity.
Constraints
- 0 <= len(strs) <= 10000
- 0 <= len(strs[i]) <= 200
- All strings contain standard ASCII characters
- The prefix must begin at index 0 in every string
Examples
Input: (["flower", "flow", "flight"],)
Expected Output: "fl"
Explanation: All three strings start with "fl", but they differ at the next character.
Input: (["dog", "racecar", "car"],)
Expected Output: ""
Explanation: The first characters already differ, so there is no shared prefix.
Input: (["interview"],)
Expected Output: "interview"
Explanation: With only one string, that entire string is the common prefix.
Input: ([],)
Expected Output: ""
Explanation: An empty input array has no common prefix.
Input: (["", "abc", "ab"],)
Expected Output: ""
Explanation: Because one string is empty, the longest common prefix must be empty.
Input: (["prefix", "prefix", "prefixes"],)
Expected Output: "prefix"
Explanation: The shortest full shared starting sequence across all strings is "prefix".
Hints
- The common prefix can never be longer than the shortest string in the array.
- Try comparing characters at the same index across all strings. As an alternative idea, sort the strings and compare only the first and last.