Why are Java solutions are slower than other languages??


  • 0
    H

    Hi, the following my solution is divide-conquer and recursive as well. The interesting thing I realized is that all the Java solutions took 300+ms to finish but others like c/c++ and even python only took less than 100ms. I was wondering is it something about this platform, language or the solution itself? thank you!

    public class Solution {
            public String longestCommonPrefix(String[] strs) {
                if (strs == null || strs.length == 0) return "";
                return helper(strs, 0, strs.length - 1);       
            }
            
            private String helper(String[] strs, int l, int r) {
                if (l == r) return strs[l];
                if (l == r -1) {
                    return findPrefixFor2(strs[l], strs[r]);
                }
                
                int mid = (l+r) / 2;
                String lHalfPrefix = helper(strs, l, mid);
                String rHalfPrefix = helper(strs, mid+1, r);
                
                return findPrefixFor2(lHalfPrefix, rHalfPrefix);
            }
            private String findPrefixFor2(String l, String r) {
                if (l == "" || r == "") return "";
                
                int p = 0;
                int prefix = 0;
                while(p < l.length() && p < r.length()) {
                    if (l.charAt(p) == r.charAt(p)) {
                        prefix++;
                        p++;
                    } else {
                        break;
                    }
                }
                return l.substring(0, prefix);
            }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.