Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 04

Asymptotic Analysis & Complexity

3 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Asymptotic analysis measures how running time and memory grow with input size n, ignoring machine-specific constants.

Big-O (upper bound), Omega (lower bound) and Theta (tight bound) are the language of every algorithm comparison; recursion adds call-stack space.

GATE and interviews ask you to derive complexity of a snippet in under a minute.

A wrong bound makes every later design choice (sort, DS, DP) wrong.

Choosing between O(n log n) and O(n^2) approaches, predicting whether n = 10^5 or 10^7 will pass a time limit (about 10^8 simple ops/sec), and sizing memory for recursion.

1

Big-O, Big-Omega & Big-Theta Notation

f(n)=O(g(n)) if there exist c>0, n0 such that f(n) <= c*g(n) for all n>=n0 (upper bound). f(n)=Omega(g(n)) if f(n) >= c*g(n) (lower bound). f(n)=Theta(g(n)) if both hold (tight bound). Little-o and little-omega are strict (non-tight) versions.

In short: Big-O says "at most this fast-growing", Omega says "at least", Theta says "exactly this order".

Think about it

Hardware changes constants; growth rate is the machine-independent comparison needed to choose algorithms.

Constants and lower-order terms are dropped: 3n^2+10n+7 = Theta(n^2).

Big-O is an upper bound, not necessarily tight: n = O(n^2) is true but useless.

Best/worst/average case are separate functions of n; each can have its own O/Omega/Theta.

Saying "quick sort is Omega(n log n)" is the best case; worst case is O(n^2).

Logs of different bases differ by a constant, so O(log2 n) = O(log10 n).

But 2^(2n) is NOT O(2^n) because the exponent constant matters.

Key points

  • Upper bound: Big-O: growth never exceeds c*g(n) beyond n0.
  • Tight bound: Theta: sandwiched between c1*g(n) and c2*g(n).
  • Dominant term: Highest-order term decides the class.
  • Order: 1 < log n < sqrt(n) < n < n log n < n^2 < n^3 < 2^n < n! < n^n.
  • log(n!) = Theta(n log n) (Stirling). Sum of 1..n = Theta(n^2). Sum of 1/i for i=1..n = Theta(log n).
  • If f=O(g) and g=O(h) then f=O(h) (transitive). f=Theta(g) iff g=Theta(f) (symmetric).

Example

Code
Constant dropping:
# 5n^2 + 20n + 100  ->  Theta(n^2)
# Proof sketch: for n >= 10, 5n^2 <= f(n) <= 7n^2  (c1=5, c2=7, n0=10)
def f(n):
    return 5 * n * n + 20 * n + 100
2

Calculating Time Complexity

Time complexity counts elementary operations as a function of input size. Sequential blocks add (take the max), nested independent loops multiply, loops with multiplicative/divisive steps give logarithms, and recursive algorithms yield recurrences solved by substitution, recursion tree, or the Master theorem.

In short: Count how many times the innermost statement runs as n grows.

Input Size (n) → Time (T) ↑ O(1) O(log n) O(n) O(n log n) O(n²) O(2ⁿ)
Asymptotic Analysis & Complexity

Think about it

Deriving this by hand is a direct GATE question type and the first interview follow-up after any solution.

Rules: (1) for i in range(n): O(n).

(2) Nested independent loops: O(n*m).

(3) Dependent inner loop j<i gives n(n-1)/2 = O(n^2).

(4) i *= 2 or i //= 2 gives O(log n).

(5) Outer n times with inner log n gives O(n log n).

(6) Inner loop where j runs n/i times gives harmonic sum n(1+1/2+...

) = O(n log n).

(7) i=1; while i*i<=n: O(sqrt n).

Master theorem for T(n)=aT(n/b)+Theta(n^d): if d > log_b a then Theta(n^d); if d = log_b a then Theta(n^d log n); if d < log_b a then Theta(n^(log_b a)).

Examples

  • 1merge sort a=2,b=2,d=1 gives n log n
  • 2binary search a=1,b=2,d=0 gives log n
  • 3T(n)=2T(n-1)+1 is Theta(2^n)
  • 4T(n)=T(n-1)+n is Theta(n^2)
  • 5T(n)=T(n-1)+T(n-2) (naive Fibonacci) is Theta(phi^n), upper bound O(2^n)

Key points

  • Recurrence: Equation expressing T(n) via smaller inputs, e.g. T(n)=2T(n/2)+n.
  • Master theorem: Closed form for T(n)=aT(n/b)+f(n), a>=1, b>1.
  • Amortized cost: Average per operation over a sequence, e.g. dynamic array append is O(1) amortized.
  • Two sequential loops of n and m: O(n+m), not O(n*m).
  • Input-dependent: loop to sqrt(n) on a number n is O(sqrt n) but the input size in bits is log n (pseudo-polynomial issue).
  • String concatenation s += c in a loop is O(n^2) in languages with immutable strings.

Example

Code
Four common patterns:
def a(n):                 # O(n log n)
    for i in range(n):
        j = 1
        while j < n:
            j *= 2

def b(n):                 # O(n^2): dependent loop, n(n-1)/2
    for i in range(n):
        for j in range(i):
            pass

def c(n):                 # O(n log n): harmonic
    for i in range(1, n + 1):
        for j in range(0, n, i):
            pass

def d(n):                 # O(sqrt n)
    i = 1
    while i * i <= n:
        i += 1
3

Space Complexity & Call Stack

Space complexity is the memory an algorithm needs as a function of n. Auxiliary space is the extra memory beyond the input; total space = input + auxiliary. Each recursive call adds a stack frame, so recursion depth d contributes O(d) space.

In short: How much extra memory you use, including the hidden memory taken by recursion.

Recursion call stack: each call waits for the next to return
Recursion call stack: each call waits for the next to return

Think about it

Memory limits and stack overflow crashes are real failure modes; GATE asks stack depth of recursive functions directly.

Iterative sum: O(1).

Recursive sum(n) = n + sum(n-1): O(n) stack.

Binary search recursive: O(log n) stack, iterative O(1).

Merge sort: O(n) auxiliary for the merge buffer plus O(log n) stack.

Quick sort: O(log n) expected stack, O(n) worst case unless you recurse on the smaller half first (guarantees O(log n)).

DFS on a graph: O(V) stack worst case.

Memoized Fibonacci: O(n) table + O(n) stack.

In-place means O(1) auxiliary (reverse an array with two pointers).

Python default recursion limit is about 1000 frames, so deep recursion on n=10^5 raises RecursionError; convert to iteration or an explicit stack.

Key points

  • Auxiliary space: Extra space beyond input storage.
  • Stack frame: Per-call record of locals, parameters, return address.
  • In-place: Uses O(1) extra space (input overwritten/modified).
  • Tail recursion: Recursive call is the last action; can be optimized to a loop in some languages (not CPython/Java).

Example

Code
Recursion vs iteration space:
def sum_rec(n):            # time O(n), stack O(n)
    if n == 0:
        return 0
    return n + sum_rec(n - 1)

def sum_iter(n):           # time O(n), space O(1)
    total = 0
    for i in range(1, n + 1):
        total += i
    return total

def fib_naive(n):          # time O(2^n), stack depth O(n)
    return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)

Solved examples

Example 01 · Basic

Find time complexity: for i in range(n): for j in range(i, n): work()

Given Data:
    Required To Find:

    Big-O

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Inner loop runs n-i times for each i.
    Step 2: Total = n + (n-1) + ... + 1 = n(n+1)/2.
    Step 3: Drop constants and lower terms.
    Final Answer: Theta(n^2)

    Approach note: Triangular sums always give n^2 / 2.

    Example 02 · Intermediate

    Solve T(n) = 2T(n/2) + n log n using Master-like reasoning.

    Given Data:
      Required To Find:

      Closed form

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: a=2, b=2, so n^(log_b a) = n.
      Step 2: f(n)=n log n is larger than n by a log factor (not polynomially larger), so basic cases do not apply.
      Step 3: Extended case: f(n)=Theta(n^(log_b a) log^k n) with k>=0 gives Theta(n^(log_b a) log^(k+1) n).
      Step 4: Here k=1.
      Final Answer: Theta(n log^2 n)

      Approach note: Recursion tree: each of log n levels costs n log n at the top and about n*log(n/2^i) below, summing to n log^2 n.

      Example 03 · Advanced

      Stack space of: def f(n): return 0 if n <= 1 else f(n // 2) + f(n // 2)

      Given Data:
        Required To Find:

        Time and stack depth

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Recurrence T(n) = 2T(n/2) + 1 gives Theta(n) calls (leaf count = n).
        Step 2: Depth is the longest root-to-leaf path = log2 n.
        Step 3: Only one path is live on the stack at a time.
        Final Answer: Time Theta(n), stack space Theta(log n)

        Approach note: Stack space = depth, not total number of calls.

        Example 04 · Intermediate

        for (i=n; i>0; i/=2) for (j=1; j<=n; j++) stmt;. What is the time complexity?

        Given Data:
          Required To Find:

          Big-O

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Outer loop runs Theta(log n) times (halving)
          Step 2: Inner loop always runs n times
          Step 3: Total Theta(n log n)
          Final Answer: Theta(n log n)

          Approach note: Multiply independent nested loop costs.

          Real-world applications

          DSA

          Using Asymptotic Analysis & Complexity in real projects

          Choosing between O(n log n) and O(n^2) approaches, predicting whether n = 10^5 or 10^7 will pass a time limit (about 10^8 simple ops/sec), and sizing memory for recursion.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Big-O always means the worst case.

          Why this is wrong: Big-O is a mathematical upper bound on any function; it can describe best, average or worst case.

          ✅ Verified Truth: Say "worst-case time is O(n^2)" or "best case is Omega(n)". Theta applies when upper and lower match.

          ⚠️ Exam Tip: In GATE, if a case is not specified, assume worst case for the algorithm.

          ❌ Myth: O(n) is always faster than O(n^2) for any input.

          Why this is wrong: Asymptotic notation hides constants and holds only for n beyond n0; 1000n loses to n^2 for n<1000.

          ✅ Verified Truth: Growth rate wins for large n; for tiny n insertion sort beats merge sort, which is why hybrid sorts exist.

          ⚠️ Exam Tip: State the n0 caveat if asked to compare real performance.

          ❌ Myth: Recursive code uses O(1) space if it has no arrays.

          Why this is wrong: Every pending call holds a stack frame.

          ✅ Verified Truth: Space = max recursion depth times frame size.

          ⚠️ Exam Tip: Always add stack depth to auxiliary space.

          Revision notes

          Asymptotic analysis measures how running time and memory grow with input size n, ignoring machine-specific constants. Big-O (upper bound), Omega (lower bound) and Theta (tight bound) are the language of every algorithm comparison; recursion adds call-stack space.

          High-Yield Quick Revision Points

          1. Order: 1 < log n < sqrt n < n < n log n < n^2 < n^3 < 2^n < n! < n^n
          2. Theta = O and Omega; drop constants and lower terms
          3. Sequential: add (max); nested: multiply; halving/doubling: log
          4. Master: compare n^(log_b a) with f(n)
          5. Space = auxiliary + recursion depth; naive Fibonacci time 2^n, stack n

          Practice questions

          Question 1 · MCQ (GATE)

          Complexity of: i = n; while i > 1: i = i // 2 ?

          Question 2 · MCQ (GATE)

          T(n) = T(n-1) + n has solution:

          Question 3 · MCQ (GATE)

          Which is true? 2^(n+1) = ? and 2^(2n) = ?

          Question 4 · MCQ (GATE)

          Master theorem: T(n) = 4T(n/2) + n gives:

          Question 5 · MCQ (Interview)

          Auxiliary space of recursive binary search on n elements: