-2

Lets say we have a switch function, e.g.

switch (obj) {
  case 'Oranges':
    const { a, b } = obj;
    return a + b;
    break;

  case 'Apples':
    const { c, d } = obj;
    return c + d;
    break;

  case 'Bananas':
    const { e, f } = obj;
    return e + f;
    break;

  default:
    return obj;
}

Question: what will be the time complexity of that function?

Question2: what if we raise the number of cases here to e.g. 100? Will complexity raise aswell? If so - how many times?

Patrickkx
  • 1,740
  • 7
  • 31
  • 60
  • What complexity? Time complexity? Space complexity? Complexity is a way to express how efficient is a function, it doesn't change based on the parameters it receives – iagowp Nov 27 '18 at 17:10

1 Answers1

0

The time-complexity is O(n), regardless of the number of inputs. If you start putting for loops into your cases, then that could change it.

Here’s an example of how it would be O(n^2), meaning that the amount of input will increase the time-complexity exponentially. In this case it’s based on string length, causing 12 loops on a 3 letter word.

switch(foo){
  case 'bar':
    for (let i = 0; i < foo.length; i++){
      for (let j = 0; j < foo.length; j++){
        console.log(i, j);
      }
    }
}

That doesn’t necessarily mean that nested for loops automatically make it O(n^2). The following example is actually O(1) because the input has no effect on how long it takes. This will always be 210 loops, regardless:

switch(foo){
  case 'bar':
    for (let i = 0; i < 10; i++){
      for (let j = 0; j < 20; j++){
        console.log(i, j);
      }
    }
}
AnonymousSB
  • 3,516
  • 10
  • 28