Bucky
Bucky

Reputation: 127

What is the time complexity of String compareTo function in Java?

I have a String array String strs[] = {"flower", "flow", "flight"};.

I want to find the smallest and largest lexicographically string from the array. This is what I did:

String first = strs[0], last = strs[0];

for (String str : strs) {
    if (str.compareTo(first) < 0)
        first = str;
    if (str.compareTo(last) > 0)
        last = str;
}

System.out.println("First : " + first + " Last : " + last);

Now I want find the time complexity of this algorithm. I know it will be n * (time complexity of compareTo()). So, what is the time complexity of this algorithm?

Upvotes: 2

Views: 2485

Answers (1)

Esotopo21
Esotopo21

Reputation: 412

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

This is the implementation of String#compareTo which leads to consider the complexity, in the worst case scenario (len1 = len2 = n), as O(n)

So the complexity of your algorithm would be O(nm) with n = number of strings in your array and m the max length among those strings lenghts.

Upvotes: 4

Related Questions