101 Logo
onenoughtone

Solution Approach

Solution Overview

There are 2 main approaches to solve this problem:

  1. Horizontal Scanning - Complex approach
  2. Vertical Scanning - Complex approach

Approach 1: Horizontal Scanning

In this approach, we start with the first string as our assumed longest common prefix (LCP). Then, we iteratively scan through the remaining strings, reducing the LCP as needed until we've processed all strings or the LCP becomes empty.

Initial LCP = "ACGTGGT"

A
C
G
T
G
G
T

Compare with "ACGTCAT"

A
C
G
T
C
A
T

Updated LCP = "ACGT"

Compare with "ACGTTGA"

A
C
G
T
T
G
A

Final LCP = "ACGT"

Algorithm:

  1. Start with the first string as the initial longest common prefix (LCP).
  2. Iterate through the remaining strings in the array.
  3. For each string, compare it with the current LCP and update the LCP to be the common prefix between them.
  4. If at any point the LCP becomes an empty string, we can stop and return it.
  5. After processing all strings, return the final LCP.

Time Complexity:

O(S)

where S is the sum of all characters in all strings. In the worst case, we might need to compare all characters of all strings.

Space Complexity:

O(1)

We only need a constant amount of extra space for the LCP string (not counting the input and output).

Approach 2: Vertical Scanning

In this approach, we compare characters at the same position across all strings. We start from the first character and move forward until we find a mismatch or reach the end of a string.

Compare first characters

A
C
G
T
G
G
T
A
C
G
T
C
A
T
A
C
G
T
T
G
A

All match, LCP = "A"

Compare second characters

A
C
G
T
G
G
T
A
C
G
T
C
A
T
A
C
G
T
T
G
A

All match, LCP = "AC"

Continue until mismatch at position 5

Final LCP = "ACGT"

Algorithm:

  1. Iterate through the characters of the first string.
  2. For each character position, check if this character exists in all other strings at the same position.
  3. If a mismatch is found or we reach the end of any string, return the prefix found so far.
  4. Otherwise, add the character to our result and continue.

Time Complexity:

O(S)

where S is the sum of all characters in all strings. In the worst case, we might need to compare all characters of all strings.

Space Complexity:

O(1)

We only need a constant amount of extra space for the result string.

Pseudocode

solution.pseudo
1
2
3
4
5
6
7
8
9
10
11
12
13
function longestCommonPrefix(strs):
if strs is empty:
return ""
prefix = strs[0]
for i from 1 to strs.length - 1:
while strs[i].indexOf(prefix) != 0:
prefix = prefix.substring(0, prefix.length - 1)
if prefix is empty:
return ""
return prefix
ProblemSolutionCode
101 Logo
onenoughtone