0

I am a new learner and am unable to understand time complexity of if else statement. I have read online that time complexity for if-else is given in both max and min terms.

As per my understanding both max and min would be O(1), but some websites share otherwise and I am unable to understand it. Thank you.

Function copy(number)
  If number == 3
     console.log("number is 3");
  Else
     console.log("number is not 3");
Ali a
  • 13
  • 2
  • 1
    It is O(1). I have never heard of Time complexity of if else statements. You can speed up the process by having the most likely outcome be the first if-condition though. And it only matters if the condition is tested multiple times. If other web sites share otherwise, please share the source, and others can have a look at it as well – John Nov 25 '20 at 00:17
  • Does this answer your question? [Algorithm complexity: if/else under for loop](https://stackoverflow.com/questions/31164749/algorithm-complexity-if-else-under-for-loop) – John Nov 25 '20 at 00:17
  • @John These are the notes, I read from, it says, the complexity should be O(1) and O(n) [link] (http://pages.cs.wisc.edu/~vernon/cs367/notes/3.COMPLEXITY.html#:~:text=For%20example%2C%20if%20sequence%201,would%20be%20O(N).&text=Every%20time%20the%20outer%20loop,O(N%20*%20M)). – Ali a Nov 25 '20 at 00:23

1 Answers1

0

To make things clear, from the link you posted in the comment, it says:

if-then-else statements

if (condition) {
    sequence of statements 1
}
else {
    sequence of statements 2
}

Here, either sequence 1 will execute, or sequence 2 will execute. Therefore, the worst-case time is the slowest of the two possibilities: max(time(sequence 1), time(sequence 2)). For example, if sequence 1 is O(N) and sequence 2 is O(1) the worst-case time for the whole if-then-else statement would be O(N).

Which means that you account for the worst time complexity of one of the sequences, not the if-else-statement itself.

Let me give another example

function foo(){
  if (bar) {
    return 'bar'; // O(1)
  } else {
    return someArray.map((a) => a+1); // O(n)
  }
}

John
  • 10,165
  • 5
  • 55
  • 71