Longest Common Prefix

Hello friends today I have solved the problem of longest common prefix on the leetcode which is based on the topic strings. In this problem as give below we have to solve the longest common prefix between strings that are present in arrays so first we sort the array using Arrays .sort() method because strings are sorted by alphabetical manner, hence we can compare first and list string only. Initialize the string s1 and s2 to the first and last strings of arrays. Iterate the loop until the length of s1 and s2 note that you are using and operator and then check the characters one by one by incrementing i if condition becomes not true then get out of loop using break statement and return the substring of any of s1 or s2 till the incremented i using substring method.

Problem : Write a function 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"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200

  • 0 <= strs[i].length <= 200

  • strs[i] consists of only lowercase English letters.

Solution:

class Solution {
    public String longestCommonPrefix(String[] strs) {

        Arrays.sort(strs);
        String s1 = strs[0];
        String s2 = strs[strs.length-1];

        int i = 0;

        while(i<s1.length() && i<s2.length())
        {
            if(s1.charAt(i) == s2.charAt(i))
                i++;
            else
                break;
        }

        return s1.substring(0, i);

    }
}

Did you find this article valuable?

Support DHANRAJ NIKAM by becoming a sponsor. Any amount is appreciated!