Search code examples
javaif-statementcomplexity-theory

If statement and O(1) complexity


If there is an if else condition and if consists of 2 lines and else of 1 or generally the one has one more line, is the program O(1) ?

edit1: The following example is about linked lists.

For example:

    public String smth() throws NoSuchElementException{
        if (size!=0) {  
            Object n = tail.item;
            
            if (size!=1) {
                tail = tail.prev;
                tail.next = null;
                
            }
            else{       
                head.prev = null;       
                head = head.next;
                tail = tail.prev;
            
                
            }   
            
            this.size = this.size - 1;
            return n.toString();
        }else {
            throw new NoSuchElementException();
        }
    }

edit2:

Thank you all for your suggestions. The toString() is the default one; I didn't create (override) a one one.


Solution

  • While both metrics tend to be correlated with overall performance (because programs that "do more things" will typically take longer to run), lines of code and computational complexity don't measure the same thing.

    To clarify, to say that a program's complexity is O(1) simply means that it takes a constant number of steps regardless of the size of the input. Adding more lines of code will not, in and of itself, change the computational complexity (unless one of those lines is doing something that's more complex than O(1)).

    Put another way, 30 O(1) operations, 50 O(1) operations, and 100 O(1) operations are all still O(1). However, 99 O(1) operations and an O(n) operation is O(n).

    That being said: please do be sure to check the n.toString() line. I don't have a lot of insight as to what that actually contains, but it might be O(n) depending on how it's implemented. If that line is O(n), it would make the entire method O(n); otherwise, unless I'm missing something, I don't see anything there that would make this anything other than O(1). (Also, I'll freely admit that I don't recall the computational complexity of throwing exceptions in Java, that's something that I'd have to do more research on).