100% FREE Updated: Mar 2026 Algorithms and Data Structures Foundations of Algorithms

Algorithm Basics and Analysis

Comprehensive study notes on Algorithm Basics and Analysis for CMI M.Sc. and Ph.D. Computer Science preparation. This chapter covers key concepts, formulas, and examples needed for your exam.

Algorithm Basics and Analysis

This chapter establishes the foundational principles of algorithm analysis, critical for evaluating computational efficiency. Mastery of these concepts is indispensable for advanced algorithm design and optimization, forming a core component of the M.Sc./Ph.D. Computer Science CMI examination.

---

Chapter Contents

|

| Topic |

|---|-------| | 1 | Time and Space Complexity | | 2 | Best, Worst, and Average Case |

---

We begin with Time and Space Complexity.

Part 1: Time and Space Complexity

Understanding the efficiency of algorithms through time and space complexity analysis is fundamental for designing scalable and performant solutions in computer science. This topic provides the tools to evaluate and compare algorithms, crucial for CMI examinations.

---

Core Concepts

1. Asymptotic Notation

Asymptotic notation describes the limiting behavior of a function, providing a way to classify algorithms based on their growth rate as input size approaches infinity. We use Big-O, Omega, and Theta notation to express upper bounds, lower bounds, and tight bounds, respectively.

πŸ“– Big-O Notation

We say f(n)=O(g(n))f(n) = O(g(n)) if there exist positive constants cc and n0n_0 such that 0≀f(n)≀cβ‹…g(n)0 \le f(n) \le c \cdot g(n) for all nβ‰₯n0n \ge n_0. It represents an upper bound on the growth rate.

πŸ“– Omega Notation

We say f(n)=Ξ©(g(n))f(n) = \Omega(g(n)) if there exist positive constants cc and n0n_0 such that 0≀cβ‹…g(n)≀f(n)0 \le c \cdot g(n) \le f(n) for all nβ‰₯n0n \ge n_0. It represents a lower bound on the growth rate.

πŸ“– Theta Notation

We say f(n)=Θ(g(n))f(n) = \Theta(g(n)) if there exist positive constants c1,c2,c_1, c_2, and n0n_0 such that 0≀c1β‹…g(n)≀f(n)≀c2β‹…g(n)0 \le c_1 \cdot g(n) \le f(n) \le c_2 \cdot g(n) for all nβ‰₯n0n \ge n_0. It represents a tight bound on the growth rate.

Worked Example: Proving Big-O

Show that 3n2+2n+5=O(n2)3n^2 + 2n + 5 = O(n^2).

Step 1: Identify f(n)f(n) and g(n)g(n).

> f(n)=3n2+2n+5f(n) = 3n^2 + 2n + 5
> g(n)=n2g(n) = n^2

Step 2: Find constants cc and n0n_0 such that 3n2+2n+5≀cβ‹…n23n^2 + 2n + 5 \le c \cdot n^2 for nβ‰₯n0n \ge n_0.

> For nβ‰₯1n \ge 1:
> 3n2+2n+5≀3n2+2n2+5n23n^2 + 2n + 5 \le 3n^2 + 2n^2 + 5n^2
> 3n2+2n+5≀10n23n^2 + 2n + 5 \le 10n^2

Step 3: Choose cc and n0n_0.

> We can choose c=10c = 10 and n0=1n_0 = 1.
> Thus, 3n2+2n+5=O(n2)3n^2 + 2n + 5 = O(n^2).

Answer: 3n2+2n+5=O(n2)3n^2 + 2n + 5 = O(n^2) is proven with c=10,n0=1c=10, n_0=1.

:::question type="MCQ" question="Which of the following statements is true for f(n)=nlog⁑nf(n) = n \log n and g(n)=nng(n) = n \sqrt{n}?" options=["f(n)=Θ(g(n))f(n) = \Theta(g(n))","f(n)=O(g(n))f(n) = O(g(n)) but f(n)β‰ Ξ©(g(n))f(n) \ne \Omega(g(n))","f(n)=Ξ©(g(n))f(n) = \Omega(g(n)) but f(n)β‰ O(g(n))f(n) \ne O(g(n))","Neither f(n)=O(g(n))f(n) = O(g(n)) nor f(n)=Ξ©(g(n))f(n) = \Omega(g(n))"] answer="f(n)=O(g(n))f(n) = O(g(n)) but f(n)β‰ Ξ©(g(n))f(n) \ne \Omega(g(n))" hint="Compare the growth rates of log⁑n\log n and n\sqrt{n}." solution="We need to compare nlog⁑nn \log n and nnn \sqrt{n}. This simplifies to comparing log⁑n\log n and n\sqrt{n}.
We know that for sufficiently large nn, log⁑n<n\log n < \sqrt{n}.
Therefore, nlog⁑n<nnn \log n < n \sqrt{n}.
This implies f(n)=O(g(n))f(n) = O(g(n)).
Since log⁑n\log n grows slower than n\sqrt{n}, f(n)f(n) cannot be bounded below by a constant multiple of g(n)g(n), so f(n)β‰ Ξ©(g(n))f(n) \ne \Omega(g(n)).
Thus, f(n)=O(g(n))f(n) = O(g(n)) but f(n)β‰ Ξ©(g(n))f(n) \ne \Omega(g(n)) is the correct statement."
:::

---

2. Analyzing Time Complexity of Iterative Algorithms

We analyze iterative algorithms by counting the number of basic operations (e.g., comparisons, assignments, arithmetic operations) as a function of the input size nn. Summation notation is often used to express the total count of operations over loops.

Worked Example 1: Single Loop Analysis

Consider the function `g(int n)`:

```c
int g(int n) {
int a = 1;
int i = 0;
while (i < n) {
i = i + 1;
a = 2 * a;
}
return a;
}
```

Determine the time complexity of `g(n)`.

Step 1: Identify the loop and its iteration count.

> The `while` loop runs as long as `i < n`.
> The variable `i` starts at 00 and increments by 11 in each iteration.
> The loop executes nn times (for i=0,1,…,nβˆ’1i = 0, 1, \ldots, n-1).

Step 2: Count operations inside the loop.

> Inside the loop: `i = i + 1` (1 assignment, 1 addition), `a = 2 * a` (1 assignment, 1 multiplication).
> Each iteration performs a constant number of operations.

Step 3: Calculate total operations.

> Total operations β‰ˆnΓ—(constantΒ operationsΒ perΒ iteration)\approx n \times (\text{constant operations per iteration}).
> Total operations is Θ(n)\Theta(n).

Answer: The time complexity of `g(n)` is Θ(n)\Theta(n).

Worked Example 2: Nested Loops Analysis

Consider the `mystery` function:

```c
function mystery (A[0...99]) {
int i,j,m;
for (i = 0; i < 100; i++) {
m = i;
for (j = i; j < 100; j++) {
if (A[j] > A[m]) { // The test
m = j;
}
}
reverse(A,i,m); // Assume reverse(A,i,m) takes O(m-i+1) time
}
return;
}
```

Determine the number of times the test `A[j] > A[m]` is executed.

Step 1: Analyze the outer loop.

> The outer loop runs for `i` from 00 to 9999. This is 100100 iterations.

Step 2: Analyze the inner loop for a given `i`.

> The inner loop runs for `j` from `i` to 9999.
> For `i = 0`, `j` runs from 00 to 9999 (100100 times).
> For `i = 1`, `j` runs from 11 to 9999 (9999 times).
> ...
> For `i = 99`, `j` runs from 9999 to 9999 (11 time).

Step 3: Sum the total number of test executions.

> Total tests = βˆ‘i=099(numberΒ ofΒ jΒ iterations)\sum_{i=0}^{99} (\text{number of j iterations})
> Total tests = βˆ‘k=1100k\sum_{k=1}^{100} k (where k=100βˆ’ik = 100-i)
> Total tests = 100+99+β‹―+1100 + 99 + \cdots + 1
> Total tests = 100Γ—(100+1)2\frac{100 \times (100 + 1)}{2}
> Total tests = 100Γ—1012\frac{100 \times 101}{2}
> Total tests = 50Γ—10150 \times 101
> Total tests = 50505050

Answer: The test `A[j] > A[m]` is executed 50505050 times.

Worked Example 3: Analyzing a function with Fibonacci-like sequence

Consider the function `f(int n)`:

```c
int f(int n) {
int a, b, c, d;
a = 0; b = 0;
c = 0; d = 1;
while (a < n) {
a = a + 1;
b = b + c;
int temp = d;
d = c;
c = temp;
}
return b;
}
```

Determine the value returned by `f(100)`.

Step 1: Trace the variables `a`, `b`, `c`, `d` through iterations.

> Initial: a=0,b=0,c=0,d=1a=0, b=0, c=0, d=1

| Iteration | `a` (before increment) | `a` (after increment) | `b` (after `b=b+c`) | `temp` | `d` (after `d=c`) | `c` (after `c=temp`) |
|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 0+0=00+0=0 | 1 | 0 | 1 |
| 1 | 1 | 2 | 0+1=10+1=1 | 0 | 1 | 0 |
| 2 | 2 | 3 | 1+0=11+0=1 | 1 | 0 | 1 |
| 3 | 3 | 4 | 1+1=21+1=2 | 0 | 1 | 0 |
| 4 | 4 | 5 | 2+0=22+0=2 | 1 | 0 | 1 |
| 5 | 5 | 6 | 2+1=32+1=3 | 0 | 1 | 0 |
| 6 | 6 | 7 | 3+0=33+0=3 | 1 | 0 | 1 |
| 7 | 7 | 8 | 3+1=43+1=4 | 0 | 1 | 0 |
| 8 | 8 | 9 | 4+0=44+0=4 | 1 | 0 | 1 |
| 9 | 9 | 10 | 4+1=54+1=5 | 0 | 1 | 0 |

Step 2: Observe the pattern of `c` and `b`.

> `c` alternates between 00 and 11 (starting 0,1,0,1,…0, 1, 0, 1, \dots).
> `b` accumulates `c`.
> `b` sequence: 0,0,1,1,2,2,3,3,4,4,5,…0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, \dots
> `b` increments by 11 every two iterations. Specifically, `b` increments by 11 when `a` (after increment) is odd.

Step 3: Calculate `b` for `n=100`.

> The loop runs until `a` (after increment) reaches `n`. So, `a` takes values 1,2,…,1001, 2, \dots, 100.
> The value of `b` is updated nn times.
> `b` increments when `a` is 1,3,5,…,991, 3, 5, \dots, 99.
> The number of odd values in this range is (99βˆ’1)/2+1=49+1=50(99-1)/2 + 1 = 49+1 = 50.
> Therefore, `b` will sum 11 for 5050 times, resulting in 5050.

Answer: `f(100)` returns 5050.

:::question type="MCQ" question="What is the time complexity of the following code snippet in terms of nn?" options=["O(n)O(n)","O(nlog⁑n)O(n \log n)","O(n2)O(n^2)","O(log⁑n)O(\log n)"] answer="O(n2)O(n^2)" hint="Analyze the nested loop structure and how many times the inner loop executes for each outer loop iteration." solution="Step 1: Analyze the outer loop.
The outer loop `for (i = 0; i < n; i++)` runs nn times.

Step 2: Analyze the inner loop.
The inner loop `for (j = i; j < n; j++)` runs for `j` starting from `i` up to `n-1`.

  • When `i = 0`, `j` runs nn times.

  • When `i = 1`, `j` runs nβˆ’1n-1 times.

  • When `i = 2`, `j` runs nβˆ’2n-2 times.

  • ...

  • When `i = n-1`, `j` runs 11 time.


Step 3: Sum the operations.
The total number of times the innermost statement (e.g., `sum++`) is executed is the sum of an arithmetic series:
βˆ‘i=0nβˆ’1(nβˆ’i)=n+(nβˆ’1)+β‹―+1\sum_{i=0}^{n-1} (n-i) = n + (n-1) + \cdots + 1

This sum is equal to n(n+1)2\frac{n(n+1)}{2}.

Step 4: Determine the Big-O complexity.
n(n+1)2=n2+n2=12n2+12n\frac{n(n+1)}{2} = \frac{n^2 + n}{2} = \frac{1}{2}n^2 + \frac{1}{2}n.
The dominant term is n2n^2.
Therefore, the time complexity is O(n2)O(n^2).

```c
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
sum++;
}
}
```"
:::

---

3. Analyzing Time Complexity of Recursive Algorithms

Recursive algorithms are analyzed by formulating recurrence relations that describe the running time T(n)T(n) in terms of the running time on smaller inputs. Common methods for solving recurrences include the Master Theorem, the Substitution Method, and the Recursion Tree Method.

πŸ“ Master Theorem

For a recurrence of the form T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), where aβ‰₯1,b>1a \ge 1, b > 1, and f(n)f(n) is asymptotically positive, we compare f(n)f(n) with nlog⁑ban^{\log_b a}:

  • If f(n)=O(nlog⁑baβˆ’Ο΅)f(n) = O(n^{\log_b a - \epsilon}) for some constant Ο΅>0\epsilon > 0, then T(n)=Θ(nlog⁑ba)T(n) = \Theta(n^{\log_b a}).

  • If f(n)=Θ(nlog⁑ba)f(n) = \Theta(n^{\log_b a}), then T(n)=Θ(nlog⁑balog⁑n)T(n) = \Theta(n^{\log_b a} \log n).

  • If f(n)=Ξ©(nlog⁑ba+Ο΅)f(n) = \Omega(n^{\log_b a + \epsilon}) for some constant Ο΅>0\epsilon > 0, and if af(n/b)≀cf(n)a f(n/b) \le c f(n) for some constant c<1c < 1 and sufficiently large nn (regularity condition), then T(n)=Θ(f(n))T(n) = \Theta(f(n)).

Worked Example 1: Master Theorem Application

Solve the recurrence T(n)=2T(n/2)+nT(n) = 2T(n/2) + n.

Step 1: Identify a,b,a, b, and f(n)f(n).

> a=2a = 2
> b=2b = 2
> f(n)=nf(n) = n

Step 2: Calculate nlog⁑ban^{\log_b a}.

> nlog⁑22=n1=nn^{\log_2 2} = n^1 = n.

Step 3: Compare f(n)f(n) with nlog⁑ban^{\log_b a}.

> f(n)=nf(n) = n and nlog⁑ba=nn^{\log_b a} = n.
> This matches Case 2 of the Master Theorem: f(n)=Θ(nlog⁑ba)f(n) = \Theta(n^{\log_b a}).

Step 4: Apply the Master Theorem result.

> T(n)=Θ(nlog⁑balog⁑n)=Θ(nlog⁑n)T(n) = \Theta(n^{\log_b a} \log n) = \Theta(n \log n).

Answer: T(n)=Θ(nlog⁑n)T(n) = \Theta(n \log n).

Worked Example 2: Substitution Method

Solve the recurrence T(n)=2T(n/2)+1T(n) = 2T(n/2) + 1 with T(1)=1T(1) = 1.

Step 1: Guess the solution (using Master Theorem as a hint).

> For T(n)=2T(n/2)+1T(n) = 2T(n/2) + 1: a=2,b=2,f(n)=1a=2, b=2, f(n)=1.
> nlog⁑ba=nlog⁑22=n1=nn^{\log_b a} = n^{\log_2 2} = n^1 = n.
> Since f(n)=1=O(n1βˆ’Ο΅)f(n)=1 = O(n^{1-\epsilon}) for Ο΅=1\epsilon=1, this falls under Case 1, implying T(n)=Θ(n)T(n) = \Theta(n).
> Let's try to prove T(n)≀cnβˆ’dT(n) \le cn - d for some constants c,dc, d.

Step 2: Substitute the guess into the recurrence.

> Assume T(k)≀ckβˆ’dT(k) \le ck - d for all k<nk < n.
> T(n)≀2(c(n/2)βˆ’d)+1T(n) \le 2(c(n/2) - d) + 1
> T(n)≀cnβˆ’2d+1T(n) \le cn - 2d + 1

Step 3: Show that T(n)≀cnβˆ’dT(n) \le cn - d.

> We need cnβˆ’2d+1≀cnβˆ’dcn - 2d + 1 \le cn - d.
> This implies βˆ’2d+1β‰€βˆ’d-2d + 1 \le -d, or 1≀d1 \le d. Let d=1d=1.
> So, we need to show T(n)≀cnβˆ’1T(n) \le cn - 1.

Step 4: Verify base case and solve for cc.

> For n=1n=1, T(1)=1T(1)=1.
> c(1)βˆ’1=1β€…β€ŠβŸΉβ€…β€Šc=2c(1) - 1 = 1 \implies c = 2.
> So, our guess is T(n)≀2nβˆ’1T(n) \le 2n - 1.
> Let's substitute back: T(n)≀2(2(n/2)βˆ’1)+1=2(nβˆ’1)+1=2nβˆ’2+1=2nβˆ’1T(n) \le 2(2(n/2)-1) + 1 = 2(n-1) + 1 = 2n-2+1 = 2n-1.
> The guess holds.

Answer: T(n)=Θ(n)T(n) = \Theta(n).

:::question type="MCQ" question="What is the asymptotic time complexity of an algorithm whose recurrence relation is T(n)=3T(n/3)+n2T(n) = 3T(n/3) + n^2?" options=["O(n)O(n)","O(nlog⁑n)O(n \log n)","O(n2)O(n^2)","O(n3)O(n^3)"] answer="O(n2)O(n^2)" hint="Apply the Master Theorem. Compare f(n)f(n) with nlog⁑ban^{\log_b a}." solution="Step 1: Identify a,b,a, b, and f(n)f(n).
> a=3a = 3
> b=3b = 3
> f(n)=n2f(n) = n^2

Step 2: Calculate nlog⁑ban^{\log_b a}.
> nlog⁑33=n1=nn^{\log_3 3} = n^1 = n.

Step 3: Compare f(n)f(n) with nlog⁑ban^{\log_b a}.
> f(n)=n2f(n) = n^2 and nlog⁑ba=nn^{\log_b a} = n.
> We observe that n2=Ξ©(n1+Ο΅)n^2 = \Omega(n^{1+\epsilon}) for Ο΅=1\epsilon = 1.
> This matches Case 3 of the Master Theorem.

Step 4: Check regularity condition.
> We need to check if af(n/b)≀cf(n)a f(n/b) \le c f(n) for some constant c<1c < 1.
> 3β‹…(n/3)2=3β‹…n2/9=n2/33 \cdot (n/3)^2 = 3 \cdot n^2/9 = n^2/3.
> We need n2/3≀cn2n^2/3 \le c n^2. We can choose c=1/3<1c = 1/3 < 1. The condition holds.

Step 5: Apply the Master Theorem result.
> T(n)=Θ(f(n))=Θ(n2)T(n) = \Theta(f(n)) = \Theta(n^2).
Therefore, the asymptotic time complexity is O(n2)O(n^2)."
:::

---

4. Space Complexity Analysis

Space complexity quantifies the total amount of memory an algorithm requires to run, as a function of the input size nn. It includes both auxiliary space (memory used by the algorithm itself, excluding input) and input space (memory required to store the input). In competitive programming, we often focus on auxiliary space.

Worked Example: Iterative vs. Recursive Factorial Space

Compare the auxiliary space complexity of iterative and recursive implementations of factorial.

Step 1: Iterative Factorial

```python
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
```

> The variables `result`, `i`, and `n` each take constant space. No additional data structures grow with nn.
> Auxiliary space complexity: O(1)O(1).

Step 2: Recursive Factorial

```python
def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)
```

> Each recursive call adds a stack frame to the call stack. This stack frame stores local variables and the return address.
> The depth of the recursion is nn (from nn down to 00).
> Each stack frame takes constant space.
> Auxiliary space complexity: O(n)O(n) due to the call stack.

Answer: Iterative factorial has O(1)O(1) auxiliary space, while recursive factorial has O(n)O(n) auxiliary space.

:::question type="MCQ" question="What is the auxiliary space complexity of the following function?" options=["O(1)O(1)","O(log⁑n)O(\log n)","O(n)O(n)","O(n2)O(n^2)"] answer="O(n)O(n)" hint="Consider the data structure used and its size relative to the input nn." solution="Step 1: Identify data structures that store elements.
The function `create_list` creates a list `my_list` and appends nn elements to it.

Step 2: Determine space used by `my_list`.
Each element added to `my_list` occupies constant space.
Since nn elements are added, the total space occupied by `my_list` is proportional to nn.

Step 3: Determine auxiliary space.
The variable `i` and the list `my_list` are the primary memory consumers. `i` takes O(1)O(1) space. `my_list` takes O(n)O(n) space.
Thus, the dominant factor for auxiliary space is O(n)O(n).

```python
def create_list(n):
my_list = []
for i in range(n):
my_list.append(i)
return my_list
```"
:::

---

5. Complexity Classes and Reductions

Complexity classes categorize problems based on the resources (time or space) required to solve them. Reductions are a fundamental tool to relate the difficulty of problems. If problem A can be reduced to problem B, it means that an efficient algorithm for B can be used to efficiently solve A.

πŸ“– Polynomial-time Reduction

A problem AA is polynomial-time reducible to a problem BB (denoted A≀PBA \le_P B) if there exists a polynomial-time algorithm that transforms any instance of AA into an instance of BB, such that solving the instance of BB correctly yields a solution to the instance of AA.

πŸ“– Complexity Class P

The class PP contains decision problems that can be solved by a deterministic Turing machine in polynomial time.

πŸ“– Complexity Class NP

The class NPNP contains decision problems for which a given solution (a "certificate") can be verified in polynomial time by a deterministic Turing machine.

Worked Example 1: Implications of Reductions

Suppose problem AA can be reduced to problem BB in polynomial time (A≀PBA \le_P B). We know there is a polynomial-time algorithm to solve BB. What can we conclude about problem AA?

Step 1: Understand A≀PBA \le_P B.

> This means an instance of AA can be transformed into an instance of BB in polynomial time (Treduce(n)=O(nk)T_{reduce}(n) = O(n^k)).
> The size of the transformed instance mm must be polynomially bounded by nn, i.e., m=O(np)m = O(n^p) for some pp.

Step 2: Combine reduction with solving BB.

> If we have a polynomial-time algorithm for BB (TB(m)=O(mj)T_B(m) = O(m^j)), then to solve AA:
> 1. Transform AA instance (size nn) to BB instance (size mm) in O(nk)O(n^k) time.
> 2. Solve the BB instance in O(mj)=O((np)j)=O(npj)O(m^j) = O((n^p)^j) = O(n^{pj}) time.
> 3. The total time for AA is O(nk+npj)O(n^k + n^{pj}), which is polynomial in nn.

Step 3: Conclude total time for AA.

> Therefore, problem AA can also be solved in polynomial time.

Answer: If A≀PBA \le_P B and B∈PB \in P, then A∈PA \in P.

Worked Example 2: Modified Procedure Complexity

A procedure P(n)P(n) makes multiple calls to Q(m)Q(m) and runs in polynomial time in nn. Q(m)Q(m) is replaced by R(m)R(m), which runs in exponential time in mm. What conditions ensure P(n)P(n) still runs in polynomial time?

Step 1: Analyze the original P(n)P(n).

> P(n)P(n) runs in polynomial time. Let its original complexity be O(nk)O(n^k).
> This means the total time spent in PP's own operations plus all calls to Q(m)Q(m) is O(nk)O(n^k).

Step 2: Analyze the impact of replacing Q(m)Q(m) with R(m)R(m).

> Q(m)Q(m) was polynomial in mm. R(m)R(m) is exponential in mm, e.g., TR(m)=O(cm)T_R(m) = O(c^m) for some constant c>1c>1.

Step 3: Consider the total time for P(n)P(n) with R(m)R(m).

> The new total time for P(n)P(n) would be (polynomial time for PP's own operations) + βˆ‘(timeΒ forΒ eachΒ callΒ toΒ R(m))\sum (\text{time for each call to } R(m)).
> If PP makes KK calls to R(m)R(m), and for each call, mm is some value mjm_j, the total time is O(nk+βˆ‘j=1Kcmj)O(n^k + \sum_{j=1}^K c^{m_j}).

Step 4: Identify conditions for polynomial time.

> For P(n)P(n) to remain polynomial in nn, the sum βˆ‘cmj\sum c^{m_j} must be polynomially bounded by nn.
> If the number of calls KK is polynomial in nn (e.g., K=O(nq)K=O(n^q)), then we need cmjc^{m_j} for each mjm_j to not cause exponential growth in nn.
> This happens if mjm_j is bounded by a logarithmic function of nn.
> Specifically, if mj≀log⁑cnm_j \le \log_c n for all calls, then cmj≀clog⁑cn=nc^{m_j} \le c^{\log_c n} = n.
> In this case, each call to R(mj)R(m_j) takes O(n)O(n) time.
> If there are O(nq)O(n^q) such calls, the total time for calls is O(nqβ‹…n)=O(nq+1)O(n^q \cdot n) = O(n^{q+1}), which is polynomial in nn.

Answer: P(n)P(n) runs in polynomial time in nn if, for each call Q(m)Q(m), m≀log⁑nm \le \log n.

:::question type="MSQ" question="Given that problem XX is polynomial-time reducible to problem YY (X≀PYX \le_P Y), and problem YY is known to be NP-complete. Which of the following statements are definitely true?" options=["Problem XX is also NP-complete.","Problem XX belongs to NP.","If XX is NP-complete, then P=NPP=NP.","If YY can be solved in polynomial time, then XX can also be solved in polynomial time."] answer="Problem XX belongs to NP.,If YY can be solved in polynomial time, then XX can also be solved in polynomial time." hint="Recall definitions of NP-completeness and the implications of polynomial-time reductions between complexity classes." solution="Analysis of options:

Problem XX is also NP-complete. Not necessarily. If X≀PYX \le_P Y and YY is NP-complete, XX could be in PP, or XX could be NP-complete, or XX could be in NP but not NP-complete (if Pβ‰ NPP \ne NP). For XX to be NP-complete, it must also be in NP, and all problems in NP must be reducible to XX. The reduction X≀PYX \le_P Y only tells us that XX is at most as hard* as YY in terms of polynomial time.

* Problem XX belongs to NP. This is true. If X≀PYX \le_P Y and YY is NP-complete, then Y∈NPY \in NP. Since XX reduces to YY, and YY is verifiable in polynomial time, then XX is also verifiable in polynomial time (by first reducing XX to YY, then verifying YY's solution). Therefore, X∈NPX \in NP.

* If XX is NP-complete, then P=NPP=NP. This is false. This statement should be 'If YY is NP-complete and Y∈PY \in P, then P=NPP=NP'. If XX is NP-complete, it means XX is one of the hardest problems in NP. If XX could be solved in polynomial time, then P=NPP=NP. The statement as written is not definitely true.

* If YY can be solved in polynomial time, then XX can also be solved in polynomial time. This is true. This is the direct implication of a polynomial-time reduction. If X≀PYX \le_P Y and YY has a polynomial-time algorithm, then we can solve XX by transforming it to YY (polynomial time) and solving YY (polynomial time), resulting in an overall polynomial-time algorithm for XX.

Thus, 'Problem XX belongs to NP.' and 'If YY can be solved in polynomial time, then XX can also be solved in polynomial time.' are the definitely true statements."
:::

---

Advanced Applications

Worked Example: Combined Analysis of Reduction and Exponential Algorithms

We have constructed a polynomial time reduction from problem AA to problem BB. Consider the implications for the existence of algorithms.

Step 1: Define the reduction A≀PBA \le_P B.

> This means if BB can be solved in polynomial time, then AA can also be solved in polynomial time.
> Equivalently, if AA cannot be solved in polynomial time (i.e., requires exponential time), then BB also cannot be solved in polynomial time (must also require exponential time).

Step 2: Analyze the scenarios.

> Scenario 1: We know of polynomial time algorithms for both AA and BB.
> * Possible. If B∈PB \in P, then A∈PA \in P. This is consistent.

> Scenario 2: We only know of exponential time algorithms for both AA and BB.
> * Possible. If Bβˆ‰PB \notin P, then AA could also be βˆ‰P\notin P. This is consistent.

> Scenario 3: We only know of an exponential time algorithm for AA, but we have a polynomial time algorithm for BB.
> This scenario is NOT possible. If BB has a polynomial-time algorithm, then by the reduction A≀PBA \le_P B, AA must also have a polynomial-time algorithm. It cannot only* have an exponential-time algorithm.

> Scenario 4: We only know of an exponential time algorithm for BB, but we have a polynomial time algorithm for AA.
> * Possible. A≀PBA \le_P B means BB is at least as hard as AA. If A∈PA \in P, BB could still be harder (e.g., Bβˆ‰PB \notin P). This is consistent. For example, 3βˆ’SAT≀PSAT3-SAT \le_P SAT. If Pβ‰ NPP \ne NP, both are exponential. But if AA is a trivial problem in PP and BB is NP-complete, this situation is possible.

Answer: The scenario that is not possible is: "We only know of an exponential time algorithm for AA, but we have a polynomial time algorithm for BB."

:::question type="MCQ" question="An algorithm has a time complexity of T(n)=T(nβˆ’1)+O(n)T(n) = T(n-1) + O(n) with T(1)=O(1)T(1)=O(1). What is its overall time complexity?" options=["O(n)O(n)","O(nlog⁑n)O(n \log n)","O(n2)O(n^2)","O(2n)O(2^n)"] answer="O(n2)O(n^2)" hint="Use the substitution method or expand the recurrence." solution="Step 1: Expand the recurrence.
> T(n)=T(nβˆ’1)+cnT(n) = T(n-1) + cn (for some constant cc)
> T(nβˆ’1)=T(nβˆ’2)+c(nβˆ’1)T(n-1) = T(n-2) + c(n-1)
> T(nβˆ’2)=T(nβˆ’3)+c(nβˆ’2)T(n-2) = T(n-3) + c(n-2)
> ...
> T(2)=T(1)+c(2)T(2) = T(1) + c(2)

Step 2: Substitute backwards.
> T(n)=T(nβˆ’2)+c(nβˆ’1)+cnT(n) = T(n-2) + c(n-1) + cn
> T(n)=T(nβˆ’3)+c(nβˆ’2)+c(nβˆ’1)+cnT(n) = T(n-3) + c(n-2) + c(n-1) + cn
> Continuing this pattern, we get:
> T(n)=T(1)+c(2)+c(3)+β‹―+c(nβˆ’1)+cnT(n) = T(1) + c(2) + c(3) + \cdots + c(n-1) + cn

Step 3: Sum the series.
> T(n)=O(1)+cβˆ‘i=2niT(n) = O(1) + c \sum_{i=2}^{n} i
> The sum βˆ‘i=2ni=n(n+1)2βˆ’1\sum_{i=2}^{n} i = \frac{n(n+1)}{2} - 1.

Step 4: Determine the asymptotic complexity.
> T(n)=O(1)+c(n2+n2βˆ’1)T(n) = O(1) + c \left( \frac{n^2 + n}{2} - 1 \right)
> T(n)=O(n2)T(n) = O(n^2).
Therefore, the overall time complexity is O(n2)O(n^2)."
:::

---

Problem-Solving Strategies

πŸ’‘ Analyzing Loops

For nested loops, multiply the number of iterations of each loop. For `for i=0 to n`, `for j=i to n`, sum an arithmetic series. For `for j=1; jO(log⁑n)O(\log n) times.

πŸ’‘ Master Theorem Checklist

  • Identify a,b,f(n)a, b, f(n) from T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n).

  • Calculate nlog⁑ban^{\log_b a}.

  • Compare f(n)f(n) with nlog⁑ban^{\log_b a} to determine which case applies.

  • If Case 3, verify the regularity condition af(n/b)≀cf(n)a f(n/b) \le c f(n) for c<1c < 1.

πŸ’‘ Reduction Implications

If A≀PBA \le_P B:
If B∈PB \in P, then A∈PA \in P.
If Aβˆ‰PA \notin P (e.g., AA is NP-hard and Pβ‰ NPP \ne NP), then Bβˆ‰PB \notin P.
* AA is 'no harder than' BB in polynomial time.

---

Common Mistakes

⚠️ Ignoring Constants in Asymptotic Notation

❌ Students sometimes include constants like T(n)=O(3n2)T(n) = O(3n^2) instead of O(n2)O(n^2).
βœ… Constants and lower-order terms are dropped in asymptotic notation. O(3n2+5n+10)=O(n2)O(3n^2 + 5n + 10) = O(n^2).

⚠️ Confusing Big-O with Theta

❌ Using Big-O (OO) when a tight bound (Θ\Theta) is appropriate, or vice-versa, especially when comparing functions.
βœ… f(n)=O(g(n))f(n) = O(g(n)) means ff grows no faster than gg. f(n)=Θ(g(n))f(n) = \Theta(g(n)) means ff grows at the same rate as gg. Be precise about upper, lower, and tight bounds.

⚠️ Incorrect Base Cases for Recurrences

❌ Assuming T(1)=1T(1)=1 or T(0)=1T(0)=1 always, without checking the problem context.
βœ… Always specify or derive the base case for recurrence relations. Incorrect base cases can lead to incorrect solutions, especially with the substitution method.

⚠️ Misinterpreting Reduction Direction

❌ If A≀PBA \le_P B, concluding that BB is in PP because AA is in PP.
βœ… A≀PBA \le_P B means BB is at least as hard as AA. So, if Aβˆ‰PA \notin P, then Bβˆ‰PB \notin P. If B∈PB \in P, then A∈PA \in P. The implication only goes one way for problem hardness.

---

Practice Questions

:::question type="MCQ" question="Which of the following functions grows fastest asymptotically?" options=["nlog⁑nn \log n","n1.5n^{1.5}","2log⁑n2^{\sqrt{\log n}}","(log⁑n)2(\log n)^2"] answer="n1.5n^{1.5}" hint="Compare the growth rates by taking logarithms or raising to powers to simplify comparison." solution="We need to compare the growth rates of the four functions.

  • f1(n)=nlog⁑nf_1(n) = n \log n

  • f2(n)=n1.5f_2(n) = n^{1.5}

  • f3(n)=2log⁑nf_3(n) = 2^{\sqrt{\log n}}
  • f4(n)=(log⁑n)2f_4(n) = (\log n)^2
  • Let's compare them:
    * n1.5n^{1.5} vs nlog⁑nn \log n: n1.5=nβ‹…n0.5=nnn^{1.5} = n \cdot n^{0.5} = n \sqrt{n}. Since n\sqrt{n} grows faster than log⁑n\log n, n1.5n^{1.5} grows faster than nlog⁑nn \log n.
    * n1.5n^{1.5} vs (log⁑n)2(\log n)^2: Any polynomial nkn^k (for k>0k>0) grows faster than any polylogarithmic function (log⁑n)p(\log n)^p. So n1.5n^{1.5} grows much faster than (log⁑n)2(\log n)^2.
    *n1.5n^{1.5} vs 2log⁑n2^{\sqrt{\log n}}**: To compare these, let k=log⁑nk = \log n, so n=2kn = 2^k.
    * n1.5=(2k)1.5=21.5kn^{1.5} = (2^k)^{1.5} = 2^{1.5k}
    * 2log⁑n=2k2^{\sqrt{\log n}} = 2^{\sqrt{k}}
    Since kk grows faster than k\sqrt{k} for large kk, 21.5k2^{1.5k} grows much faster than 2k2^{\sqrt{k}}.
    Therefore, n1.5n^{1.5} grows faster than 2log⁑n2^{\sqrt{\log n}}.

    Comparing all, n1.5n^{1.5} is the fastest growing function."
    :::

    :::question type="NAT" question="What is the result of the `count` variable after the execution of the following code for N=64N=64?" answer="321" hint="Analyze the inner loop's condition and increment, and then sum the iterations over the outer loop." solution="Step 1: Analyze the outer loop.
    The outer loop `for (int i = 1; i <= N; i++)` runs NN times. For N=64N=64, it runs 6464 times.

    Step 2: Analyze the inner loop.
    The inner loop `for (int j = 1; j < i; j = j * 2)` depends on the value of `i`.
    The variable `j` takes values 1,2,4,…,2k1, 2, 4, \ldots, 2^k such that 2k<i2^k < i.
    The number of iterations for the inner loop, for a given `i > 1`, is the number of powers of 2 strictly less than `i`. This is ⌊log⁑2(iβˆ’1)βŒ‹+1\lfloor \log_2 (i-1) \rfloor + 1.
    For i=1i=1, the inner loop condition `j < i` (i.e., `1 < 1`) is false, so it runs 0 times.

    Let's calculate the number of inner loop iterations for each `i` from 11 to 6464:
    * `i=1`: 0 iterations.
    * `i=2`: `j=1`. (1 iteration). ⌊log⁑2(1)βŒ‹+1=1\lfloor \log_2(1) \rfloor + 1 = 1.
    * `i=3`: `j=1,2`. (2 iterations). ⌊log⁑2(2)βŒ‹+1=2\lfloor \log_2(2) \rfloor + 1 = 2.
    * `i=4`: `j=1,2`. (2 iterations). ⌊log⁑2(3)βŒ‹+1=2\lfloor \log_2(3) \rfloor + 1 = 2.
    * `i=5`: `j=1,2,4`. (3 iterations). ⌊log⁑2(4)βŒ‹+1=3\lfloor \log_2(4) \rfloor + 1 = 3.
    * ...
    * `i=64`: `j=1,2,4,8,16,32`. (6 iterations). ⌊log⁑2(63)βŒ‹+1=6\lfloor \log_2(63) \rfloor + 1 = 6.

    Step 3: Sum the total `count`.
    We need to sum the number of inner loop iterations for each `i` from 11 to 6464.
    The number of times `k` iterations occur:
    * k=1k=1: for i=2i=2 (1 value)
    * k=2k=2: for i∈[3,4]i \in [3,4] (2 values)
    * k=3k=3: for i∈[5,8]i \in [5,8] (4 values)
    * k=4k=4: for i∈[9,16]i \in [9,16] (8 values)
    * k=5k=5: for i∈[17,32]i \in [17,32] (16 values)
    * k=6k=6: for i∈[33,64]i \in [33,64] (32 values)

    Total `count` = (1Γ—1)+(2Γ—2)+(3Γ—4)+(4Γ—8)+(5Γ—16)+(6Γ—32)(1 \times 1) + (2 \times 2) + (3 \times 4) + (4 \times 8) + (5 \times 16) + (6 \times 32)
    Total `count` = 1+4+12+32+80+1921 + 4 + 12 + 32 + 80 + 192
    Total `count` = 321321.

    ```c
    int calculate(int N) {
    int count = 0;
    for (int i = 1; i <= N; i++) {
    for (int j = 1; j < i; j = j * 2) {
    count++;
    }
    }
    return count;
    }
    ```"
    :::

    :::question type="MSQ" question="Which of the following statements are true about the relationship between PP and NPNP?" options=["If P=NPP=NP, then all problems in NPNP can be solved in polynomial time by a deterministic algorithm.","If an NP-complete problem can be solved in polynomial time, then P=NPP=NP.","Every problem in PP is also in NPNP.","Every problem in NPNP is also in PP."] answer="If P=NPP=NP, then all problems in NPNP can be solved in polynomial time by a deterministic algorithm.,If an NP-complete problem can be solved in polynomial time, then P=NPP=NP.,Every problem in PP is also in NPNP." hint="Recall the definitions of P, NP, and NP-completeness, and their known relationships." solution="Analysis of options:

    * If P=NPP=NP, then all problems in NPNP can be solved in polynomial time by a deterministic algorithm. This is true by definition. If P=NPP=NP, it means that the class of problems verifiable in polynomial time (NPNP) is equivalent to the class of problems solvable in polynomial time by a deterministic algorithm (PP).

    * If an NP-complete problem can be solved in polynomial time, then P=NPP=NP. This is true. If an NP-complete problem (which is by definition the 'hardest' problem in NP, in the sense that all problems in NP can be reduced to it) can be solved in polynomial time, then by applying the polynomial-time reduction, every problem in NP can also be solved in polynomial time. This implies NPβŠ†PNP \subseteq P. Since PβŠ†NPP \subseteq NP is always true, it would mean P=NPP=NP.

    * Every problem in PP is also in NPNP. This is true. If a problem can be solved in polynomial time by a deterministic algorithm (PP), then a solution can certainly be verified in polynomial time (we can just solve it and check if the solution is correct). Thus, PβŠ†NPP \subseteq NP.

    Every problem in NPNP is also in PP. This is the famous P=NPP=NP question. It is not known* to be true; it is an open problem in computer science. If this were true, it would imply P=NPP=NP.

    Thus, the first three statements are definitely true."
    :::

    :::question type="MCQ" question="What is the space complexity of a recursive function that calculates the nn-th Fibonacci number, F(n)=F(nβˆ’1)+F(nβˆ’2)F(n) = F(n-1) + F(n-2), using a standard recursive implementation without memoization?" options=["O(1)O(1)","O(log⁑n)O(\log n)","O(n)O(n)","O(n2)O(n^2)"] answer="O(n)O(n)" hint="Consider the maximum depth of the recursion call stack." solution="Step 1: Analyze the recursion depth.
    The standard recursive implementation of Fibonacci numbers (e.g., `fib(n) = fib(n-1) + fib(n-2)`) makes two recursive calls.
    The depth of the recursion stack is determined by the longest chain of calls.
    The longest chain of calls is `fib(n) -> fib(n-1) -> fib(n-2) -> ... -> fib(1)`.
    This chain has a depth proportional to nn.

    Step 2: Space per stack frame.
    Each recursive call adds a stack frame to the call stack. This frame stores local variables and the return address. Each stack frame consumes a constant amount of memory.

    Step 3: Total space complexity.
    Since the maximum depth of the recursion stack is O(n)O(n), and each stack frame takes O(1)O(1) space, the total auxiliary space complexity is O(n)Γ—O(1)=O(n)O(n) \times O(1) = O(n).
    "
    :::

    :::question type="MCQ" question="An algorithm has a time complexity described by the recurrence T(n)=4T(n/2)+n3T(n) = 4T(n/2) + n^3. What is its asymptotic time complexity?" options=["O(n2)O(n^2)","O(n2log⁑n)O(n^2 \log n)","O(n3)O(n^3)","O(n4)O(n^4)"] answer="O(n3)O(n^3)" hint="Apply the Master Theorem, comparing f(n)f(n) with nlog⁑ban^{\log_b a}." solution="Step 1: Identify a,b,a, b, and f(n)f(n).
    > a=4a = 4
    > b=2b = 2
    > f(n)=n3f(n) = n^3

    Step 2: Calculate nlog⁑ban^{\log_b a}.
    > nlog⁑24=n2n^{\log_2 4} = n^2.

    Step 3: Compare f(n)f(n) with nlog⁑ban^{\log_b a}.
    > f(n)=n3f(n) = n^3 and nlog⁑ba=n2n^{\log_b a} = n^2.
    > We observe that n3=Ξ©(n2+Ο΅)n^3 = \Omega(n^{2+\epsilon}) for Ο΅=1\epsilon = 1.
    > This matches Case 3 of the Master Theorem.

    Step 4: Check regularity condition.
    > We need to check if af(n/b)≀cf(n)a f(n/b) \le c f(n) for some constant c<1c < 1.
    > 4β‹…(n/2)3=4β‹…n3/8=n3/24 \cdot (n/2)^3 = 4 \cdot n^3/8 = n^3/2.
    > We need n3/2≀cn3n^3/2 \le c n^3. We can choose c=1/2<1c = 1/2 < 1. The condition holds.

    Step 5: Apply the Master Theorem result.
    > T(n)=Θ(f(n))=Θ(n3)T(n) = \Theta(f(n)) = \Theta(n^3).
    Therefore, the asymptotic time complexity is O(n3)O(n^3)."
    :::

    ---

    Summary

    ❗ Key Formulas & Takeaways

    |

    | Formula/Concept | Expression |

    |---|----------------|------------| | 1 | Big-O Notation (Upper Bound) | f(n)=O(g(n))β€…β€ŠβŸΊβ€…β€Šβˆƒc,n0>0:f(n)≀cβ‹…g(n)Β forΒ nβ‰₯n0f(n) = O(g(n)) \iff \exists c, n_0 > 0: f(n) \le c \cdot g(n) \text{ for } n \ge n_0 | | 2 | Omega Notation (Lower Bound) | f(n)=Ξ©(g(n))β€…β€ŠβŸΊβ€…β€Šβˆƒc,n0>0:cβ‹…g(n)≀f(n)Β forΒ nβ‰₯n0f(n) = \Omega(g(n)) \iff \exists c, n_0 > 0: c \cdot g(n) \le f(n) \text{ for } n \ge n_0 | | 3 | Theta Notation (Tight Bound) | f(n)=Θ(g(n))β€…β€ŠβŸΊβ€…β€Šβˆƒc1,c2,n0>0:c1g(n)≀f(n)≀c2g(n)Β forΒ nβ‰₯n0f(n) = \Theta(g(n)) \iff \exists c_1, c_2, n_0 > 0: c_1 g(n) \le f(n) \le c_2 g(n) \text{ for } n \ge n_0 | | 4 | Master Theorem | For T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n): Cases based on comparing f(n)f(n) with nlog⁑ban^{\log_b a} | | 5 | P vs NP | PβŠ†NPP \subseteq NP. P=NPP=NP is an open question. | | 6 | Polynomial Reduction (A≀PBA \le_P B) | If B∈PB \in P, then A∈PA \in P. If Aβˆ‰PA \notin P, then Bβˆ‰PB \notin P. |

    ---

    What's Next?

    πŸ’‘ Continue Learning

    This topic connects to:

      • Algorithm Design Paradigms: Understanding time and space complexity is crucial for evaluating algorithms designed using greedy, divide-and-conquer, dynamic programming, or backtracking approaches.

      • Data Structures: The choice of data structure directly impacts the time and space complexity of operations performed on it.

      • Approximation Algorithms: For NP-hard problems, where exact polynomial-time solutions are unlikely, approximation algorithms provide near-optimal solutions with guaranteed polynomial time complexity.

    ---

    πŸ’‘ Next Up

    Proceeding to Best, Worst, and Average Case.

    ---

    Part 2: Best, Worst, and Average Case

    Algorithm analysis often requires evaluating performance across various input scenarios to understand its practical implications. We define best, worst, and average cases to characterize an algorithm's efficiency bounds.

    ---

    Core Concepts

    1. Best Case Analysis

    We define the best case of an algorithm as the scenario where it performs the minimum number of operations for a given input size nn. This represents the most favorable input.

    Worked Example: Linear Search

    Consider an algorithm `LinearSearch(A, x)` that searches for an element xx in an array AA of size nn.

    Step 1: Define the algorithm

    ```
    function LinearSearch(A, x):
    n = length(A)
    for i from 1 to n:
    if A[i] == x:
    return i // Element found
    return -1 // Element not found
    ```

    Step 2: Identify the best-case input

    The best case occurs when the target element xx is found at the first position of the array. The loop executes only once.

    >

    NumberΒ ofΒ comparisons=1\text{Number of comparisons} = 1

    Answer: The best-case time complexity for Linear Search is O(1)O(1).

    :::question type="MCQ" question="For a sorting algorithm that checks if an array is already sorted before performing any major sorting operations, what is the best-case time complexity if the input array is already sorted?" options=["O(1)O(1)","O(log⁑n)O(\log n)","O(n)O(n)","O(nlog⁑n)O(n \log n)"] answer="O(n)O(n)" hint="Checking if an array of size nn is sorted requires iterating through all elements once." solution="Step 1: Analyze the 'check sorted' operation.
    To verify if an array AA of size nn is sorted, we must iterate from A[1]A[1] to A[nβˆ’1]A[n-1] and check if A[i]≀A[i+1]A[i] \le A[i+1] for all ii. This takes O(n)O(n) time.

    Step 2: Determine the total complexity.
    If the array is already sorted, the algorithm performs this O(n)O(n) check and then terminates without further sorting.

    >

    BestΒ CaseΒ Complexity=O(n)\text{Best Case Complexity} = O(n)

    "
    :::

    ---

    2. Worst Case Analysis

    We define the worst case as the scenario where an algorithm performs the maximum number of operations for a given input size nn. This provides an upper bound on the algorithm's runtime.

    Worked Example 1: Linear Search

    Consider the `LinearSearch(A, x)` algorithm.

    Step 1: Identify the worst-case input

    The worst case occurs when the target element xx is either at the last position of the array or not present in the array at all. The loop iterates through all nn elements.

    >

    NumberΒ ofΒ comparisons=n\text{Number of comparisons} = n

    Answer: The worst-case time complexity for Linear Search is O(n)O(n).

    Worked Example 2: Recursive Selection Algorithm (Inspired by PYQ 3 & 4)

    Consider the `mystery` function which attempts to find the kk-th smallest element in an array AA.

    ```
    function mystery(A, k) {
    n = length(A);
    if (k > n) return A[n];

    v = A[1]; // Pivot is always the first element
    AL = [ A[j] : 1 <= j <= n, A[j] < v ];
    AV = [ A[j] : 1 <= j <= n, A[j] == v ];
    AR = [ A[j] : 1 <= j <= n, A[j] > v ];

    if (length(AL) >= k) return mystery(AL, k);
    if (length(AL) + length(AV) > k) return v;
    return mystery(AR, k - (length(AL) + length(AV)));
    }
    ```

    Step 1: Analyze the operations at each step.

    At each recursive call, the algorithm scans the entire current array to partition it into `AL`, `AV`, and `AR`. This partitioning takes O(m)O(m) time, where mm is the length of the current array.

    Step 2: Identify the worst-case input for the pivot choice.

    The worst case occurs when the pivot v=A[1]v=A[1] is consistently chosen as the smallest or largest element in the array. This leads to highly unbalanced partitions.

    Consider A=[1,2,3,…,n]A = [1, 2, 3, \dots, n] and we search for k=nk=n.

    • First call: v=1v=1. `AL` is empty, `AV` contains `[1]`, `AR` contains `[2, 3, \dots, n]`.

    • The recursive call is `mystery(AR, n-1)`, where `AR` has size nβˆ’1n-1.

    • This pattern continues, with the array size decreasing by only one element in each recursive call.


    Step 3: Formulate the recurrence relation.

    Let T(n)T(n) be the time complexity for an input of size nn. In the worst case, the partitioning takes O(n)O(n) and the recursive call is made on an array of size nβˆ’1n-1.

    >

    T(n)=T(nβˆ’1)+O(n)T(n) = T(n-1) + O(n)

    Step 4: Solve the recurrence relation.

    >

    T(n)=n+(nβˆ’1)+(nβˆ’2)+β‹―+1=βˆ‘i=1ni=n(n+1)2\begin{aligned} T(n) & = n + (n-1) + (n-2) + \cdots + 1 \\ & = \sum_{i=1}^{n} i \\ & = \frac{n(n+1)}{2} \end{aligned}

    Answer: The worst-case time complexity is O(n2)O(n^2). An example worst-case input is an already sorted array A=[1,2,…,n]A = [1, 2, \dots, n] searching for the nn-th element, or a reverse-sorted array A=[n,nβˆ’1,…,1]A = [n, n-1, \dots, 1] searching for the 1st element.

    :::question type="MCQ" question="Consider a search algorithm for an nΓ—nn \times n matrix AA where each row and column is sorted in ascending order. The algorithm starts at A[1,n]A[1,n] (top-right corner) and searches for kk. If A[i,j]=kA[i,j] = k, it returns (i,j)(i,j). If A[i,j]<kA[i,j] < k, it moves down to A[i+1,j]A[i+1,j]. If A[i,j]>kA[i,j] > k, it moves left to A[i,jβˆ’1]A[i,j-1]. What is a worst-case input for this algorithm if kk is present?" options=["kk is at A[1,1]A[1,1]","kk is at A[n,n]A[n,n]","kk is at A[1,n]A[1,n]","kk is at A[n,1]A[n,1]"] answer="kk is at A[n,1]A[n,1]" hint="Analyze the movement pattern. To reach A[n,1]A[n,1] from A[1,n]A[1,n], the algorithm must traverse the maximum number of rows and columns." solution="Step 1: Understand the search strategy.
    Starting at (1,n)(1,n):

    • If current element is less than kk, move down (increase row index).

    • If current element is greater than kk, move left (decrease column index).

    • If current element equals kk, found.


    Step 2: Identify the path for maximum operations.
    To maximize operations, the algorithm should be forced to traverse as many rows and columns as possible.
    • To move down nβˆ’1n-1 times, kk must be greater than or equal to elements in A[1,j],A[2,j],…,A[nβˆ’1,j]A[1,j], A[2,j], \dots, A[n-1,j].

    • To move left nβˆ’1n-1 times, kk must be less than or equal to elements in A[i,n],A[i,nβˆ’1],…,A[i,2]A[i,n], A[i,n-1], \dots, A[i,2].


    Consider kk at A[n,1]A[n,1].
    The algorithm starts at A[1,n]A[1,n]. To reach A[n,1]A[n,1], it must make nβˆ’1n-1 'down' moves and nβˆ’1n-1 'left' moves. This requires 2nβˆ’22n-2 comparisons in the worst case. For example, if all elements in the first column are less than kk, it will move down until A[n,n]A[n,n]. Then, if A[n,j]>kA[n,j] > k for j>1j > 1, it will move left until A[n,1]A[n,1]. This path covers the maximum number of steps.

    >

    Worst-caseΒ positionΒ forΒ k=A[n,1]\text{Worst-case position for } k = A[n,1]

    >
    NumberΒ ofΒ stepsΒ inΒ worstΒ case=O(n)\text{Number of steps in worst case} = O(n)

    "
    :::

    ---

    3. Average Case Analysis

    We define the average case as the expected number of operations for a given input size nn, assuming a specific probability distribution over all possible inputs. This requires probabilistic analysis.

    πŸ“ Expected Value of Time Complexity
    E[T(n)]=βˆ‘I∈InT(I)β‹…P(I)E[T(n)] = \sum_{I \in \mathcal{I}_n} T(I) \cdot P(I)

    Where:

      • E[T(n)]E[T(n)] = Expected time complexity for inputs of size nn

      • In\mathcal{I}_n = Set of all possible inputs of size nn

      • T(I)T(I) = Time complexity for a specific input II

      • P(I)P(I) = Probability of input II occurring

    When to use: When a probability distribution over inputs can be reasonably assumed, to get a more realistic performance measure than worst-case.

    Worked Example: Linear Search (Average Case)

    Consider `LinearSearch(A, x)` on an array AA of size nn. We assume the following:

  • The element xx is present in the array with probability pp.

  • If xx is present, it is equally likely to be at any of the nn positions (i.e., probability 1/n1/n for each position).

  • If xx is not present (probability 1βˆ’p1-p), the algorithm performs nn comparisons.
  • Step 1: Calculate the expected number of comparisons if xx is present.

    If xx is at position ii, it takes ii comparisons.
    The probability of xx being at position ii given it's present is 1/n1/n.

    >

    E[comparisons∣xΒ present]=βˆ‘i=1niβ‹…1n=1nβˆ‘i=1ni=1nβ‹…n(n+1)2=n+12\begin{aligned} E[\text{comparisons} | x \text{ present}] & = \sum_{i=1}^{n} i \cdot \frac{1}{n} \\ & = \frac{1}{n} \sum_{i=1}^{n} i \\ & = \frac{1}{n} \cdot \frac{n(n+1)}{2} \\ & = \frac{n+1}{2} \end{aligned}

    Step 2: Calculate the total average number of comparisons.

    >

    E[T(n)]=P(xΒ present)β‹…E[comparisons∣xΒ present]+P(xΒ notΒ present)β‹…E[comparisons∣xΒ notΒ present]=pβ‹…n+12+(1βˆ’p)β‹…n\begin{aligned} E[T(n)] & = P(x \text{ present}) \cdot E[\text{comparisons} | x \text{ present}] + P(x \text{ not present}) \cdot E[\text{comparisons} | x \text{ not present}] \\ & = p \cdot \frac{n+1}{2} + (1-p) \cdot n \end{aligned}

    Answer: The average-case time complexity is O(n)O(n). For p=1p=1 (always present), it's O(n/2)=O(n)O(n/2) = O(n). For p=0p=0 (never present), it's O(n)O(n).

    :::question type="NAT" question="A hash table uses chaining to resolve collisions. The load factor is Ξ±=N/M\alpha = N/M, where NN is the number of items and MM is the number of slots. Assuming simple uniform hashing, what is the average number of probes (comparisons) for an unsuccessful search?" answer="alpha" hint="In simple uniform hashing, each item is equally likely to be hashed into any slot. An unsuccessful search must traverse the entire chain at the hashed slot." solution="Step 1: Understand simple uniform hashing and unsuccessful search.
    Simple uniform hashing implies that any given item is equally likely to hash into any of the MM slots, independently of where other items hash.
    For an unsuccessful search, we hash the key to a slot jj. If slot jj has a chain of length LjL_j, we must traverse all LjL_j elements in that chain to confirm the key is not present.

    Step 2: Calculate the expected chain length.
    The expected length of a chain at any given slot jj is the total number of items NN divided by the total number of slots MM. This is the definition of the load factor Ξ±\alpha.

    >

    E[Lj]=NM=Ξ±E[L_j] = \frac{N}{M} = \alpha

    Step 3: Determine the average probes.
    Since an unsuccessful search must traverse the entire chain at its hashed slot, the average number of probes is equal to the average chain length.

    >

    AverageΒ probesΒ forΒ unsuccessfulΒ search=Ξ±\text{Average probes for unsuccessful search} = \alpha

    "
    :::

    ---

    Advanced Applications

    1. Concurrent Execution Outcomes

    When multiple processes access and modify shared variables concurrently, the final state can depend on the interleaving of operations. We analyze best (minimum) and worst (maximum) possible outcomes by considering all valid execution schedules.

    Worked Example: Shared Variable Update (Inspired by PYQ 1)

    Consider two procedures, `proc1` and `proc2`, running in parallel. `x` is a shared variable initialized to 00.

    ```c
    int x = 0;

    proc1 {
    int temp1 = x;
    x = temp1 + 1;
    temp1 = x;
    x = temp1 + 1;
    }

    proc2 {
    int temp2 = x;
    x = temp2 + 1;
    }
    ```

    Step 1: Analyze `proc1` operations without interference.

    If `proc1` runs alone:

  • `temp1 = x;` (temp1 = 0)

  • `x = temp1 + 1;` (x = 1)

  • `temp1 = x;` (temp1 = 1)

  • `x = temp1 + 1;` (x = 2)

  • Final `x = 2`.

    Step 2: Analyze `proc2` operations without interference.

    If `proc2` runs alone:

  • `temp2 = x;` (temp2 = 0)

  • `x = temp2 + 1;` (x = 1)

  • Final `x = 1`.

    Step 3: Identify the minimum possible value for `x`.

    To get the minimum value, we want `temp` variables to read `x` when it is as small as possible, and then for updates to overwrite each other.

    Consider `proc1` reads `x` (0), then `proc2` reads `x` (0), then both write back.

    > Interleaving for Minimum `x`:
    >
    > 1. `proc1`: `temp1 = x;` (temp1=0\text{temp1}=0)
    > 2. `proc2`: `temp2 = x;` (temp2=0\text{temp2}=0)
    > 3. `proc1`: `x = temp1 + 1;` (x=1x=1)
    > 4. `proc2`: `x = temp2 + 1;` (x=1x=1)
    > 5. `proc1`: `temp1 = x;` (temp1=1\text{temp1}=1)
    > 6. `proc1`: `x = temp1 + 1;` (x=2x=2)

    In this interleaving, `x` becomes 2. This is not the minimum. A smaller value can be achieved if `proc2`'s `x = temp2 + 1` overwrites `proc1`'s first increment before `proc1` reads `x` again.

    > Revised Interleaving for Minimum `x`:
    >
    > 1. `proc1`: `temp1 = x;` (temp1=0\text{temp1}=0)
    > 2. `proc2`: `temp2 = x;` (temp2=0\text{temp2}=0)
    > 3. `proc2`: `x = temp2 + 1;` (x=1x=1)
    > 4. `proc1`: `x = temp1 + 1;` (x=1x=1) // `proc1` writes 1, overwriting `proc2`'s 1.
    > 5. `proc1`: `temp1 = x;` (temp1=1\text{temp1}=1)
    > 6. `proc1`: `x = temp1 + 1;` (x=2x=2)

    In this scenario, `x` becomes 2. Let's trace more carefully to find a smaller value. The key is when a `temp` variable reads an outdated `x`.

    > Minimum possible `x = 1`:
    >
    > 1. `proc1`: `temp1 = x;` (temp1=0\text{temp1}=0)
    > 2. `proc1`: `x = temp1 + 1;` (x=1x=1)
    > 3. `proc2`: `temp2 = x;` (temp2=1\text{temp2}=1)
    > 4. `proc2`: `x = temp2 + 1;` (x=2x=2)
    > 5. `proc1`: `temp1 = x;` (temp1=2\text{temp1}=2)
    > 6. `proc1`: `x = temp1 + 1;` (x=3x=3)
    >
    > This gives 3. The minimum occurs if one process's final write is based on an old value.

    > Correct Minimum `x = 1`:
    >
    > 1. `proc1`: `temp1 = x;` (temp1=0\text{temp1}=0)
    > 2. `proc2`: `temp2 = x;` (temp2=0\text{temp2}=0)
    > 3. `proc1`: `x = temp1 + 1;` (x=1x=1)
    > 4. `proc1`: `temp1 = x;` (temp1=1\text{temp1}=1)
    > 5. `proc1`: `x = temp1 + 1;` (x=2x=2)
    > 6. `proc2`: `x = temp2 + 1;` (x=1x=1) // `proc2` writes 1, based on its initial read of 0. This is the last operation.

    Step 4: Identify the maximum possible value for `x`.

    To get the maximum value, we want each increment to be based on the most up-to-date value of `x`. This means allowing one process to fully complete its increments, then the other.

    > Interleaving for Maximum `x = 3`:
    >
    > 1. `proc1` fully executes:
    > - `temp1 = x;` (temp1=0\text{temp1}=0)
    > - `x = temp1 + 1;` (x=1x=1)
    > - `temp1 = x;` (temp1=1\text{temp1}=1)
    > - `x = temp1 + 1;` (x=2x=2)
    > 2. `proc2` fully executes:
    > - `temp2 = x;` (temp2=2\text{temp2}=2)
    > - `x = temp2 + 1;` (x=3x=3)

    Answer: The possible values for xx are 1,2,31, 2, 3.
    Minimum possible value for `x` is 11.
    Maximum possible value for `x` is 33.

    :::question type="MCQ" question="Consider x=0x=0. `procA` performs `x = x + 1; x = x + 1;`. `procB` performs `x = x + 1;`. Both run concurrently. Which of the following values are possible for xx after both processes halt?" options=["1","2","3","4"] answer="2,3" hint="Trace interleavings. Identify the minimum and maximum possible outcomes. A value of 1 implies one of the increments was completely lost, which is not possible with these operations." solution="Step 1: Analyze `procA` and `procB` independently.
    `procA` intends to add 2 to xx.
    `procB` intends to add 1 to xx.
    Total intended increments: 3.

    Step 2: Determine the minimum possible value.
    A common way to get a minimum value is if a `read-modify-write` sequence is interrupted, and an older value is written back, effectively losing an increment.

    • Start: x=0x=0

    • `procA`: `x = x + 1;` (x=1x=1)

    • `procB`: `x = x + 1;` (x=2x=2)

    • `procA`: `x = x + 1;` (x=3x=3)

    This is 3.
    Consider:
    • `procA` reads x=0x=0.

    • `procB` reads x=0x=0.

    • `procA` writes x=1x=1.

    • `procA` reads x=1x=1.

    • `procB` writes x=1x=1. // `procB`'s write based on x=0x=0 overwrites `procA`'s previous write.

    • `procA` writes x=2x=2.

    Final x=2x=2. This is the minimum.

    Step 3: Determine the maximum possible value.
    The maximum value occurs when all increments are applied sequentially without any overwrites based on stale reads.

    • `procA` fully executes: xβ†’0β†’1β†’2x \to 0 \to 1 \to 2.

    • Then `procB` executes: xβ†’2β†’3x \to 2 \to 3.

    Final x=3x=3.

    Step 4: List all possible values.
    The possible values are 22 and 33.

    >

    PossibleΒ valuesΒ forΒ x:{2,3}\text{Possible values for } x: \{2, 3\}

    "
    :::

    2. Amortized Analysis

    We use amortized analysis to analyze the performance of a sequence of operations, where a single operation might be expensive, but the average cost over a long sequence of operations is low. It provides a worst-case guarantee on the average performance per operation.

    Worked Example: Dynamic Array (Vector) Append Operation

    Consider a dynamic array that doubles its capacity when it runs out of space. Appending an element usually takes O(1)O(1) time, but when a reallocation occurs, it takes O(N)O(N) time, where NN is the current number of elements.

    Step 1: Analyze the cost of a sequence of NN `append` operations.

    Let's start with an empty array of capacity 1.

    • `append(1)`: Cost 1 (copy 0 elements, add 1). Capacity 1 -> 2.

    • `append(2)`: Cost 1 (add 1). Capacity 2.

    • `append(3)`: Cost 3 (copy 2 elements, add 1). Capacity 2 -> 4.

    • `append(4)`: Cost 1 (add 1). Capacity 4.

    • `append(5)`: Cost 5 (copy 4 elements, add 1). Capacity 4 -> 8.


    The reallocations occur when the number of elements reaches 2k+12^k+1.
    The cost for NN appends is the sum of costs for individual appends.
    The costs for reallocations are 11 (for capacity 1 to 2), 22 (for capacity 2 to 4), 44 (for capacity 4 to 8), …\dots, 2k2^k (for capacity 2k2^k to 2k+12^{k+1}).
    The total cost for NN appends (where N=2kN = 2^k) would be approximately:

    >

    TotalΒ Cost=βˆ‘i=0kβˆ’12i+N=(2kβˆ’1)+N\text{Total Cost} = \sum_{i=0}^{k-1} 2^i + N = (2^k - 1) + N

    Since N=2kN=2^k, the sum is Nβˆ’1+N=2Nβˆ’1N-1+N = 2N-1. More accurately, for NN appends, the last reallocation might not be fully accounted for by this sum.
    A more general summation for NN elements: 1+2+4+β‹―+2⌊log⁑2(Nβˆ’1)βŒ‹+(NΒ -Β numberΒ ofΒ reallocations)1 + 2 + 4 + \dots + 2^{\lfloor \log_2 (N-1) \rfloor} + (\text{N - number of reallocations}).
    The total cost for NN appends is roughly N+βˆ‘j=1log⁑N2jβˆ’1N + \sum_{j=1}^{\log N} 2^{j-1}. This sum is N+(Nβˆ’1)β‰ˆ2NN + (N-1) \approx 2N.

    Step 2: Calculate the amortized cost.

    The total cost for NN appends is O(N)O(N).

    >

    AmortizedΒ CostΒ perΒ operation=TotalΒ CostNumberΒ ofΒ Operations=O(N)N=O(1)\text{Amortized Cost per operation} = \frac{\text{Total Cost}}{\text{Number of Operations}} = \frac{O(N)}{N} = O(1)

    Answer: The amortized time complexity of the `append` operation for a dynamic array is O(1)O(1).

    :::question type="MCQ" question="A stack supports `PUSH(x)` (cost 1) and `MULTIPOP(k)` (pops kk elements or until empty, cost kk). What is the amortized cost of a `MULTIPOP` operation over a sequence of NN operations?" options=["O(1)O(1)","O(log⁑N)O(\log N)","O(N)O(N)","O(N2)O(N^2)"] answer="O(1)O(1)" hint="Consider the total number of elements pushed and popped across the entire sequence of operations. Each element can be pushed once and popped once." solution="Step 1: Use the aggregate method for amortized analysis.
    We want to find the total cost of a sequence of NN operations and then divide by NN.

    Step 2: Analyze the cost of `PUSH` and `MULTIPOP`.

    • `PUSH(x)`: Adds one element. Cost is 1.

    • `MULTIPOP(k)`: Removes up to kk elements. The cost is the number of elements actually popped.


    Step 3: Determine the total maximum cost for NN operations.
    Each element can be pushed onto the stack exactly once.
    Each element can be popped from the stack exactly once.
    Therefore, the total number of `PUSH` operations is at most NN.
    The total number of elements popped across all `MULTIPOP` operations cannot exceed the total number of elements pushed.
    So, if there are NN operations in total, the maximum total cost for all `PUSH` operations is NN. The maximum total cost for all `MULTIPOP` operations is also NN (since each element is popped at most once).

    >

    TotalΒ CostΒ forΒ NΒ operations≀N(forΒ pushes)+N(forΒ pops)=2N\text{Total Cost for } N \text{ operations} \le N (\text{for pushes}) + N (\text{for pops}) = 2N

    Step 4: Calculate the amortized cost.

    >

    AmortizedΒ CostΒ perΒ operation=TotalΒ CostN=O(N)N=O(1)\text{Amortized Cost per operation} = \frac{\text{Total Cost}}{N} = \frac{O(N)}{N} = O(1)

    Answer: The amortized cost of a `MULTIPOP` operation is O(1)O(1)."
    :::

    ---

    Problem-Solving Strategies

    πŸ’‘ Identifying Worst-Case Inputs

    To find a worst-case input, think adversarially. What input would force the algorithm to perform the maximum number of operations? For recursive algorithms, consider inputs that lead to the most unbalanced recursive calls (e.g., already sorted arrays for QuickSort, or a pivot that is always the smallest/largest). For search algorithms, consider elements at the very end or not present.

    πŸ’‘ Average Case Calculation

    Average case analysis requires a clear definition of the probability distribution of inputs. If not given, make a reasonable assumption (e.g., uniform distribution) and state it. The calculation often involves summing costs weighted by their probabilities.

    πŸ’‘ Concurrent Min/Max Outcomes

    For concurrent programs, identify all memory accesses (reads and writes) to shared variables. To find the minimum or maximum possible outcome, trace extreme interleavings:

      • Minimum: Schedule reads before writes, or allow one process to overwrite another's increment with an older value.

      • Maximum: Schedule processes to complete their increments sequentially, or ensure reads always see the most updated values.

    ---

    Common Mistakes

    ⚠️ Confusing Average and Worst Case

    ❌ Students often assume average case is "typically what happens" and don't calculate it rigorously, or confuse it with the best case.
    βœ… Worst case provides an upper bound guarantee. Average case provides expected performance under specific input distributions. Both are distinct and require different analytical approaches.

    ⚠️ Misidentifying Worst-Case for Recursive Algorithms

    ❌ For algorithms like QuickSort, assuming a random pivot always leads to good performance, or not recognizing that a fixed pivot choice (e.g., first element) can lead to O(N2)O(N^2) worst-case on specific inputs.
    βœ… Always analyze the pivot selection strategy. If it's deterministic, identify the input that consistently forces the worst pivot. If it's randomized, the worst-case expected time might be better, but a worst-case input still exists for a specific run.

    ⚠️ Incorrectly Handling Concurrent Variable Updates

    ❌ Assuming that `x = x + 1` is an atomic operation.
    βœ… `x = x + 1` is typically `read x`, `increment x`, `write x`. Each of these sub-operations can be interleaved, leading to race conditions and unexpected outcomes. Always break down composite operations into atomic reads and writes.

    ---

    Practice Questions

    :::question type="MCQ" question="Consider the following algorithm for finding the maximum element in an array AA of NN integers.
    ```
    function FindMax(A, N):
    if N == 0: return null
    max_val = A[1]
    for i from 2 to N:
    if A[i] > max_val:
    max_val = A[i]
    return max_val
    ```
    What is the best-case number of comparisons performed by this algorithm?" options=["1","Nβˆ’1N-1","NN","2N2N"] answer="Nβˆ’1N-1" hint="The best case for this algorithm is not about early exit but about minimizing assignments to `max_val`. However, the number of comparisons remains constant for a given NN." solution="Step 1: Analyze the operations.
    The algorithm initializes `max_val` with `A[1]`.
    The loop runs from i=2i=2 to NN, performing one comparison `A[i] > max_val` in each iteration.
    This loop executes Nβˆ’1N-1 times.

    Step 2: Determine best case.
    The number of comparisons (Nβˆ’1N-1) is fixed regardless of the input array, as the loop always runs completely. The best case for this algorithm would be minimizing the number of assignments to `max_val`, which happens if the array is sorted in descending order (e.g., `[10, 9, 8, ..., 1]`). However, the question asks for comparisons, which is constant.

    >

    Best-caseΒ comparisons=Nβˆ’1\text{Best-case comparisons} = N-1

    "
    :::

    :::question type="NAT" question="A binary search algorithm takes O(log⁑N)O(\log N) time in the worst case. If we are searching for an element in a sorted array of NN elements, and the element is guaranteed to be present, what is the maximum number of comparisons (including the final equality check) required to find the element?" answer="floor(log2(N)) + 1" hint="In a binary search, each comparison halves the search space. The number of comparisons is related to the depth of the binary search tree." solution="Step 1: Understand binary search comparisons.
    In binary search, each comparison eliminates half of the remaining search space. The maximum number of comparisons corresponds to traversing a path from the root to a leaf in a balanced binary search tree of NN nodes.

    Step 2: Relate to tree height.
    The height of a perfectly balanced binary tree with NN nodes is ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.
    The number of comparisons is the number of nodes visited on the path from the root to the target element.
    If the element is guaranteed to be found, it will be found at some depth. The maximum depth is ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.
    A node at depth dd requires d+1d+1 comparisons (including the comparison at the node itself).
    The root is at depth 0. A leaf is at depth ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.

    Step 3: Calculate maximum comparisons.
    The maximum number of comparisons occurs when the element is found at a leaf node (maximum depth).
    If N=1N=1, ⌊log⁑21βŒ‹+1=0+1=1\lfloor \log_2 1 \rfloor + 1 = 0 + 1 = 1.
    If N=2N=2, ⌊log⁑22βŒ‹+1=1+1=2\lfloor \log_2 2 \rfloor + 1 = 1 + 1 = 2.
    If N=3N=3, ⌊log⁑23βŒ‹+1=1+1=2\lfloor \log_2 3 \rfloor + 1 = 1 + 1 = 2. (e.g., for [1,2,3], search for 3: check 2, then check 3)
    If N=7N=7, ⌊log⁑27βŒ‹+1=2+1=3\lfloor \log_2 7 \rfloor + 1 = 2 + 1 = 3.
    If N=8N=8, ⌊log⁑28βŒ‹+1=3+1=4\lfloor \log_2 8 \rfloor + 1 = 3 + 1 = 4.

    >

    MaximumΒ comparisons=⌊log⁑2NβŒ‹+1\text{Maximum comparisons} = \lfloor \log_2 N \rfloor + 1

    "
    :::

    :::question type="MCQ" question="Consider a queue implemented using a circular array of fixed size MM. The `ENQUEUE` operation adds an element to the rear, and `DEQUEUE` removes from the front. If the queue is full, `ENQUEUE` fails. If the queue is empty, `DEQUEUE` fails. What is the worst-case time complexity for a single `ENQUEUE` operation?" options=["O(1)O(1)","O(log⁑M)O(\log M)","O(M)O(M)","O(M2)O(M^2)"] answer="O(1)O(1)" hint="In a circular array implementation, `ENQUEUE` typically involves updating pointers and placing an element, which are constant time operations." solution="Step 1: Analyze the `ENQUEUE` operation in a circular array.
    A circular array queue maintains `front` and `rear` pointers (or indices).
    To `ENQUEUE`:

  • Check if the queue is full (e.g., `(rear + 1) % M == front`).

  • If not full, increment `rear` (modulo MM).

  • Place the new element at `array[rear]`.

  • These operations (comparison, arithmetic, assignment) take constant time.

    Step 2: Determine worst-case.
    The worst case for `ENQUEUE` occurs when it has to check if the queue is full. This check is also a constant-time operation. No resizing or shifting of elements occurs in a fixed-size circular array.

    >

    Worst-caseΒ timeΒ complexity=O(1)\text{Worst-case time complexity} = O(1)

    "
    :::

    :::question type="MSQ" question="Which of the following statements about worst-case analysis are true?" options=["Worst-case analysis provides an upper bound on an algorithm's running time.","The worst-case input for an algorithm is always unique.","Worst-case analysis is useful for real-time systems where performance guarantees are critical.","An algorithm's worst-case time complexity can be better than its best-case time complexity."] answer="Worst-case analysis provides an upper bound on an algorithm's running time.,Worst-case analysis is useful for real-time systems where performance guarantees are critical." hint="Consider the definitions and applications of worst-case analysis. Think about scenarios where guarantees are paramount." solution="Option 1: Worst-case analysis provides an upper bound on an algorithm's running time.
    βœ… This is true by definition. The worst case describes the maximum time an algorithm will take for any input of a given size.

    Option 2: The worst-case input for an algorithm is always unique.
    ❌ This is false. For many algorithms, multiple distinct inputs can trigger the worst-case behavior. For example, for linear search, if the element is not present, any array where the element is absent is a worst-case input.

    Option 3: Worst-case analysis is useful for real-time systems where performance guarantees are critical.
    βœ… This is true. In real-time systems, it's crucial to know the absolute maximum time an operation might take to ensure deadlines are met. Average-case performance is insufficient here.

    Option 4: An algorithm's worst-case time complexity can be better than its best-case time complexity.
    ❌ This is false. By definition, the worst case represents the maximum operations, while the best case represents the minimum operations. The worst-case complexity can never be 'better' (i.e., faster, or lower complexity class) than the best-case complexity.

    >

    CorrectΒ statements:\text{Correct statements:}

    >
    Worst-caseΒ analysisΒ providesΒ anΒ upperΒ boundΒ onΒ anΒ algorithm’sΒ runningΒ time.\text{Worst-case analysis provides an upper bound on an algorithm's running time.}

    >
    Worst-caseΒ analysisΒ isΒ usefulΒ forΒ real-timeΒ systemsΒ whereΒ performanceΒ guaranteesΒ areΒ critical.\text{Worst-case analysis is useful for real-time systems where performance guarantees are critical.}

    "
    :::

    :::question type="MCQ" question="Consider a hash table using open addressing with linear probing. The table size is MM. We want to insert NN distinct keys, where N<MN < M. What is the average-case number of probes for an insertion, assuming simple uniform hashing and that the table is not full?" options=["O(1)O(1)","O(log⁑M)O(\log M)","O(N)O(N)","O(M)O(M)"] answer="O(1)O(1)" hint="For open addressing with linear probing, the average-case performance is usually expressed in terms of the load factor α=N/M\alpha = N/M. When α\alpha is small (e.g., constant), the expected probes are constant." solution="Step 1: Define the load factor.
    The load factor Ξ±=N/M\alpha = N/M represents the fraction of the hash table that is occupied.

    Step 2: Analyze linear probing performance.
    For open addressing with linear probing, the expected number of probes for an unsuccessful search (which is similar to an insertion, as it probes until an empty slot is found) is approximately 1/(1βˆ’Ξ±)21/(1-\alpha)^2.

    Step 3: Evaluate average case for N<MN < M.
    Since N<MN < M, the load factor Ξ±<1\alpha < 1. If we consider a scenario where NN is much smaller than MM (e.g., Ξ±\alpha is a small constant like 0.50.5), then 1/(1βˆ’Ξ±)21/(1-\alpha)^2 becomes a constant.
    For example, if Ξ±=0.5\alpha = 0.5, expected probes β‰ˆ1/(0.5)2=4\approx 1/(0.5)^2 = 4.
    Thus, for a constant load factor (i.e., NN is proportional to MM), the average number of probes is constant.

    >

    Average-caseΒ numberΒ ofΒ probes=O(1)Β (whenΒ Ξ±Β isΒ constant)\text{Average-case number of probes} = O(1) \text{ (when } \alpha \text{ is constant)}

    "
    :::

    ---

    Summary

    ❗ Key Formulas & Takeaways

    |

    | Concept | Description | Time Complexity |

    |---|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Best, Worst, and Average Case

    Algorithm analysis often requires evaluating performance across various input scenarios to understand its practical implications. We define best, worst, and average cases to characterize an algorithm's efficiency bounds.

    ---

    Core Concepts

    1. Best Case Analysis

    We define the best case of an algorithm as the scenario where it performs the minimum number of operations for a given input size nn. This represents the most favorable input.

    Worked Example: Linear Search

    Consider an algorithm `LinearSearch(A, x)` that searches for an element xx in an array AA of size nn.

    Step 1: Define the algorithm

    ```
    function LinearSearch(A, x):
    n = length(A)
    for i from 1 to n:
    if A[i] == x:
    return i // Element found
    return -1 // Element not found
    ```

    Step 2: Identify the best-case input

    The best case occurs when the target element xx is found at the first position of the array. The loop executes only once.

    >

    NumberΒ ofΒ comparisons=1\text{Number of comparisons} = 1

    Answer: The best-case time complexity for Linear Search is O(1)O(1).

    question type="MCQ" question="For a sorting algorithm that checks if an array is already sorted before performing any major sorting operations, what is the best-case time complexity if the input array is already sorted?" options=["O(1)O(1)","O(log⁑n)O(\log n)","O(n)O(n)","O(nlog⁑n)O(n \log n)"] answer="O(n)O(n)" hint="Checking if an array of size nn is sorted requires iterating through all elements once." solution="Step 1: Analyze the 'check sorted' operation. To verify if an array AA of size nn is sorted, we must iterate from A[1]A[1] to A[nβˆ’1]A[n-1] and check if A[i]≀A[i+1]A[i] \le A[i+1] for all ii. This takes O(n)O(n) time.

    Step 2: Determine the total complexity.
    If the array is already sorted, the algorithm performs this O(n)O(n) check and then terminates without further sorting.

    >

    BestΒ CaseΒ Complexity=O(n)\text{Best Case Complexity} = O(n)

    "
    :::

    ---

    2. Worst Case Analysis

    We define the worst case as the scenario where an algorithm performs the maximum number of operations for a given input size nn. This provides an upper bound on the algorithm's runtime.

    Worked Example 1: Linear Search

    Consider the `LinearSearch(A, x)` algorithm.

    Step 1: Identify the worst-case input

    The worst case occurs when the target element xx is either at the last position of the array or not present in the array at all. The loop iterates through all nn elements.

    >

    NumberΒ ofΒ comparisons=n\text{Number of comparisons} = n

    Answer: The worst-case time complexity for Linear Search is O(n)O(n).

    Worked Example 2: Recursive Selection Algorithm (Inspired by PYQ 3 & 4)

    Consider the `mystery` function which attempts to find the kk-th smallest element in an array AA.

    ```
    function mystery(A, k) {
    n = length(A);
    if (k > n) return A[n];

    v = A[1]; // Pivot is always the first element
    AL = [ A[j] : 1 <= j <= n, A[j] < v ];
    AV = [ A[j] : 1 <= j <= n, A[j] == v ];
    AR = [ A[j] : 1 <= j <= n, A[j] > v ];

    if (length(AL) >= k) return mystery(AL, k);
    if (length(AL) + length(AV) > k) return v;
    return mystery(AR, k - (length(AL) + length(AV)));
    }
    ```

    Step 1: Analyze the operations at each step.

    At each recursive call, the algorithm scans the entire current array to partition it into `AL`, `AV`, and `AR`. This partitioning takes O(m)O(m) time, where mm is the length of the current array.

    Step 2: Identify the worst-case input for the pivot choice.

    The worst case occurs when the pivot v=A[1]v=A[1] is consistently chosen as the smallest or largest element in the array. This leads to highly unbalanced partitions.

    Consider A=[1,2,3,…,n]A = [1, 2, 3, \dots, n] and we search for k=nk=n.

    • First call: v=1v=1. `AL` is empty, `AV` contains `[1]`, `AR` contains `[2, 3, \dots, n]`.

    • The recursive call is `mystery(AR, n-1)`, where `AR` has size nβˆ’1n-1.

    • This pattern continues, with the array size decreasing by only one element in each recursive call.


    Step 3: Formulate the recurrence relation.

    Let T(n)T(n) be the time complexity for an input of size nn. In the worst case, the partitioning takes O(n)O(n) and the recursive call is made on an array of size nβˆ’1n-1.

    >

    T(n)=T(nβˆ’1)+O(n)T(n) = T(n-1) + O(n)

    Step 4: Solve the recurrence relation.

    >

    T(n)=n+(nβˆ’1)+(nβˆ’2)+β‹―+1=βˆ‘i=1ni=n(n+1)2\begin{aligned} T(n) & = n + (n-1) + (n-2) + \cdots + 1 \\ & = \sum_{i=1}^{n} i \\ & = \frac{n(n+1)}{2} \end{aligned}

    Answer: The worst-case time complexity is O(n2)O(n^2). An example worst-case input is an already sorted array A=[1,2,…,n]A = [1, 2, \dots, n] searching for the nn-th element, or a reverse-sorted array A=[n,nβˆ’1,…,1]A = [n, n-1, \dots, 1] searching for the 1st element.

    :::question type="MCQ" question="Consider a search algorithm for an nΓ—nn \times n matrix AA where each row and column is sorted in ascending order. The algorithm starts at A[1,n]A[1,n] (top-right corner) and searches for kk. If A[i,j]=kA[i,j] = k, it returns (i,j)(i,j). If A[i,j]<kA[i,j] < k, it moves down to A[i+1,j]A[i+1,j]. If A[i,j]>kA[i,j] > k, it moves left to A[i,jβˆ’1]A[i,j-1]. What is a worst-case input for this algorithm if kk is present?" options=["kk is at A[1,1]A[1,1]","kk is at A[n,n]A[n,n]","kk is at A[1,n]A[1,n]","kk is at A[n,1]A[n,1]"] answer="kk is at A[n,1]A[n,1]" hint="Analyze the movement pattern. To reach A[n,1]A[n,1] from A[1,n]A[1,n], the algorithm must traverse the maximum number of rows and columns." solution="Step 1: Understand the search strategy.
    Starting at (1,n)(1,n):

    • If current element is less than kk, move down (increase row index).

    • If current element is greater than kk, move left (decrease column index).

    • If current element equals kk, found.


    Step 2: Identify the path for maximum operations.
    To maximize operations, the algorithm should be forced to traverse as many rows and columns as possible.
    • To move down nβˆ’1n-1 times, kk must be greater than or equal to elements in A[1,j],A[2,j],…,A[nβˆ’1,j]A[1,j], A[2,j], \dots, A[n-1,j].

    • To move left nβˆ’1n-1 times, kk must be less than or equal to elements in A[i,n],A[i,nβˆ’1],…,A[i,2]A[i,n], A[i,n-1], \dots, A[i,2].


    Consider kk at A[n,1]A[n,1].
    The algorithm starts at A[1,n]A[1,n]. To reach A[n,1]A[n,1], it must make nβˆ’1n-1 'down' moves and nβˆ’1n-1 'left' moves. This requires 2nβˆ’22n-2 comparisons in the worst case. For example, if all elements in the first column are less than kk, it will move down until A[n,n]A[n,n]. Then, if A[n,j]>kA[n,j] > k for j>1j > 1, it will move left until A[n,1]A[n,1]. This path covers the maximum number of steps.

    >

    Worst-caseΒ positionΒ forΒ k=A[n,1]\text{Worst-case position for } k = A[n,1]

    >
    NumberΒ ofΒ stepsΒ inΒ worstΒ case=O(n)\text{Number of steps in worst case} = O(n)

    "
    :::

    ---

    3. Average Case Analysis

    We define the average case as the expected number of operations for a given input size nn, assuming a specific probability distribution over all possible inputs. This requires probabilistic analysis.

    πŸ“ Expected Value of Time Complexity
    E[T(n)]=βˆ‘I∈InT(I)β‹…P(I)E[T(n)] = \sum_{I \in \mathcal{I}_n} T(I) \cdot P(I)

    Where:

      • E[T(n)]E[T(n)] = Expected time complexity for inputs of size nn

      • In\mathcal{I}_n = Set of all possible inputs of size nn

      • T(I)T(I) = Time complexity for a specific input II

      • P(I)P(I) = Probability of input II occurring

    When to use: When a probability distribution over inputs can be reasonably assumed, to get a more realistic performance measure than worst-case.

    Worked Example: Linear Search (Average Case)

    Consider `LinearSearch(A, x)` on an array AA of size nn. We assume the following:

  • The element xx is present in the array with probability pp.

  • If xx is present, it is equally likely to be at any of the nn positions (i.e., probability 1/n1/n for each position).

  • If xx is not present (probability 1βˆ’p1-p), the algorithm performs nn comparisons.
  • Step 1: Calculate the expected number of comparisons if xx is present.

    If xx is at position ii, it takes ii comparisons.
    The probability of xx being at position ii given it's present is 1/n1/n.

    >

    E[comparisons∣xΒ present]=βˆ‘i=1niβ‹…1n=1nβˆ‘i=1ni=1nβ‹…n(n+1)2=n+12\begin{aligned} E[\text{comparisons} | x \text{ present}] & = \sum_{i=1}^{n} i \cdot \frac{1}{n} \\ & = \frac{1}{n} \sum_{i=1}^{n} i \\ & = \frac{1}{n} \cdot \frac{n(n+1)}{2} \\ & = \frac{n+1}{2} \end{aligned}

    Step 2: Calculate the total average number of comparisons.

    >

    E[T(n)]=P(xΒ present)β‹…E[comparisons∣xΒ present]+P(xΒ notΒ present)β‹…E[comparisons∣xΒ notΒ present]=pβ‹…n+12+(1βˆ’p)β‹…n\begin{aligned} E[T(n)] & = P(x \text{ present}) \cdot E[\text{comparisons} | x \text{ present}] + P(x \text{ not present}) \cdot E[\text{comparisons} | x \text{ not present}] \\ & = p \cdot \frac{n+1}{2} + (1-p) \cdot n \end{aligned}

    Answer: The average-case time complexity is O(n)O(n). For p=1p=1 (always present), it's O(n/2)=O(n)O(n/2) = O(n). For p=0p=0 (never present), it's O(n)O(n).

    :::question type="NAT" question="A hash table uses chaining to resolve collisions. The load factor is Ξ±=N/M\alpha = N/M, where NN is the number of items and MM is the number of slots. Assuming simple uniform hashing, what is the average number of probes (comparisons) for an unsuccessful search?" answer="alpha" hint="In simple uniform hashing, each item is equally likely to be hashed into any slot. An unsuccessful search must traverse the entire chain at the hashed slot." solution="Step 1: Understand simple uniform hashing and unsuccessful search.
    Simple uniform hashing implies that any given item is equally likely to hash into any of the MM slots, independently of where other items hash.
    For an unsuccessful search, we hash the key to a slot jj. If slot jj has a chain of length LjL_j, we must traverse all LjL_j elements in that chain to confirm the key is not present.

    Step 2: Calculate the expected chain length.
    The expected length of a chain at any given slot jj is the total number of items NN divided by the total number of slots MM. This is the definition of the load factor Ξ±\alpha.

    >

    E[Lj]=NM=Ξ±E[L_j] = \frac{N}{M} = \alpha

    Step 3: Determine the average probes.
    Since an unsuccessful search must traverse the entire chain at its hashed slot, the average number of probes is equal to the average chain length.

    >

    AverageΒ probesΒ forΒ unsuccessfulΒ search=Ξ±\text{Average probes for unsuccessful search} = \alpha

    "
    :::

    ---

    Advanced Applications

    1. Concurrent Execution Outcomes

    When multiple processes access and modify shared variables concurrently, the final state can depend on the interleaving of operations. We analyze best (minimum) and worst (maximum) possible outcomes by considering all valid execution schedules.

    Worked Example: Shared Variable Update (Inspired by PYQ 1)

    Consider two procedures, `proc1` and `proc2`, running in parallel. `x` is a shared variable initialized to 00.

    ```c
    int x = 0;

    proc1 {
    int temp1 = x;
    x = temp1 + 1;
    temp1 = x;
    x = temp1 + 1;
    }

    proc2 {
    int temp2 = x;
    x = temp2 + 1;
    }
    ```

    Step 1: Analyze `proc1` operations without interference.

    If `proc1` runs alone:

  • `temp1 = x;` (temp1 = 0)

  • `x = temp1 + 1;` (x = 1)

  • `temp1 = x;` (temp1 = 1)

  • `x = temp1 + 1;` (x = 2)

  • Final `x = 2`.

    Step 2: Analyze `proc2` operations without interference.

    If `proc2` runs alone:

  • `temp2 = x;` (temp2 = 0)

  • `x = temp2 + 1;` (x = 1)

  • Final `x = 1`.

    Step 3: Identify the minimum possible value for `x`.

    The minimum value occurs when `proc2`'s write operation, based on an old value of `x`, is the very last operation to complete, effectively overwriting any previous increments.

    > Interleaving for Minimum `x = 1`:
    >
    > 1. `proc1`: `temp1 = x;` (temp1=0\text{temp1}=0)
    > 2. `proc2`: `temp2 = x;` (temp2=0\text{temp2}=0)
    > 3. `proc1`: `x = temp1 + 1;` (x=1x=1)
    > 4. `proc1`: `temp1 = x;` (temp1=1\text{temp1}=1)
    > 5. `proc1`: `x = temp1 + 1;` (x=2x=2)
    > 6. `proc2`: `x = temp2 + 1;` (x=1x=1) // `proc2` writes 1, based on its initial read of 0. This is the last operation.

    Step 4: Identify the maximum possible value for `x`.

    The maximum value occurs when all increments are applied sequentially without any overwrites based on stale reads.

    > Interleaving for Maximum `x = 3`:
    >
    > 1. `proc1` fully executes:
    > - `temp1 = x;` (temp1=0\text{temp1}=0)
    > - `x = temp1 + 1;` (x=1x=1)
    > - `temp1 = x;` (temp1=1\text{temp1}=1)
    > - `x = temp1 + 1;` (x=2x=2)
    > 2. `proc2` fully executes:
    > - `temp2 = x;` (temp2=2\text{temp2}=2)
    > - `x = temp2 + 1;` (x=3x=3)

    Answer: The possible values for xx are 1,2,31, 2, 3.
    Minimum possible value for `x` is 11.
    Maximum possible value for `x` is 33.

    :::question type="MCQ" question="Consider x=0x=0. `procA` performs `x = x + 1; x = x + 1;`. `procB` performs `x = x + 1;`. Both run concurrently. Which of the following values are possible for xx after both processes halt?" options=["1","2","3","4"] answer="2,3" hint="Trace interleavings. Identify the minimum and maximum possible outcomes. A value of 1 implies one of the increments was completely lost, which is not possible with these operations." solution="Step 1: Analyze `procA` and `procB` independently.
    `procA` intends to add 2 to xx.
    `procB` intends to add 1 to xx.
    Total intended increments: 3.

    Step 2: Determine the minimum possible value.
    The minimum value occurs if one process's final write is based on an old value.

    • Start: x=0x=0

    • `procA`: `tempA1 = x;` (tempA1=0\text{tempA1}=0)

    • `procA`: `x = tempA1 + 1;` (x=1x=1)

    • `procA`: `tempA2 = x;` (tempA2=1\text{tempA2}=1)

    • `procB`: `tempB1 = x;` (tempB1=1\text{tempB1}=1)

    • `procB`: `x = tempB1 + 1;` (x=2x=2)

    • `procA`: `x = tempA2 + 1;` (x=2x=2) // `procA` writes 2, based on `tempA2=1`. This overwrites `procB`'s increment.

    Final x=2x=2.

    Step 3: Determine the maximum possible value.
    The maximum value occurs when all increments are applied sequentially without any overwrites based on stale reads.

    • `procA` fully executes: xβ†’0β†’1β†’2x \to 0 \to 1 \to 2.

    • Then `procB` executes: xβ†’2β†’3x \to 2 \to 3.

    Final x=3x=3.

    Step 4: List all possible values.
    The possible values are 22 and 33.

    >

    PossibleΒ valuesΒ forΒ x:{2,3}\text{Possible values for } x: \{2, 3\}

    "
    :::

    2. Amortized Analysis

    We use amortized analysis to analyze the performance of a sequence of operations, where a single operation might be expensive, but the average cost over a long sequence of operations is low. It provides a worst-case guarantee on the average performance per operation.

    Worked Example: Dynamic Array (Vector) Append Operation

    Consider a dynamic array that doubles its capacity when it runs out of space. Appending an element usually takes O(1)O(1) time, but when a reallocation occurs, it takes O(N)O(N) time, where NN is the current number of elements.

    Step 1: Analyze the cost of a sequence of NN `append` operations.

    Let's start with an empty array of capacity 1.

    • `append(1)`: Cost 1 (copy 0 elements, add 1). Capacity 1 -> 2.

    • `append(2)`: Cost 1 (add 1). Capacity 2.

    • `append(3)`: Cost 3 (copy 2 elements, add 1). Capacity 2 -> 4.

    • `append(4)`: Cost 1 (add 1). Capacity 4.

    • `append(5)`: Cost 5 (copy 4 elements, add 1). Capacity 4 -> 8.


    The total cost for NN appends involves NN constant-time insertions plus the cost of reallocations. A reallocation occurs when the array size reaches a power of 2 (e.g., 1, 2, 4, 8, ...). If we append NN elements, the total number of elements copied during reallocations is approximately 1+2+4+β‹―+2k1+2+4+\dots+2^k where 2k<N2^k < N. This sum is 2Nβˆ’12N-1.

    >

    TotalΒ Cost=N(forΒ insertions)+(Nβˆ’1)(forΒ copiesΒ inΒ reallocations)=2Nβˆ’1\text{Total Cost} = N (\text{for insertions}) + (N-1) (\text{for copies in reallocations}) = 2N-1

    Step 2: Calculate the amortized cost.

    The total cost for NN appends is O(N)O(N).

    >

    AmortizedΒ CostΒ perΒ operation=TotalΒ CostNumberΒ ofΒ Operations=O(N)N=O(1)\text{Amortized Cost per operation} = \frac{\text{Total Cost}}{\text{Number of Operations}} = \frac{O(N)}{N} = O(1)

    Answer: The amortized time complexity of the `append` operation for a dynamic array is O(1)O(1).

    :::question type="MCQ" question="A stack supports `PUSH(x)` (cost 1) and `MULTIPOP(k)` (pops kk elements or until empty, cost kk). What is the amortized cost of a `MULTIPOP` operation over a sequence of NN operations?" options=["O(1)O(1)","O(log⁑N)O(\log N)","O(N)O(N)","O(N2)O(N^2)"] answer="O(1)O(1)" hint="Consider the total number of elements pushed and popped across the entire sequence of operations. Each element can be pushed once and popped once." solution="Step 1: Use the aggregate method for amortized analysis.
    We want to find the total cost of a sequence of NN operations and then divide by NN.

    Step 2: Analyze the cost of `PUSH` and `MULTIPOP`.

    • `PUSH(x)`: Adds one element. Cost is 1.

    • `MULTIPOP(k)`: Removes up to kk elements. The cost is the number of elements actually popped.


    Step 3: Determine the total maximum cost for NN operations.
    Each element can be pushed onto the stack exactly once.
    Each element can be popped from the stack exactly once.
    Therefore, the total number of `PUSH` operations is at most NN.
    The total number of elements popped across all `MULTIPOP` operations cannot exceed the total number of elements pushed.
    So, if there are NN operations in total, the maximum total cost for all `PUSH` operations is NN. The maximum total cost for all `MULTIPOP` operations is also NN (since each element is popped at most once).

    >

    TotalΒ CostΒ forΒ NΒ operations≀N(forΒ pushes)+N(forΒ pops)=2N\text{Total Cost for } N \text{ operations} \le N (\text{for pushes}) + N (\text{for pops}) = 2N

    Step 4: Calculate the amortized cost.

    >

    AmortizedΒ CostΒ perΒ operation=TotalΒ CostN=O(N)N=O(1)\text{Amortized Cost per operation} = \frac{\text{Total Cost}}{N} = \frac{O(N)}{N} = O(1)

    Answer: The amortized cost of a `MULTIPOP` operation is O(1)O(1)."
    :::

    ---

    Problem-Solving Strategies

    πŸ’‘ Identifying Worst-Case Inputs

    To find a worst-case input, think adversarially. What input would force the algorithm to perform the maximum number of operations? For recursive algorithms, consider inputs that lead to the most unbalanced recursive calls (e.g., already sorted arrays for QuickSort, or a pivot that is always the smallest/largest). For search algorithms, consider elements at the very end or not present.

    πŸ’‘ Average Case Calculation

    Average case analysis requires a clear definition of the probability distribution of inputs. If not given, make a reasonable assumption (e.g., uniform distribution) and state it. The calculation often involves summing costs weighted by their probabilities.

    πŸ’‘ Concurrent Min/Max Outcomes

    For concurrent programs, identify all memory accesses (reads and writes) to shared variables. To find the minimum or maximum possible outcome, trace extreme interleavings:

      • Minimum: Schedule reads before writes, or allow one process to overwrite another's increment with an older value.

      • Maximum: Schedule processes to complete their increments sequentially, or ensure reads always see the most updated values.

    ---

    Common Mistakes

    ⚠️ Confusing Average and Worst Case

    ❌ Students often assume average case is "typically what happens" and don't calculate it rigorously, or confuse it with the best case.
    βœ… Worst case provides an upper bound guarantee. Average case provides expected performance under specific input distributions. Both are distinct and require different analytical approaches.

    ⚠️ Misidentifying Worst-Case for Recursive Algorithms

    ❌ For algorithms like QuickSort, assuming a random pivot always leads to good performance, or not recognizing that a fixed pivot choice (e.g., first element) can lead to O(N2)O(N^2) worst-case on specific inputs.
    βœ… Always analyze the pivot selection strategy. If it's deterministic, identify the input that consistently forces the worst pivot. If it's randomized, the worst-case expected time might be better, but a worst-case input still exists for a specific run.

    ⚠️ Incorrectly Handling Concurrent Variable Updates

    ❌ Assuming that `x = x + 1` is an atomic operation.
    βœ… `x = x + 1` is typically `read x`, `increment x`, `write x`. Each of these sub-operations can be interleaved, leading to race conditions and unexpected outcomes. Always break down composite operations into atomic reads and writes.

    ---

    Practice Questions

    :::question type="MCQ" question="Consider the following algorithm for finding the maximum element in an array AA of NN integers.
    ```
    function FindMax(A, N):
    if N == 0: return null
    max_val = A[1]
    for i from 2 to N:
    if A[i] > max_val:
    max_val = A[i]
    return max_val
    ```
    What is the best-case number of comparisons performed by this algorithm?" options=["1","Nβˆ’1N-1","NN","2N2N"] answer="Nβˆ’1N-1" hint="The best case for this algorithm is not about early exit but about minimizing assignments to `max_val`. However, the number of comparisons remains constant for a given NN." solution="Step 1: Analyze the operations.
    The algorithm initializes `max_val` with `A[1]`.
    The loop runs from i=2i=2 to NN, performing one comparison `A[i] > max_val` in each iteration.
    This loop executes Nβˆ’1N-1 times.

    Step 2: Determine best case.
    The number of comparisons (Nβˆ’1N-1) is fixed regardless of the input array, as the loop always runs completely. The best case for this algorithm would be minimizing the number of assignments to `max_val`, which happens if the array is sorted in descending order (e.g., `[10, 9, 8, ..., 1]`). However, the question asks for comparisons, which is constant.

    >

    Best-caseΒ comparisons=Nβˆ’1\text{Best-case comparisons} = N-1

    "
    :::

    :::question type="NAT" question="A binary search algorithm takes O(log⁑N)O(\log N) time in the worst case. If we are searching for an element in a sorted array of NN elements, and the element is guaranteed to be present, what is the maximum number of comparisons (including the final equality check) required to find the element?" answer="floor(log2(N)) + 1" hint="In a binary search, each comparison halves the search space. The number of comparisons is related to the depth of the binary search tree." solution="Step 1: Understand binary search comparisons.
    In binary search, each comparison eliminates half of the remaining search space. The maximum number of comparisons corresponds to traversing a path from the root to a leaf in a balanced binary search tree of NN nodes.

    Step 2: Relate to tree height.
    The height of a perfectly balanced binary tree with NN nodes is ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.
    The number of comparisons is the number of nodes visited on the path from the root to the target element.
    If the element is guaranteed to be found, it will be found at some depth. The maximum depth is ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.
    A node at depth dd requires d+1d+1 comparisons (including the comparison at the node itself).
    The root is at depth 0. A leaf is at depth ⌊log⁑2NβŒ‹\lfloor \log_2 N \rfloor.

    Step 3: Calculate maximum comparisons.
    The maximum number of comparisons occurs when the element is found at a leaf node (maximum depth).
    If N=1N=1, ⌊log⁑21βŒ‹+1=0+1=1\lfloor \log_2 1 \rfloor + 1 = 0 + 1 = 1.
    If N=2N=2, ⌊log⁑22βŒ‹+1=1+1=2\lfloor \log_2 2 \rfloor + 1 = 1 + 1 = 2.
    If N=3N=3, ⌊log⁑23βŒ‹+1=1+1=2\lfloor \log_2 3 \rfloor + 1 = 1 + 1 = 2. (e.g., for [1,2,3], search for 3: check 2, then check 3)
    If N=7N=7, ⌊log⁑27βŒ‹+1=2+1=3\lfloor \log_2 7 \rfloor + 1 = 2 + 1 = 3.
    If N=8N=8, ⌊log⁑28βŒ‹+1=3+1=4\lfloor \log_2 8 \rfloor + 1 = 3 + 1 = 4.

    >

    MaximumΒ comparisons=⌊log⁑2NβŒ‹+1\text{Maximum comparisons} = \lfloor \log_2 N \rfloor + 1

    "
    :::

    :::question type="MCQ" question="Consider a queue implemented using a circular array of fixed size MM. The `ENQUEUE` operation adds an element to the rear, and `DEQUEUE` removes from the front. If the queue is full, `ENQUEUE` fails. If the queue is empty, `DEQUEUE` fails. What is the worst-case time complexity for a single `ENQUEUE` operation?" options=["O(1)O(1)","O(log⁑M)O(\log M)","O(M)O(M)","O(M2)O(M^2)"] answer="O(1)O(1)" hint="In a circular array implementation, `ENQUEUE` typically involves updating pointers and placing an element, which are constant time operations." solution="Step 1: Analyze the `ENQUEUE` operation in a circular array.
    A circular array queue maintains `front` and `rear` pointers (or indices).
    To `ENQUEUE`:

  • Check if the queue is full (e.g., `(rear + 1) % M == front`).

  • If not full, increment `rear` (modulo MM).

  • Place the new element at `array[rear]`.

  • These operations (comparison, arithmetic, assignment) take constant time.

    Step 2: Determine worst-case.
    The worst case for `ENQUEUE` occurs when it has to check if the queue is full. This check is also a constant-time operation. No resizing or shifting of elements occurs in a fixed-size circular array.

    >

    Worst-caseΒ timeΒ complexity=O(1)\text{Worst-case time complexity} = O(1)

    "
    :::

    :::question type="MSQ" question="Which of the following statements about worst-case analysis are true?" options=["Worst-case analysis provides an upper bound on an algorithm's running time.","The worst-case input for an algorithm is always unique.","Worst-case analysis is useful for real-time systems where performance guarantees are critical.","An algorithm's worst-case time complexity can be better than its best-case time complexity."] answer="Worst-case analysis provides an upper bound on an algorithm's running time.,Worst-case analysis is useful for real-time systems where performance guarantees are critical." hint="Consider the definitions and applications of worst-case analysis. Think about scenarios where guarantees are paramount." solution="Option 1: Worst-case analysis provides an upper bound on an algorithm's running time.
    βœ… This is true by definition. The worst case describes the maximum time an algorithm will take for any input of a given size.

    Option 2: The worst-case input for an algorithm is always unique.
    ❌ This is false. For many algorithms, multiple distinct inputs can trigger the worst-case behavior. For example, for linear search, if the element is not present, any array where the element is absent is a worst-case input.

    Option 3: Worst-case analysis is useful for real-time systems where performance guarantees are critical.
    βœ… This is true. In real-time systems, it's crucial to know the absolute maximum time an operation might take to ensure deadlines are met. Average-case performance is insufficient here.

    Option 4: An algorithm's worst-case time complexity can be better than its best-case time complexity.
    ❌ This is false. By definition, the worst case represents the maximum operations, while the best case represents the minimum operations. The worst-case complexity can never be 'better' (i.e., faster, or lower complexity class) than the best-case complexity.

    >

    CorrectΒ statements:\text{Correct statements:}

    >
    Worst-caseΒ analysisΒ providesΒ anΒ upperΒ boundΒ onΒ anΒ algorithm’sΒ runningΒ time.\text{Worst-case analysis provides an upper bound on an algorithm's running time.}

    >
    Worst-caseΒ analysisΒ isΒ usefulΒ forΒ real-timeΒ systemsΒ whereΒ performanceΒ guaranteesΒ areΒ critical.\text{Worst-case analysis is useful for real-time systems where performance guarantees are critical.}

    "
    :::

    :::question type="MCQ" question="Consider a hash table using open addressing with linear probing. The table size is MM. We want to insert NN distinct keys, where N<MN < M. What is the average-case number of probes for an insertion, assuming simple uniform hashing and that the table is not full?" options=["O(1)O(1)","O(log⁑M)O(\log M)","O(N)O(N)","O(M)O(M)"] answer="O(1)O(1)" hint="For open addressing with linear probing, the average-case performance is usually expressed in terms of the load factor α=N/M\alpha = N/M. When α\alpha is small (e.g., constant), the expected probes are constant." solution="Step 1: Define the load factor.
    The load factor Ξ±=N/M\alpha = N/M represents the fraction of the hash table that is occupied.

    Step 2: Analyze linear probing performance.
    For open addressing with linear probing, the expected number of probes for an unsuccessful search (which is similar to an insertion, as it probes until an empty slot is found) is approximately 1/(1βˆ’Ξ±)21/(1-\alpha)^2.

    Step 3: Evaluate average case for N<MN < M.
    Since N<MN < M, the load factor Ξ±<1\alpha < 1. If we consider a scenario where NN is much smaller than MM (e.g., Ξ±\alpha is a small constant like 0.50.5), then 1/(1βˆ’Ξ±)21/(1-\alpha)^2 becomes a constant.
    For example, if Ξ±=0.5\alpha = 0.5, expected probes β‰ˆ1/(0.5)2=4\approx 1/(0.5)^2 = 4.
    Thus, for a constant load factor (i.e., NN is proportional to MM), the average number of probes is constant.

    >

    Average-caseΒ numberΒ ofΒ probes=O(1)Β (whenΒ Ξ±Β isΒ constant)\text{Average-case number of probes} = O(1) \text{ (when } \alpha \text{ is constant)}

    "
    :::

    ---

    Summary

    ❗ Key Formulas & Takeaways

    |

    | Concept | Expression |

    |---|---------------------------|------------| | 1 | Best Case | Minimum operations for input size nn. | | 2 | Worst Case | Maximum operations for input size nn. | | 3 | Average Case | E[T(n)]=βˆ‘I∈InT(I)β‹…P(I)E[T(n)] = \sum_{I \in \mathcal{I}_n} T(I) \cdot P(I) | | 4 | Amortized Analysis | Average cost per operation over a sequence. |

    ---

    What's Next?

    πŸ’‘ Continue Learning

    This topic connects to:

      • Recurrence Relations: Essential for analyzing the time complexity of recursive algorithms, especially for worst and average cases.

      • Sorting Algorithms: Many sorting algorithms (e.g., QuickSort, MergeSort) have distinct best, worst, and average-case complexities.

      • Data Structures: Understanding the best, worst, and amortized performance of operations on data structures like hash tables, dynamic arrays, and heaps.

      • Probabilistic Analysis: Deeper understanding of how to derive average-case complexities when randomized algorithms or probabilistic inputs are involved.

    ---

    Chapter Summary

    ❗ Algorithm Basics and Analysis β€” Key Points

    Asymptotic notations (Big-OO, Ω\Omega, Θ\Theta) are fundamental for characterizing algorithm efficiency, focusing on growth rates for large inputs.
    Time complexity quantifies computational steps, while space complexity measures memory usage, both typically expressed as functions of input size nn.
    Algorithm analysis involves identifying dominant operations, loop iterations, recursive calls, and memory allocations to derive complexity bounds.
    Algorithms are often evaluated for their best-case, worst-case, and average-case performance, providing a comprehensive understanding of their behavior under different input scenarios.
    Common complexity classes (e.g., O(1)O(1), O(log⁑n)O(\log n), O(n)O(n), O(nlog⁑n)O(n \log n), O(n2)O(n^2), O(2n)O(2^n)) represent distinct performance tiers, with polynomial and polylogarithmic complexities generally preferred over exponential.
    Auxiliary space refers to extra memory used beyond input storage, crucial for optimizing memory-constrained applications and understanding an algorithm's overall footprint.

    ---

    Chapter Review Questions

    :::question type="MCQ" question="What is the time complexity of the following Python function?" options=["O(n)O(n)","O(nlog⁑n)O(n \log n)","O(n2)O(n^2)","O(n3)O(n^3)"] answer="O(n2)O(n^2)" hint="The inner loop's iterations depend on the outer loop's variable. Consider the sum of an arithmetic progression." solution="The outer loop runs nn times. The inner loop runs i+1i+1 times for each ii. The total number of operations is approximately 1+2+β‹―+n=n(n+1)21 + 2 + \dots + n = \frac{n(n+1)}{2}, which simplifies to O(n2)O(n^2)."
    ```python
    def example_func(n):
    count = 0
    for i in range(n):
    for j in range(i + 1):
    count += 1
    return count
    ```
    :::

    :::question type="NAT" question="An algorithm processes an array of nn elements. It uses a fixed-size auxiliary stack of 10 elements and internally creates a copy of the input array. If n=200n=200, how many units of space (approximately) does it use in total for both the copy and the stack? (Assume each element takes 1 unit of space)." answer="210" hint="Sum the space used by the copied array and the fixed-size stack." solution="The copied array uses nn units of space. The stack uses 10 units of space. Total space = n+10n + 10. For n=200n=200, total space = 200+10=210200 + 10 = 210 units."
    :::

    :::question type="MCQ" question="For a linear search algorithm on an unsorted array of nn elements, when does the best-case time complexity O(1)O(1) occur?" options=["When the element is not present in the array","When the element is at the very end of the array","When the element is the first element in the array","When the array is sorted"] answer="When the element is the first element in the array" hint="Best case implies the minimum possible number of operations." solution="Linear search checks elements sequentially. If the target element is found at the very first position, only one comparison is needed, resulting in O(1)O(1) time complexity."
    :::

    :::question type="MCQ" question="Which of the following functions represents the fastest growing time complexity for large nn?" options=["O(nlog⁑n)O(n \log n)","O(n2)O(n^2)","O(2n)O(2^n)","O(n)O(n)"] answer="O(2n)O(2^n)" hint="Compare the growth rates of logarithmic, linear, polynomial, and exponential functions." solution="For large nn, exponential functions (O(2n)O(2^n)) grow significantly faster than polynomial functions (O(n2)O(n^2), O(n)O(n)) or polylogarithmic functions (O(nlog⁑n)O(n \log n)). The order of growth from slowest to fastest among the options is O(n)O(n), O(nlog⁑n)O(n \log n), O(n2)O(n^2), O(2n)O(2^n)."
    :::

    ---

    What's Next?

    πŸ’‘ Continue Your CMI Journey

    Building upon the foundational techniques of algorithm analysis, the next chapters will delve into various Data Structures, examining how their structural properties influence the time and space complexity of common operations. Subsequently, we will apply these analytical skills to Sorting Algorithms and Searching Algorithms, understanding their performance characteristics and suitability for different problem domains.

    🎯 Key Points to Remember

    • βœ“ Master the core concepts in Algorithm Basics and Analysis before moving to advanced topics
    • βœ“ Practice with previous year questions to understand exam patterns
    • βœ“ Review short notes regularly for quick revision before exams

    Related Topics in Algorithms and Data Structures

    More Resources

    Why Choose MastersUp?

    🎯

    AI-Powered Plans

    Personalized study schedules based on your exam date and learning pace

    πŸ“š

    15,000+ Questions

    Verified questions with detailed solutions from past papers

    πŸ“Š

    Smart Analytics

    Track your progress with subject-wise performance insights

    πŸ”–

    Bookmark & Revise

    Save important questions for quick revision before exams

    Start Your Free Preparation β†’

    No credit card required β€’ Free forever for basic features