Longest Common Prefix
Algorithm/String
Intuition
The task is to find the longest common prefix shared by an array of strings. We can use a character-by-character comparison across all strings. By checking each character position in all strings, we can quickly find the prefix shared by all.
Approach
Below is the step-by-step breakdown of the approach:
- Initialize a Pointer:
- Start with a pointer
left
at 0, which will track the length of the common prefix.
- Start with a pointer
- Character-by-Character Comparison:
- For each character position
left
in the first string, check if it matches the character at the same position in all other strings usingArray.every()
. - If all strings have the same character at position
left
, incrementleft
to continue checking the next character. - If any string has a different character at position
left
, break out of the loop.
- For each character position
- Return the Result:
- Return the substring from the start up to
left
instrs[0]
, representing the longest common prefix.
- Return the substring from the start up to
Complexity
-
Time complexity: ,
n
is the number of strings, andm
is the length of the shortest string in the array. -
Space complexity: , no additional space is used aside from a few variables.