Sunday, December 5, 2021

Leetcode Easy: Longest Common Prefix

Tea-time snacking!


PROBLEM: https://leetcode.com/problems/longest-common-prefix/

TIME-COMPLEXITY: O(n*m) where n is the number of strings in input and m is the length of longest common prefix.


Sample Java Solution for tea-time snacking:


class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 1)
            return strs[0];
        
        int minLen = Integer.MAX_VALUE;
        for (int i=0; i<strs.length; i++) {
            minLen = Math.min(minLen, strs[i].length());
        }
        int lastPastIdx = minLen;
        outer:
        for (int i=0; i<minLen; i++) {
            char ch = strs[0].charAt(i);
            for (int str=0; str<strs.length; str++) {
                if (strs[str].charAt(i) != ch) {
                    lastPastIdx = i;
                    break outer;
                }
            }
        }
        return strs[0].substring(0, lastPastIdx);
    }
}

Enjoy and Happy Coding!!


Love! ❤️ 
#Lets #Code

Follow us on :

https://twitter.com/ThinkAlgorithms

No comments:

Post a Comment

Featured Post

interviewBit Medium: Palindrome Partitioning II

Problem Name:  Palindrome Partitioning II Problem Description : https://www.interviewbit.com/problems/palindrome-partitioning-ii/ Problem Ap...