Longest Common Prefix of Two Strings in Java (Time Complexity: O(n))


Given two strings s1 and s2, return their longest common prefix

Example 1:

Input:  s1 = "hello", s2 = "help"
Output:  "hel"

Example 2:

Input:  s1 = "Andy", s2 = "Mircea"
Output:  ""

Example 3:

Input:  s1 = "AlgoCademy", s2 = "Algo"
Output:  "Algo"

Understanding the Problem

The core challenge of this problem is to find the longest common prefix between two given strings. This is a common problem in string manipulation and has applications in text processing, DNA sequence analysis, and more. A potential pitfall is assuming that the common prefix will always be non-empty, which is not the case as shown in Example 2.

Approach

To solve this problem, we can start by comparing characters of both strings one by one from the beginning until we find a mismatch or reach the end of one of the strings. This approach ensures that we find the longest common prefix efficiently.

Naive Solution

A naive solution would involve nested loops to compare each character of the first string with each character of the second string. However, this is not optimal and has a time complexity of O(n*m), where n and m are the lengths of the two strings.

Optimized Solution

An optimized solution involves a single loop to compare characters of both strings until a mismatch is found. This approach has a time complexity of O(n), where n is the length of the shorter string.

Algorithm

Here is a step-by-step breakdown of the optimized algorithm:

  1. Initialize an index variable to 0.
  2. Loop through both strings until the characters at the current index are the same and the index is less than the length of both strings.
  3. Increment the index variable.
  4. Return the substring of the first string from the beginning to the current index.

Code Implementation

public class LongestCommonPrefix {
    public static String longestCommonPrefix(String s1, String s2) {
        int minLength = Math.min(s1.length(), s2.length());
        int i = 0;
        
        // Loop until characters match and within the bounds of the shorter string
        while (i < minLength && s1.charAt(i) == s2.charAt(i)) {
            i++;
        }
        
        // Return the common prefix
        return s1.substring(0, i);
    }

    public static void main(String[] args) {
        // Test cases
        System.out.println(longestCommonPrefix("hello", "help")); // Output: "hel"
        System.out.println(longestCommonPrefix("Andy", "Mircea")); // Output: ""
        System.out.println(longestCommonPrefix("AlgoCademy", "Algo")); // Output: "Algo"
    }
}

Complexity Analysis

The time complexity of the optimized solution is O(n), where n is the length of the shorter string. The space complexity is O(1) as we are using a constant amount of extra space.

Edge Cases

Potential edge cases include:

  • One or both strings are empty: The output should be an empty string.
  • No common prefix: The output should be an empty string.
  • One string is a prefix of the other: The output should be the shorter string.

Examples:

Input:  s1 = "", s2 = "hello"
Output:  ""

Input:  s1 = "hello", s2 = ""
Output:  ""

Input:  s1 = "prefix", s2 = "pre"
Output:  "pre"

Testing

To test the solution comprehensively, consider the following test cases:

  • Both strings are empty.
  • One string is empty.
  • No common prefix.
  • One string is a prefix of the other.
  • Both strings are identical.

Using a testing framework like JUnit can help automate and validate these test cases.

Thinking and Problem-Solving Tips

When approaching string problems, always consider edge cases and constraints. Breaking down the problem into smaller steps and thinking about the simplest solution first can help in deriving an optimized solution. Practice similar problems to improve your problem-solving skills.

Conclusion

Understanding and solving the longest common prefix problem is crucial for various applications in text processing and other fields. By practicing and exploring different approaches, you can enhance your problem-solving skills and tackle more complex problems effectively.

Additional Resources