Competitive Coding

Unit 1: Behaviour Analysis

Master the art of analysing algorithm behaviour โ€” understand Big-O notation, time & space complexity, and learn to pick the right algorithm for every competitive coding problem.

โฑ๏ธ 5 hrs theory + 3 hrs practice  |  ๐Ÿ’ฐ Earning Potential: โ‚น5Kโ€“โ‚น20K/month  |  ๐Ÿ“ 30 MCQs (Bloom's Mapped)

๐Ÿ’ผ Jobs this unlocks: SDE Intern (โ‚น3โ€“6 LPA)  |  Competitive Programmer (โ‚น5โ€“15 LPA)  |  Algorithm Engineer (โ‚น8โ€“20 LPA)

Section A

Opening Hook โ€” The Speed That Separates Good From Great

โšก Why Does Your Code Take 10 Seconds While Theirs Takes 10 Milliseconds?

When you search for a restaurant on Zomato, the app searches through 10 lakh+ restaurants and returns results in milliseconds. How? They use hashing (O(1) lookup), not a linear scan (O(n)). That single design choice makes the difference between a 0.001-second response and a 10-second freeze.

Google indexes 10 billion+ web pages and returns results in 0.5 seconds. Behind the scenes, algorithms like PageRank, inverted indices, and distributed sorting work together โ€” each carefully analysed for time and space complexity.

In competitive programming, you have 1โ€“2 seconds to process up to 10โถ inputs. A brute-force O(nยฒ) solution that works for n=1000 will TLE (Time Limit Exceeded) for n=10โต. Understanding algorithm behaviour isn't optional โ€” it's the single most important skill that separates a Codeforces Specialist from a Grandmaster.

This chapter teaches you to think like an algorithm analyst. You'll learn to look at any code and instantly know: "This is O(n log n), it'll pass for nโ‰ค10โต" or "This is O(nยฒ), I need to optimise."

๐Ÿข Google๐Ÿข Amazon๐Ÿ• Zomato๐Ÿ›’ Flipkart๐Ÿ’ป Codeforces๐Ÿ’ป LeetCode
India has the 2nd largest competitive programming community in the world (after China). Over 500,000 Indians are active on Codeforces and LeetCode. Indian coders like Gennady Korotkevich's rival Anudeep Nekkanti and ACM ICPC World Finalists from IITs regularly crack top positions. Companies like Google, Amazon, and Microsoft hire directly from competitive coding platforms โ€” and the first filter is always algorithmic complexity analysis.
Section B

Learning Outcomes โ€” Bloom's Taxonomy Mapped

Bloom's Level#Learning Outcome
๐Ÿ”ต Remember1Define Big-O, Big-ฮฉ, and Big-ฮ˜ notation and state their mathematical definitions
๐Ÿ”ต Remember2List the 7 common complexity classes: O(1), O(log n), O(n), O(n log n), O(nยฒ), O(2โฟ), O(n!)
๐ŸŸข Understand3Explain why worst-case analysis is preferred over average-case in competitive programming
๐ŸŸข Understand4Describe the time-space tradeoff with real examples (HashMap vs binary search)
๐ŸŸก Apply5Calculate time complexity of given code snippets involving loops, recursion, and nested structures
๐ŸŸก Apply6Apply Big-O simplification rules (drop constants, drop lower-order terms) to mathematical expressions
๐ŸŸ  Analyze7Compare the efficiency of brute-force vs optimised algorithms for the same problem
๐ŸŸ  Analyze8Analyze nested loop patterns, divide-and-conquer recurrences, and sliding window techniques for complexity
๐Ÿ”ด Evaluate9Judge which algorithm/data structure is best suited for a problem given its constraints (n โ‰ค 10โต vs n โ‰ค 10ยณ)
๐Ÿ”ด Evaluate10Evaluate time-space tradeoff decisions and justify when to use extra memory for faster execution
๐ŸŸฃ Create11Design optimised solutions by selecting appropriate algorithmic patterns based on constraint analysis
๐ŸŸฃ Create12Write formal complexity analysis reports for competitive programming solutions with proof of correctness
Section C

Concept Explanation โ€” Behaviour Analysis from Scratch

1. Introduction to Limits and Behaviour of Logic

Why does one algorithm solve a problem in 0.01 seconds while another takes 10 seconds? The answer lies in how the number of operations grows as input size increases. This growth behaviour is what we call algorithmic complexity.

๐Ÿ”ฌ The Core Question: Input Size vs Execution Time

Definition:

Algorithm behaviour analysis is the study of how an algorithm's resource consumption (time and space) changes as the input size (n) grows towards infinity.

Key Insight:

We don't measure time in seconds (hardware-dependent). Instead, we count the number of fundamental operations as a function of input size n.

Example:

Linear Search checks each element one by one โ€” for n elements, it does at most n comparisons. Binary Search halves the search space each step โ€” for n elements, it does at most logโ‚‚(n) comparisons. For n = 1,000,000: linear search = 1,000,000 operations. Binary search = 20 operations. That's a 50,000ร— difference!

Linear Search โ€” O(n)

C++
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {      // Runs n times in worst case
        if (arr[i] == target) return i;  // 1 comparison per iteration
    }
    return -1;
}

Binary Search โ€” O(log n)

Python
def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:               # Runs logโ‚‚(n) times
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            lo = mid + 1           # Eliminate left half
        else:
            hi = mid - 1           # Eliminate right half
    return -1

2. Understanding Taxonomy in Worst Case

Every algorithm has three possible behaviours depending on the input:

CaseDefinitionLinear Search Example
Best CaseMinimum operations โ€” the most favourable inputTarget is at index 0 โ†’ O(1)
Average CaseExpected operations over all possible inputsTarget is somewhere in the middle โ†’ O(n/2) = O(n)
Worst CaseMaximum operations โ€” the most unfavourable inputTarget is the last element or absent โ†’ O(n)

Why do we focus on worst case? In competitive programming, the judge tests your code against the hardest possible input. If your worst case exceeds the time limit, you get TLE โ€” even if your average case is fast. Worst-case analysis gives you a guarantee.

Students often confuse O(n/2) with being "better" than O(n). In Big-O notation, O(n/2) = O(n) because we drop constants. The constant factor 1/2 doesn't change the growth rate. Always simplify before answering!
Big-O is like Swiggy's delivery estimate. Swiggy says "Delivery in 30โ€“45 minutes." The 45 minutes is the worst case โ€” that's Big-O. The 30 minutes is the best case โ€” that's Big-ฮฉ. You plan your dinner based on the worst case, not the best case. Same with algorithms.

3. Analysing Effectiveness and Efficiency

An algorithm must be correct (effective) AND fast (efficient). These are independent properties:

PropertyQuestionExample
Effectiveness (Correctness)Does it produce the right answer?Bubble Sort correctly sorts any array โœ…
EfficiencyDoes it do so within resource limits?Bubble Sort is O(nยฒ) โ€” too slow for n > 10โด โŒ

A correct but slow algorithm is useless in competitive coding. Bubble Sort correctly sorts an array, but for n = 10โต, it performs 10ยนโฐ operations โ€” that's ~10 seconds on a modern CPU. Merge Sort gives the same correct result in O(n log n) = ~1.7 million operations โ€” under 0.01 seconds.

Students submit the first working solution without checking complexity. "It works on the sample test cases!" โ€” Yes, but sample cases have n โ‰ค 10. The actual judge tests n = 10โต. Always calculate your complexity BEFORE submitting. If it's worse than what the constraints allow, optimise first.

4. Measuring Time Complexity

Big-O Notation describes the upper bound of an algorithm's growth rate. Formally: f(n) = O(g(n)) if there exist constants c > 0 and nโ‚€ such that f(n) โ‰ค cยทg(n) for all n โ‰ฅ nโ‚€.

The 7 Common Complexity Classes

ComplexityNameExamplen=10n=100n=1000n=10โต
O(1)ConstantArray index access1111
O(log n)LogarithmicBinary search371017
O(n)LinearSingle loop101001,000100,000
O(n log n)LinearithmicMerge sort336649,9661,660,964
O(nยฒ)QuadraticNested loops10010,0001,000,00010,000,000,000
O(2โฟ)ExponentialSubset generation1,0241.27ร—10ยณโฐโˆžโˆž
O(n!)FactorialPermutations3,628,800โˆžโˆžโˆž

O(1) โ€” Constant Time

C
int getFirst(int arr[]) {
    return arr[0];  // Always 1 operation regardless of array size
}

O(log n) โ€” Logarithmic Time

C++
// Binary search halves the problem each step
while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (arr[mid] == target) return mid;
    else if (arr[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}

O(n) โ€” Linear Time

Python
def find_max(arr):
    mx = arr[0]
    for x in arr:    # Visits each element once
        if x > mx:
            mx = x
    return mx

O(nยฒ) โ€” Quadratic Time

C++
// Bubble Sort โ€” nested loops
for (int i = 0; i < n; i++)
    for (int j = 0; j < n - i - 1; j++)
        if (arr[j] > arr[j+1])
            swap(arr[j], arr[j+1]);

Simplification Rules

Rule 1 โ€” Drop constants: O(2n) = O(n), O(5nยฒ) = O(nยฒ)

Rule 2 โ€” Drop lower-order terms: O(nยฒ + n) = O(nยฒ), O(nยณ + nยฒ + n) = O(nยณ)

Rule 3 โ€” Different variables stay: O(n + m) stays as O(n + m), NOT O(n)

Quick mental math for contests: A modern computer does ~10โธ simple operations per second. So for a 1-second time limit: O(n) works for n โ‰ค 10โธ, O(n log n) works for n โ‰ค 10โถ, O(nยฒ) works for n โ‰ค 10โด, O(nยณ) works for n โ‰ค 500, O(2โฟ) works for n โ‰ค 25.
O(n log n) โ‰  O(n ร— n). logโ‚‚(10โถ) โ‰ˆ 20, so n log n โ‰ˆ 20 million. But nยฒ = 10ยนยฒ. That's a 50,000ร— difference! Many students underestimate how much faster n log n is compared to nยฒ.

5. Measuring Space Complexity

Space complexity measures the memory an algorithm uses as a function of input size.

TermMeaningExample
Auxiliary SpaceExtra space used beyond the inputMerge sort uses O(n) auxiliary array
Total SpaceInput space + Auxiliary spaceMerge sort: O(n) input + O(n) aux = O(n) total
In-place AlgorithmUses O(1) auxiliary spaceQuicksort (in-place partitioning), Bubble sort
Stack SpaceMemory used by recursive callsRecursive binary search: O(log n) stack frames
Python
# O(n) space โ€” creates a new list
def reverse_copy(arr):
    return arr[::-1]     # New list of size n

# O(1) space โ€” reverses in place
def reverse_inplace(arr):
    i, j = 0, len(arr) - 1
    while i < j:
        arr[i], arr[j] = arr[j], arr[i]
        i += 1; j -= 1

6. Trade-off Concept โ€” Time vs Space

Often you can make an algorithm faster by using more memory, or use less memory at the cost of speed. This is the time-space tradeoff.

ApproachTimeSpaceUse When
HashMap lookupO(1)O(n)Memory is cheap, speed matters
Binary search on sorted arrayO(log n)O(1)Memory is tight, data is sorted
Prefix sum precomputationO(1) per queryO(n)Many range-sum queries
Recompute each timeO(n) per queryO(1)Few queries, tight memory

Prefix Sum Example โ€” Precompute to Answer Fast

C++
// Without prefix sum: O(n) per query, O(1) space
int rangeSum(int arr[], int l, int r) {
    int sum = 0;
    for (int i = l; i <= r; i++) sum += arr[i];
    return sum;
}

// With prefix sum: O(1) per query, O(n) space
int prefix[N];
void buildPrefix(int arr[], int n) {
    prefix[0] = arr[0];
    for (int i = 1; i < n; i++)
        prefix[i] = prefix[i-1] + arr[i];
}
int querySum(int l, int r) {
    return prefix[r] - (l > 0 ? prefix[l-1] : 0);
}
Flipkart's search uses precomputed indices. When you search "blue shirt," they don't scan all 150 million products. An inverted index (precomputed HashMap) maps every keyword to product IDs โ€” O(1) lookup using O(n) extra space. The tradeoff pays off when you have millions of searches per second.

7. Complexity Analysis of Common Patterns

Pattern 1: Single Loop โ€” O(n)

C++
int sum = 0;
for (int i = 0; i < n; i++) {  // Runs n times
    sum += arr[i];               // O(1) work per iteration
}
// Total: n ร— O(1) = O(n)

Pattern 2: Nested Loops โ€” O(nยฒ)

Python
for i in range(n):       # n iterations
    for j in range(n):   # n iterations each
        print(i, j)      # O(1) work
# Total: n ร— n ร— O(1) = O(nยฒ)

Pattern 3: Binary Search โ€” O(log n)

C++
int lo = 0, hi = n - 1;
while (lo <= hi) {           // Each iteration halves the range
    int mid = (lo + hi) / 2;
    if (arr[mid] == target) return mid;
    else if (arr[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}
// Range shrinks: n โ†’ n/2 โ†’ n/4 โ†’ ... โ†’ 1
// Steps = logโ‚‚(n), so O(log n)

Pattern 4: Two Pointer โ€” O(n)

Python
# Find pair with given sum in sorted array
def two_sum_sorted(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:            # Each step moves one pointer
        s = arr[left] + arr[right]
        if s == target:
            return (left, right)
        elif s < target:
            left += 1
        else:
            right -= 1
    return None
# Total pointer moves โ‰ค n, so O(n)

Pattern 5: Sliding Window โ€” O(n)

C++
// Maximum sum subarray of size k
int maxSumWindow(int arr[], int n, int k) {
    int windowSum = 0;
    for (int i = 0; i < k; i++) windowSum += arr[i]; // Initial window
    int maxSum = windowSum;
    for (int i = k; i < n; i++) {
        windowSum += arr[i] - arr[i - k]; // Slide: add right, remove left
        maxSum = max(maxSum, windowSum);
    }
    return maxSum;
}
// Only one pass through the array โ†’ O(n)

8. Amortized Analysis (Brief)

๐Ÿ“ฆ ArrayList / Vector Dynamic Resizing

When a C++ vector or Python list runs out of space, it doubles its capacity. Copying n elements costs O(n). But this happens only every n insertions.

Cost Analysis:

Insert 1: cost 1. Insert 2: cost 1 + copy 1 = 2. Insert 3: cost 1. Insert 4: cost 1 + copy 3 = 4. Insert 5โ€“8: cost 1 each. Insert 9: cost 1 + copy 8 = 9...

Total cost for n insertions โ‰ˆ n + n/2 + n/4 + ... โ‰ˆ 2n. Amortized cost per insertion = 2n/n = O(1).

Key Takeaway:

Even though individual operations can be expensive (O(n) for resize), the average cost per operation over a sequence is O(1). This is amortized analysis.

9. Competitive Coding Constraints โ€” The Cheat Sheet

The single most valuable skill in competitive coding: reading the constraints and immediately knowing what complexity you need.

Constraint (n)Max ComplexityAlgorithm Examples
n โ‰ค 10O(n!) or O(2โฟยทn)Brute-force permutations, backtracking
n โ‰ค 20O(2โฟ)Bitmask DP, subset enumeration
n โ‰ค 500O(nยณ)Floyd-Warshall, DP on intervals
n โ‰ค 5,000O(nยฒ)Bubble sort, 2D DP, brute-force pairs
n โ‰ค 10โตO(n log n)Merge sort, segment trees, binary search
n โ‰ค 10โถO(n)Linear scan, prefix sum, two pointers
n โ‰ค 10โธO(log n) or O(1)Binary search, math formula, O(1) lookup
Contest speed hack: When you read a problem, FIRST look at constraints. If n โ‰ค 10โต, immediately eliminate any O(nยฒ) approach. This saves you from writing a solution that you'll have to throw away. Think complexity FIRST, then code.
Understanding complexity analysis is what separates a โ‚น3 LPA coder from a โ‚น15 LPA coder. Every FAANG interview round includes at least one "What is the time complexity of your solution?" question. Mastering this chapter literally increases your earning potential by 3โ€“5ร—.
Section D

Learn by Doing โ€” 3-Tier Lab Structure

๐ŸŸข Tier 1 โ€” GUIDED: Analyse Code Snippets for Big-O

โฑ๏ธ 30โ€“45 minutesBeginner

For each code snippet below, determine the time complexity. Answers follow.

Snippet 1
C++
for (int i = 0; i < n; i++)
    for (int j = i; j < n; j++)
        cout << arr[j];

Answer: O(nยฒ) โ€” Inner loop runs n + (n-1) + ... + 1 = n(n+1)/2 โ‰ˆ O(nยฒ)

Snippet 2
C++
for (int i = 1; i < n; i *= 2)
    cout << i;

Answer: O(log n) โ€” i doubles each time: 1, 2, 4, 8, ... until n. Number of iterations = logโ‚‚(n).

Snippet 3
C++
for (int i = 0; i < n; i++)
    for (int j = 0; j < 100; j++)
        sum++;

Answer: O(n) โ€” Inner loop runs a constant 100 times. Total = 100n = O(n).

Snippet 4
Python
def rec(n):
    if n <= 1: return
    rec(n // 2)
    rec(n // 2)

Answer: O(n) โ€” Recurrence T(n) = 2T(n/2) + O(1). By Master theorem: O(n).

Snippet 5
C++
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        for (int k = 0; k < n; k++)
            sum++;

Answer: O(nยณ) โ€” Three nested loops each running n times.

๐ŸŸก Tier 2 โ€” SEMI-GUIDED: Optimise O(nยฒ) โ†’ O(n log n)

โฑ๏ธ 60โ€“90 minutesIntermediate

Problem: Count Inversions

Given an array, count pairs (i, j) where i < j but arr[i] > arr[j].

Brute Force โ€” O(nยฒ):

C++
int count = 0;
for (int i = 0; i < n; i++)
    for (int j = i+1; j < n; j++)
        if (arr[i] > arr[j]) count++;

Your task: Use a modified Merge Sort to count inversions in O(n log n). Hint: during the merge step, when an element from the right half is placed before elements from the left half, those are inversions.

Stretch Goal: Implement both solutions and compare runtime for n = 10โต. The brute force should take ~5 seconds. The merge sort approach should finish in <0.1 seconds.

๐Ÿ”ด Tier 3 โ€” OPEN CHALLENGE: Codeforces Problems

โฑ๏ธ 2โ€“3 hoursAdvanced

Solve these problems and write the complexity analysis for each:

  1. CF 1A โ€” Theatre Square (Math, O(1)) โ€” codeforces.com/problemset/problem/1/A
  2. CF 4A โ€” Watermelon (Brute force, O(1)) โ€” codeforces.com/problemset/problem/4/A
  3. CF 230B โ€” T-primes (Sieve + binary search, O(nโˆšn)) โ€” codeforces.com/problemset/problem/230/B
  4. CF 279B โ€” Books (Two pointers / sliding window, O(n)) โ€” codeforces.com/problemset/problem/279/B
  5. CF 466C โ€” Number of Ways (Prefix sums, O(n)) โ€” codeforces.com/problemset/problem/466/C

For each, submit your solution and write: (a) Time complexity, (b) Space complexity, (c) Why this complexity is optimal for the given constraints.

Section E

Problem Set

Syntax & Tracing (5 Questions)

E1. What is the time complexity of this code? for(int i=0; i<n; i++) for(int j=0; j<m; j++) sum++;

E2. How many times does the inner statement execute? for(int i=1; i<=n; i*=3) print(i);

E3. Given T(n) = T(n/2) + O(1), what is the complexity? Trace for n = 16.

E4. What is the output and complexity of: for i in range(n): for j in range(i): print("*")

E5. Simplify: O(3nยฒ + 5n + 100 + n log n). Show each step.

Programming Problems (8 Questions)

E6. Write a function to find the second largest element in an array in O(n) time and O(1) space.

E7. Implement binary search iteratively in C. Your solution must be O(log n).

E8. Write a sliding window function to find the maximum sum of k consecutive elements. Must be O(n).

E9. Given a sorted array with duplicates, count occurrences of a target value in O(log n).

E10. Implement Two Sum: given an array and target, find two numbers that add up to the target. Do it in O(n) using a hash map.

E11. Write a recursive Fibonacci function. What is its time complexity? Now write an O(n) iterative version.

E12. Given two sorted arrays of size n, find the median of the combined array in O(log n).

E13. Write a function that checks if a string has all unique characters in O(n) time.

Industry Problems (3 Questions)

E14. Zomato has 10 lakh restaurants. Design a search system that finds a restaurant by name in O(1) average time. What data structure would you use?

E15. PhonePe processes 3,800 UPI transactions/second. Each transaction must be checked against a fraud database of 1 million known patterns. What's the minimum complexity needed?

E16. IRCTC handles 25 million Tatkal requests. Design a system that processes bookings with O(log n) search and O(1) insertion into the waiting list.

Interview Questions โ€” Asked at Google/Amazon (3 Questions)

๐Ÿข Asked at Google โ€” SDE-1 Interview

E17. "Given an array of n integers, find the maximum subarray sum. What's the brute force complexity? Can you do better than O(nยฒ)? What about O(n)?" (Kadane's Algorithm)

๐Ÿข Asked at Amazon โ€” SDE Intern Interview

E18. "You have a sorted rotated array. Find a target element. What's the time complexity of your approach? Can you do it in O(log n)?"

๐Ÿข Asked at Microsoft โ€” Complexity Analysis Round

E19. "Analyze this code and tell me the exact complexity:" for(i=0;i<n;i++) for(j=1;j<n;j*=2) sum++; "Now what if the inner loop was j<=i instead of j<n?"

Section F

MCQ Assessment Bank โ€” 30 Questions (Bloom's Mapped)

Remember / Identify (Q1โ€“Q5)

Q1

Big-O notation describes the:

  1. Best-case performance
  2. Average-case performance
  3. Upper bound of growth rate
  4. Exact number of operations
Remember
โœ… Answer: (C) โ€” Big-O gives the asymptotic upper bound of an algorithm's growth rate.
Q2

Which complexity class represents constant time?

  1. O(n)
  2. O(1)
  3. O(log n)
  4. O(n!)
Remember
โœ… Answer: (B) โ€” O(1) means the operation takes the same time regardless of input size.
Q3

O(n log n) is the time complexity of:

  1. Bubble Sort
  2. Linear Search
  3. Merge Sort
  4. Binary Search
Remember
โœ… Answer: (C) โ€” Merge Sort divides array in half (log n levels) and merges n elements at each level.
Q4

In worst-case analysis, linear search on an array of n elements takes:

  1. O(1)
  2. O(log n)
  3. O(n)
  4. O(nยฒ)
Remember
โœ… Answer: (C) โ€” Worst case: element is last or absent, requiring n comparisons.
Q5

Which notation describes the lower bound of an algorithm?

  1. Big-O (O)
  2. Big-Omega (ฮฉ)
  3. Big-Theta (ฮ˜)
  4. Small-o (o)
Remember
โœ… Answer: (B) โ€” Big-Omega (ฮฉ) represents the best-case / lower bound.

Understand / Explain (Q6โ€“Q10)

Q6

Why is worst-case analysis preferred over average-case in competitive programming?

  1. It's easier to calculate
  2. It provides a guarantee โ€” judges test worst inputs
  3. Average case is always the same as worst case
  4. Best case is too optimistic
Understand
โœ… Answer: (B) โ€” Competitive judges use hardest test cases. Worst-case guarantees your code won't TLE.
Q7

What does it mean when we say O(n/2) = O(n)?

  1. They take the same time
  2. Constants are dropped in asymptotic notation
  3. n/2 and n are the same number
  4. The notation is wrong
Understand
โœ… Answer: (B) โ€” Big-O drops constant factors. 1/2 is a constant, so O(n/2) simplifies to O(n).
Q8

Why is binary search O(log n) instead of O(n)?

  1. It skips elements randomly
  2. It halves the search space each step
  3. It uses recursion
  4. It works only on small arrays
Understand
โœ… Answer: (B) โ€” Each comparison eliminates half the remaining elements. n โ†’ n/2 โ†’ n/4 โ†’ ... โ†’ 1 takes logโ‚‚(n) steps.
Q9

What is the time-space tradeoff?

  1. Faster algorithms always use more space
  2. Using more memory can reduce time, and vice versa
  3. Time and space are always equal
  4. You can't reduce both time and space
Understand
โœ… Answer: (B) โ€” Example: HashMap gives O(1) lookup with O(n) space vs binary search O(log n) time O(1) space.
Q10

An algorithm is "correct but inefficient." What does this mean?

  1. It gives wrong answers quickly
  2. It gives right answers but takes too long for large inputs
  3. It uses too little memory
  4. It can't handle edge cases
Understand
โœ… Answer: (B) โ€” Correctness (effectiveness) and speed (efficiency) are independent. Bubble sort is correct but O(nยฒ).

Apply / Calculate (Q11โ€“Q15)

Q11

What is the time complexity? for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j]=0;

  1. O(n)
  2. O(n log n)
  3. O(nยฒ)
  4. O(nยณ)
Apply
โœ… Answer: (C) โ€” Two nested loops, each running n times: n ร— n = O(nยฒ).
Q12

Simplify: O(5nยณ + 3nยฒ + 2n + 100)

  1. O(5nยณ)
  2. O(nยณ + nยฒ)
  3. O(nยณ)
  4. O(nยฒ + n)
Apply
โœ… Answer: (C) โ€” Drop constants (5) and lower-order terms (3nยฒ, 2n, 100). Only the dominant term remains.
Q13

What is the complexity? for(i=1;i<=n;i*=2) print(i);

  1. O(n)
  2. O(n/2)
  3. O(log n)
  4. O(nยฒ)
Apply
โœ… Answer: (C) โ€” i doubles each iteration: 1,2,4,8,...n. This takes logโ‚‚(n) steps.
Q14

What is the complexity? for(i=0;i<n;i++) for(j=1;j<n;j*=2) sum++;

  1. O(nยฒ)
  2. O(n log n)
  3. O(n)
  4. O(log n)
Apply
โœ… Answer: (B) โ€” Outer loop: n iterations. Inner loop: log n iterations (j doubles). Total: n ร— log n.
Q15

Recursive function: T(n) = 2T(n/2) + O(n). What is the complexity?

  1. O(n)
  2. O(n log n)
  3. O(nยฒ)
  4. O(log n)
Apply
โœ… Answer: (B) โ€” By Master Theorem: a=2, b=2, c=1. logโ‚‚(2)=1=c, so T(n)=O(n log n). This is Merge Sort's recurrence.

Analyze / Compare (Q16โ€“Q20)

Q16

Which grows faster as n โ†’ โˆž?

  1. n log n grows faster than nยฒ
  2. nยฒ grows faster than n log n
  3. They grow at the same rate
  4. Depends on the value of n
Analyze
โœ… Answer: (B) โ€” nยฒ / (n log n) = n / log n โ†’ โˆž as n โ†’ โˆž. So nยฒ dominates n log n.
Q17

Compare: Algorithm A is O(100n), Algorithm B is O(nยฒ). For which n is A faster?

  1. Always
  2. n > 100
  3. n < 100
  4. Never
Analyze
โœ… Answer: (B) โ€” When n > 100: 100n < nยฒ. For large inputs, linear always beats quadratic.
Q18

Code: for(i=0;i<n;i++) for(j=0;j<i;j++) sum++; โ€” Total operations?

  1. nยฒ
  2. n(n-1)/2
  3. n log n
  4. n
Analyze
โœ… Answer: (B) โ€” Inner loop runs 0+1+2+...+(n-1) = n(n-1)/2 times. Still O(nยฒ) asymptotically.
Q19

HashMap lookup is O(1) average but O(n) worst case. When does worst case occur?

  1. When the key doesn't exist
  2. When all keys hash to the same bucket (collision)
  3. When the HashMap is empty
  4. When using string keys
Analyze
โœ… Answer: (B) โ€” If all n keys collide into one bucket, lookup degrades to a linear scan of that bucket.
Q20

What is the space complexity of recursive Fibonacci fib(n) = fib(n-1) + fib(n-2)?

  1. O(1)
  2. O(n)
  3. O(2โฟ)
  4. O(nยฒ)
Analyze
โœ… Answer: (B) โ€” Max depth of recursion tree is n. Stack holds at most n frames at any time.

Evaluate / Judge (Q21โ€“Q25)

Q21

For n โ‰ค 10โต, which approach is best for sorting?

  1. Bubble Sort O(nยฒ)
  2. Merge Sort O(n log n)
  3. Permutation sort O(n!)
  4. Selection Sort O(nยฒ)
Evaluate
โœ… Answer: (B) โ€” n=10โต: O(nยฒ)=10ยนโฐ (too slow), O(n log n)โ‰ˆ1.7ร—10โถ (fast enough). Only Merge Sort fits.
Q22

Problem: Find a pair with target sum. Array is unsorted, n โ‰ค 10โถ. Best approach?

  1. Sort + binary search โ€” O(n log n)
  2. Brute force nested loops โ€” O(nยฒ)
  3. HashMap โ€” O(n) time, O(n) space
  4. Recursive backtracking โ€” O(2โฟ)
Evaluate
โœ… Answer: (C) โ€” HashMap gives O(1) lookup per element, total O(n). Trade O(n) space for speed.
Q23

When should you prefer O(nยฒ) over O(n log n)?

  1. Never
  2. When n is very small (n โ‰ค 50) and O(nยฒ) has smaller constants
  3. When memory is unlimited
  4. When the data is already sorted
Evaluate
โœ… Answer: (B) โ€” For small n, constant factors dominate. Insertion sort (O(nยฒ)) beats merge sort for n < ~50 due to lower overhead.
Q24

A solution passes for n=10ยณ but TLEs for n=10โต. What should you do?

  1. Submit again โ€” maybe the judge was slow
  2. Optimize constants by using faster I/O
  3. Reduce complexity from O(nยฒ) to O(n log n) or better
  4. Increase the time limit
Evaluate
โœ… Answer: (C) โ€” n=10ยณ works with O(nยฒ)=10โถ. But n=10โต gives 10ยนโฐ operations. Need a fundamentally better algorithm.
Q25

Prefix sum uses O(n) extra space to answer range queries in O(1). Is the tradeoff worth it for 10โถ queries?

  1. No โ€” O(n) space is too much
  2. Yes โ€” saving O(n) per query ร— 10โถ queries outweighs the O(n) space cost
  3. Only if n < 100
  4. It depends on the CPU speed
Evaluate
โœ… Answer: (B) โ€” Without prefix sum: 10โถ ร— O(n) = O(n ร— 10โถ). With: O(n) build + O(10โถ) queries. Clear win.

Create / Design (Q26โ€“Q30)

Q26

To check if any two elements in an array are equal, the most efficient approach is:

  1. Sort then scan โ€” O(n log n)
  2. HashSet โ€” O(n)
  3. Nested loops โ€” O(nยฒ)
  4. Binary search โ€” O(n log n)
Create
โœ… Answer: (B) โ€” Insert into HashSet; if already present, duplicate found. O(n) time, O(n) space.
Q27

Design a solution for: "Given n โ‰ค 10โต, find the k-th smallest element." Best complexity?

  1. Sort entire array โ€” O(n log n)
  2. Min-heap of size k โ€” O(n log k)
  3. Quickselect โ€” O(n) average
  4. Brute force โ€” O(n ร— k)
Create
โœ… Answer: (C) โ€” Quickselect (partition-based) gives O(n) average case, better than sorting for this specific problem.
Q28

Problem: Find max sum subarray. Which algorithmic pattern gives O(n)?

  1. Binary search
  2. Dynamic programming (Kadane's)
  3. Divide and conquer
  4. Greedy with sorting
Create
โœ… Answer: (B) โ€” Kadane's algorithm: maintain running max_ending_here and max_so_far in one pass. O(n) time, O(1) space.
Q29

To find the longest substring without repeating characters in O(n), you would use:

  1. Brute force with nested loops
  2. Sliding window with a HashSet
  3. Dynamic programming table
  4. Sorting the string first
Create
โœ… Answer: (B) โ€” Sliding window: expand right pointer, shrink left when duplicate found. HashSet tracks current window characters. O(n).
Q30

You need to support: insert O(log n), delete O(log n), and find-min O(1). Which data structure?

  1. Array
  2. Linked list
  3. Min-Heap (priority queue)
  4. Stack
Create
โœ… Answer: (C) โ€” Min-Heap gives O(log n) insert/delete and O(1) find-min. Perfect for priority queue operations.
Section G

Short Answer Questions (8)

SA1. What is Big-O notation? Why do we use it?

Model Answer: Big-O notation describes the upper bound of an algorithm's growth rate as input size approaches infinity. We use it because it's hardware-independent โ€” instead of measuring seconds (which vary by CPU), we measure how operations scale with input size. O(nยฒ) means operations grow quadratically, regardless of the computer.

SA2. Explain with an example why we focus on worst-case analysis.

Model Answer: In competitive coding, the judge tests against the hardest possible inputs. For linear search, best case is O(1) (element at index 0), but worst case is O(n) (element absent). If we plan for average case, our solution might TLE on worst-case test data. Worst case gives a guarantee of maximum execution time.

SA3. Differentiate between auxiliary space and total space complexity.

Model Answer: Auxiliary space is the extra memory beyond the input (e.g., temp variables, auxiliary arrays). Total space = input space + auxiliary space. Example: Merge sort has O(n) total space (n for input + n for auxiliary array) but O(n) auxiliary space. In-place quicksort has O(log n) auxiliary space (recursion stack) and O(n) total space.

SA4. What are the two Big-O simplification rules? Give examples.

Model Answer: Rule 1: Drop constants โ€” O(3n) = O(n), O(100nยฒ) = O(nยฒ). Rule 2: Drop lower-order terms โ€” O(nยฒ + n) = O(nยฒ), O(nยณ + nยฒ + n) = O(nยณ). The dominant term determines growth. For n = 10โถ: nยฒ = 10ยนยฒ while n = 10โถ, so the n term is negligible.

SA5. Explain the time-space tradeoff with a real example.

Model Answer: You can often trade memory for speed. Example: Finding if a value exists in an unsorted array โ€” linear scan is O(n) time, O(1) space. Building a HashSet first is O(n) time + O(n) space, but subsequent lookups are O(1). If you have 1 million lookups, HashSet saves 10โถ ร— n operations at the cost of O(n) extra memory.

SA6. Why is O(n log n) considered the "sweet spot" for sorting?

Model Answer: It's proven that comparison-based sorting cannot be faster than O(n log n) in the worst case (information-theoretic lower bound). Algorithms like Merge Sort and Heap Sort achieve this bound. It's fast enough for n โ‰ค 10โถ (โ‰ˆ20 million operations), making it practical for almost all competitive programming constraints.

SA7. What is amortized analysis? Give an example.

Model Answer: Amortized analysis calculates the average cost per operation over a sequence of operations. Example: Dynamic array (vector) resizing โ€” individual append can cost O(n) during resize, but resize happens only every n insertions. Total cost for n appends โ‰ˆ 2n. Amortized cost = 2n/n = O(1) per append.

SA8. How do you read competitive programming constraints to determine required complexity?

Model Answer: Use the rule: ~10โธ operations/second. For time limit T seconds, max operations = T ร— 10โธ. Match n to complexity: n โ‰ค 10โต โ†’ need O(n log n). n โ‰ค 5000 โ†’ O(nยฒ) works. n โ‰ค 20 โ†’ O(2โฟ) ok. n โ‰ค 10 โ†’ O(n!) feasible. Always check constraints FIRST before coding.

Section H

Long Answer Questions (3)

LA1. Explain all 7 common complexity classes with examples, code, and a growth comparison table. (15 marks)

Model Answer: The seven classes are O(1), O(log n), O(n), O(n log n), O(nยฒ), O(2โฟ), O(n!). O(1) = array indexing โ€” constant regardless of size. O(log n) = binary search โ€” halves problem each step. O(n) = linear scan โ€” visits each element once. O(n log n) = merge sort โ€” divide in log n levels, merge n elements per level. O(nยฒ) = bubble sort โ€” nested loops comparing all pairs. O(2โฟ) = subset generation โ€” each element is either included or not. O(n!) = permutation generation โ€” n choices for first, n-1 for second, etc. Growth comparison at n=1000: O(1)=1, O(log n)=10, O(n)=1000, O(n log n)=10000, O(nยฒ)=10โถ, O(2โฟ)=โˆž, O(n!)=โˆž. Only O(1) through O(n log n) are practical for large inputs.

LA2. Analyze the complexity of the following 5 algorithmic patterns with code examples: single loop, nested loop, binary search, two pointers, sliding window. (15 marks)

Model Answer: (1) Single loop: iterates n times with O(1) work each โ†’ O(n). Example: finding maximum in array. (2) Nested loop: outer runs n, inner runs n โ†’ nร—n = O(nยฒ). Example: checking all pairs for duplicates. (3) Binary search: halves search space each step โ†’ O(log n). Requires sorted data. Example: finding target in sorted array. (4) Two pointers: two indices moving inward, total n moves โ†’ O(n). Example: finding pair with target sum in sorted array. (5) Sliding window: window of fixed/variable size moves right, each element enters and leaves once โ†’ O(n). Example: maximum sum subarray of size k. Key insight: patterns 4 and 5 convert O(nยฒ) brute force to O(n) by maintaining state incrementally.

LA3. Explain the constraint-to-complexity mapping technique used in competitive programming. How does reading constraints help you choose the right algorithm? Provide a detailed table and 3 problem examples. (15 marks)

Model Answer: Modern computers process ~10โธ operations/second. For a 1-second time limit, your algorithm must do โ‰ค 10โธ operations. Mapping: nโ‰ค10โ†’O(n!), nโ‰ค20โ†’O(2โฟ), nโ‰ค500โ†’O(nยณ), nโ‰ค5000โ†’O(nยฒ), nโ‰ค10โตโ†’O(n log n), nโ‰ค10โถโ†’O(n), nโ‰ค10โธโ†’O(log n). Example 1: "Sort n numbers, nโ‰ค10โต" โ†’ must use O(n log n) sort (merge/quick), not O(nยฒ) bubble sort. Example 2: "Find subset with target sum, nโ‰ค20" โ†’ O(2ยฒโฐ) = ~10โถ, bitmask DP feasible. Example 3: "Given nโ‰ค10โถ numbers, find two with sum = target" โ†’ need O(n) solution, use HashMap. This technique is the most valuable competitive programming skill โ€” read constraints first, determine complexity ceiling, then pick algorithm.

Section I

Lab Programs

All lab exercises for this unit are integrated into Section D โ€” 3-Tier Labs. The tiered structure provides guided (Tier 1), semi-guided (Tier 2), and open challenge (Tier 3) lab experiences covering Big-O analysis, algorithm optimization, and Codeforces problem solving.

Section J

Industry Spotlight โ€” A Day in the Life

๐Ÿ‘จโ€๐Ÿ’ป Arjun Mehta, 24 โ€” SDE-1 at Google India, Bangalore

Background: B.Tech from NIT Warangal. Started competitive programming in 2nd year. Reached Codeforces Expert (1600+) and solved 500+ LeetCode problems. Got Google interview through competitive coding contest โ€” they noticed his Codeforces profile.

A Typical Day:

9:30 AM โ€” Check team's code review queue. Review a colleague's search ranking algorithm โ€” "This nested loop is O(nยฒ), we can use a HashMap to make it O(n)."

10:30 AM โ€” Work on optimising Google Maps' route suggestion engine. Current algorithm is O(Vยฒ) for V vertices โ€” implementing Dijkstra with min-heap for O((V+E) log V).

12:00 PM โ€” Team design review meeting. Present complexity analysis of three proposed approaches. Team picks the O(n log n) solution over the O(nยฒ) one.

2:00 PM โ€” Lunch at Google cafeteria. Discuss the latest Codeforces Div 2 round with colleagues.

3:00 PM โ€” Write unit tests and benchmark the optimised algorithm. Confirm 50x speedup for production traffic.

5:00 PM โ€” 1 hour of LeetCode practice โ€” keeping competitive programming skills sharp.

6:30 PM โ€” Mentor a junior intern on time complexity analysis.

DetailInfo
Tools Used DailyC++, Python, Algorithm Design, Code Review, Profiling Tools
Entry Salary (SDE-1)โ‚น25โ€“45 LPA (Google India)
Key SkillComplexity analysis โ€” every code review involves Big-O discussion
Competitive Coding ProfileCodeforces Expert, 500+ LeetCode, ACM ICPC regionalist
Companies Hiring CP CodersGoogle, Amazon, Microsoft, Flipkart, DE Shaw, Tower Research, Directi
Section K

Earn With It โ€” Freelance & Income Roadmap

๐Ÿ’ฐ Your Earning Path After This Chapter

Portfolio Piece: A complexity analysis report comparing brute-force vs optimised solutions for 5 problems โ€” demonstrates analytical thinking to employers.

Competitive Programming Coaching: Teach juniors Big-O analysis, constraint mapping, and pattern recognition. Charge โ‚น500โ€“โ‚น1,500/hr on platforms like Codementor, Preply, or local tutoring.

Problem Setting: Create algorithmic problems for college contests or platforms. โ‚น500โ€“โ‚น2,000 per problem with test cases and editorials.

PlatformBest ForTypical Rate
Codementor1-on-1 competitive programming coachingโ‚น500โ€“โ‚น1,500/hr ($7โ€“$20/hr)
PreplyAlgorithm tutoring for interview prepโ‚น400โ€“โ‚น1,200/hr
UnstopProblem setting for Indian college contestsโ‚น500โ€“โ‚น2,000/problem
TopmateMentorship sessions for DSA/CPโ‚น300โ€“โ‚น1,000/session
LinkedIn/WhatsAppDirect coaching to juniors at your collegeโ‚น300โ€“โ‚น800/hr
The fastest way to earn from this chapter: Offer "DSA Complexity Analysis Crash Course" to juniors preparing for placements. 4 sessions ร— โ‚น500 = โ‚น2,000 from each student. Get 10 students and you've earned โ‚น20,000 in a month โ€” just by teaching what you learned in this chapter.
Section L

Chapter Summary & Complexity Cheat Sheet

๐Ÿ“‹ Key Takeaways

  • Algorithm behaviour is measured by how operations grow with input size, not by clock time
  • Big-O notation gives the upper bound (worst case) of growth rate
  • Worst case is preferred because competitive judges test hardest inputs
  • Always drop constants and drop lower-order terms when simplifying
  • Time-space tradeoff: use more memory to get faster execution when needed
  • The 5 key patterns: single loop O(n), nested O(nยฒ), binary search O(log n), two-pointer O(n), sliding window O(n)
  • Read constraints first โ€” they tell you the maximum complexity your solution can have

Complexity Cheat Sheet

ComplexityNameExampleOps at n=10โถFeasible?
O(1)ConstantArray index, hash lookup1โœ… Always
O(log n)LogarithmicBinary search20โœ… Always
O(n)LinearSingle scan, prefix sum10โถโœ… <0.01s
O(n log n)LinearithmicMerge sort, sort+search2ร—10โทโœ… ~0.2s
O(nยฒ)QuadraticNested loops, bubble sort10ยนยฒโŒ ~3hrs
O(2โฟ)ExponentialSubset generationโˆžโŒ Only nโ‰ค25
O(n!)FactorialPermutationsโˆžโŒ Only nโ‰ค12
Section M

Checkpoint โ€” Self-Assessment

SkillTool/MethodPortfolio OutputCan You Earn?
Big-O NotationMathematical analysisโ€”โœ… Yes โ€” interview-ready skill
Complexity IdentificationCode pattern recognition5 analysed code snippetsโœ… Yes โ€” core interview skill
Constraint MappingConstraint โ†’ complexity tableCheat sheet referenceโœ… Yes โ€” contest-ready skill
Algorithm OptimisationPattern applicationO(nยฒ) โ†’ O(n log n) solutionโœ… Yes โ€” high-value skill
Time-Space TradeoffHashMap, prefix sumTradeoff analysis documentโœ… Yes โ€” system design skill
Common PatternsTwo-pointer, sliding window, binary search5 pattern implementationsโœ… Yes โ€” covers 80% of problems
Competitive CodingCodeforces, LeetCode5 solved problems with analysisโœ… Yes โ€” โ‚น500โ€“โ‚น1,500/hr coaching
Minimum Viable Earning Setup after this chapter: A Codementor/Topmate profile offering "Big-O & Complexity Analysis Tutoring" + 5 solved Codeforces problems as proof of skill = you can earn โ‚น5,000โ€“โ‚น20,000/month coaching placement-bound students.

โœ… Unit 1 complete. MCQs: 30. Ready for Unit 2!

[QR: Link to EduArtha video tutorial โ€” Behaviour Analysis & Complexity]