DEV Community

Debesh P.
Debesh P.

Posted on

14. Longest Common Prefix | LeetCode | Top Interview 150 | Coding Questions

Problem Link

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


Detailed Step-by-Step Explanation

https://leetcode.com/problems/longest-common-prefix/solutions/7441779/most-optimal-solution-beats-100-best-app-jxyq


leetcode 14


Solution

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

        int n = strs.length;

        if (strs == null || n == 0) {
            return "";
        }

        String prefix = strs[0];

        for (int i = 1; i < n; i++) {
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) {
                    return "";
                }
            }
        }

        return prefix;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)