
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
Editorial
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. |
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