Tutorialspoint
Problem
Solution
Submissions

Longest Common Prefix

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a Java program to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Example 1
  • Input: strs = ["flower", "flow", "flight"]
  • Output: "fl"
  • Explanation:
    • Step 1: Take the first string as the initial prefix candidate.
    • Step 2: Compare this prefix with each subsequent string in the array.
    • Step 3: If a string doesn't start with the current prefix, reduce the prefix length until it matches.
    • Step 4: After comparing with all strings, "fl" is the longest common prefix.
Example 2
  • Input: strs = ["dog", "racecar", "car"]
  • Output: ""
  • Explanation:
    • Step 1: Take "dog" as the initial prefix candidate.
    • Step 2: Compare with "racecar" - there is no common prefix since 'd' != 'r'.
    • Step 3: Since there's no common prefix at the very first position, the result is an empty string.
    • Step 4: Return an empty string as the longest common prefix.
Constraints
  • 1 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] consists of only lowercase English letters
  • Time Complexity: O(S) where S is the sum of all characters in all strings
  • Space Complexity: O(1)
StringsTech MahindraDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Start by assuming the first string is the common prefix
  • Iterate through the rest of the strings and compare with the current prefix
  • If a string doesn't start with the current prefix, shorten the prefix
  • Continue until you find a common prefix or determine there isn't one
  • You can implement this using either horizontal or vertical scanning approaches

Steps to solve by this approach:

 Step 1: Check if the input array is null or empty. If so, return an empty string.
 Step 2: Take the first string in the array as the initial prefix.
 Step 3: Iterate through the remaining strings in the array.
 Step 4: For each string, check if it starts with the current prefix.
 Step 5: If it doesn't, repeatedly shorten the prefix by removing the last character until the string starts with the prefix or the prefix becomes empty.
 Step 6: If the prefix becomes empty at any point, return an empty string as there is no common prefix.
 Step 7: After processing all strings, return the final prefix, which is the longest common prefix among all strings.

Submitted Code :