简体   繁体   中英

Big-O notation of a method that calls a method of O(n)

public boolean equal(MyLinkedList a, MyLinkedList b) {
    String instanceA = encode(a);
    String instanceB = encode(b);
    return instanceA.equals(instanceB);
}

I was working on a project and looked at my code and realized I didn't know the time complexity rules of calling methods.

What would be the big-O notation of my equal method if the encode(String value) is of O(n)? Would it take into consideration the big-o notation of O(n) or would it be a simple O(1)?

It would be O(n) in the worst case. If you think about it, it boils down to estimating the time complexity of testing for equality, the encodings do not add additional complexity to the problem.

The complexity of verifying that two strings are equal is most of the times < O(n). For example, the equals method could simply compare the length of the strings before actually comparing the contents of the strings, which has constant complexity. If the strings are of equal length, then the equals method could traverse the whole strings, thus O(n).

In CS stackexchange, the subject is discussed in more detail. Check it out here: https://cs.stackexchange.com/questions/127899/what-is-the-expected-time-complexity-of-checking-equality-of-two-arbitrary-strin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM