0
0
Goprogramming~5 mins

Switch statement in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch statement
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a switch statement changes as the input changes.

Specifically, we ask: does the number of cases affect how long the switch takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkNumber(n int) string {
    switch n {
    case 1:
        return "One"
    case 2:
        return "Two"
    case 3:
        return "Three"
    default:
        return "Other"
    }
}
    

This code checks a number and returns a word based on which case matches.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch compares the input value to each case until it finds a match.
  • How many times: At most, it checks each case once in order until a match is found.
How Execution Grows With Input

As the number of cases grows, the switch may need to check more cases before finding a match.

Number of Cases (n)Approx. Checks
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The checks grow roughly in direct proportion to the number of cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the matching case grows linearly with the number of cases.

Common Mistake

[X] Wrong: "A switch statement always runs in constant time no matter how many cases it has."

[OK] Correct: The switch checks cases one by one until it finds a match, so more cases can mean more checks and longer time.

Interview Connect

Understanding how switch statements scale helps you explain code efficiency clearly and shows you think about how programs behave as they grow.

Self-Check

"What if the switch used a map lookup instead of cases? How would the time complexity change?"