Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can anyone tell the reason why solution 1 is slower than solution 2

https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/

Solution 1(My code)** 3ms** runtime

class Solution {
    int countWords(String str){
        if(str.length() == 0) {
            System.out.println("0");
            return 0;
        }
        int count = 0;
        for(int i =0;i<str.length();i++){
                if(str.charAt(i) == ' '){
                    count++;
                }
        }
        return count+1;
    }
    
    public int mostWordsFound(String[] sentences) {
        int max_words = 0;
        for(int j =0;j<sentences.length;j++){
            int count = countWords(sentences[j]);
            if(count > max_words){
                    max_words = count;
            }
        }
        return max_words;
    }
}

Solution 2(Fastest solution according to leetcode through submissions tab) 1ms

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution {
    
    public static int countWords(String str) {
        if(str.length() == 0) {
            System.out.println("0");
            return 0;
        }
        int word = 0;
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == ' ') {
                word++;
            }
        }
        return (word+1);
    }
    
    public int mostWordsFound(String[] sentences) {
        
        int maxCount = 0;
        
        for(int i = 0; i < sentences.length; i++){
            int x = countWords(sentences[i]); 
            if(x > maxCount){
                maxCount = x;
            }
        }
        return maxCount;
    }
}

can anyone tell me why the solutions is faster than solution 1

>Solution :

Both codes are identical, variables names are just different.

The answer is : the execution time is too low to differenciate performance here. The server of the website can have different load at the moment you submit or whatever, a few milliseconds is not enough to differenciate performance.

Also when talking about benchmark, code should run at least 100 or 1000 time (depending of the time you have of course) to get an average

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading