0
0
Javascriptprogramming~5 mins

Stack overflow concept in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Stack overflow concept
O(n)
Understanding Time Complexity

When a program runs, it uses a special memory area called the call stack to keep track of function calls.

We want to understand how the number of function calls affects the program's running steps and memory use.

Scenario Under Consideration

Analyze the time complexity of the following recursive function that calls itself without a stopping condition.


function infiniteRecursion() {
  return infiniteRecursion();
}

infiniteRecursion();
    

This code calls the same function again and again without stopping, causing the call stack to grow endlessly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive function calls without end.
  • How many times: Infinite times until the program crashes.
How Execution Grows With Input

Each call adds a new layer to the call stack, growing step by step without stopping.

Input Size (n)Approx. Operations
1010 calls stacked
100100 calls stacked
10001000 calls stacked

Pattern observation: The number of calls grows directly with input, but here input is the depth of calls, which never ends.

Final Time Complexity

Time Complexity: O(n)

This means the number of steps grows directly with the number of recursive calls before the program crashes.

Common Mistake

[X] Wrong: "The recursion will stop on its own without a base case."

[OK] Correct: Without a stopping point, the function keeps calling itself forever, causing the program to crash with a stack overflow.

Interview Connect

Understanding how recursive calls use the call stack helps you write safe functions and avoid crashes in real projects.

Self-Check

"What if we add a base case to stop the recursion after a certain number of calls? How would the time complexity change?"