
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)
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
- 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