The goal is to find the longest portion at the beginning of all strings that is identical. This is called the longest common prefix.
Imagine writing all the words in a vertical column and comparing them letter by letter, from top to bottom. We go through the characters of the first string one at a time and check whether the same character appears in the same position in all other strings.
Let’s explore the different cases you might encounter:
- Normal case: If the strings have a common start — like ["flower", "flow", "flight"] — we start comparing character by character. At position 0, all start with 'f'. At position 1, all have 'l'. At position 2, 'flower' and 'flow' have 'o', but 'flight' has 'i'. So the common prefix ends just before the mismatch:
"fl"
.
- No match at all: If the first characters don’t even match — like in ["dog", "racecar", "car"] — there is no common prefix, and we return
""
.
- Single string: If there’s only one string, like ["a"], that string itself is the longest common prefix.
- Some string is empty: If even one of the strings is empty — like ["abc", ""] — there can’t be a common prefix. Return
""
.
- Empty array: If the input array has no strings at all — return
""
right away.
- All strings are identical: In cases like ["apple", "apple", "apple"], all characters will match and the whole string is the common prefix.
This method is known as vertical scanning because it checks each character vertically across all strings at a particular index. It stops as soon as it finds a mismatch, making it efficient and easy to understand.
Edge cases like empty arrays or strings are simple to handle with early checks. This way, we avoid unnecessary comparisons and ensure correctness in all scenarios.