Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O: O(n) of compareStrings

The algorithm below compares two strings, returns 0 if they are the same and otherwise if not.

Is the running time O(n) since the for loop depends on n, the min length of two strings?

int compareStrings(String s1, String s2) {
    int n = min(s1.length(), s2.length());
        for (int i=0; i<n; i++) {
        if (s1.charAt(i) != s2.charAt(i)) {
            return s1.charAt(i) – s2.charAt(i);
        }
    }
    return s1.length() – s2.length();
}
like image 611
CarolineRudolph Avatar asked Dec 01 '25 00:12

CarolineRudolph


1 Answers

Yes, it is O(n).

@LouisWasserman: If I use a merge sort algorithm with the compareStrings method, will the best case be (log n) time if there's only 1 string to compare? I know merge sort has a worst case of O(n log n)

You're dealing with two different n's there: one for the length of the strings, and one for the number of strings you're sorting. If the strings you're sorting are of length m, then the merge sort as a whole will take O(nm log n) time. – Louis Wasserman

like image 96
CarolineRudolph Avatar answered Dec 02 '25 12:12

CarolineRudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!