Tutorialspoint
Problem
Solution
Submissions

Longest Common Prefix

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

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

A common prefix is a substring that occurs at the beginning of all strings in the array. The program should return the longest such substring.

Example 1
  • Input: strs = ["flower", "flow", "flight"]
  • Output: "fl"
  • Explanation:
    Step 1: Compare the first characters of all strings: 'f' is common.
    Step 2: Compare the second characters of all strings: 'l' is common.
    Step 3: Compare the third characters: 'o' in "flower" and "flow", but 'i' in "flight". Not common.
    Step 4: The longest common prefix is "fl".
Example 2
  • Input: strs = ["dog", "racecar", "car"]
  • Output: ""
  • Explanation:
    Step 1: Compare the first characters: 'd' in "dog", 'r' in "racecar", and 'c' in "car". Not common.
    Step 2: Since the first characters are different, there is no common prefix.
    Step 3: Return an empty string.
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), constant extra space
ArraysStringsHCL TechnologieseBay
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

  • Use a horizontal scanning approach: compare the first string with each of the other strings
  • Alternatively, use a vertical scanning approach: compare characters at the same position for all strings
  • You could also use a divide and conquer approach: find the common prefix of two halves recursively
  • Sort the array first to reduce the problem to finding the common prefix of just the first and last strings
  • Use binary search on the length of the prefix

Steps to solve by this approach:

 Step 1: If the array is empty, return an empty string.

 Step 2: Take the first string as the initial prefix.
 Step 3: Iterate through the rest of the strings in the array.
 Step 4: For each string, compare it with the current prefix character by character.
 Step 5: If a mismatch is found, update the prefix length to the position where the mismatch occurred.
 Step 6: If the prefix becomes empty at any point, return an empty string.
 Step 7: After comparing with all strings, return the substring of the first string up to the updated prefix length.

Submitted Code :