Initial Commit

This commit is contained in:
gparidhi51
2024-03-15 16:00:07 +05:30
committed by GitHub
parent 8662d179cf
commit 16e65a901d
98 changed files with 52995 additions and 0 deletions

View File

@@ -0,0 +1,667 @@
# Arrays 1: One Dimensional
## Problem 1 Find Maximum Subarray Sum
### Problem Statement
Given an integer array A, find the maximum subarray sum out of all the subarrays.
### Examples
**Example 1**:
For the given array A with length N,
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Array | -2 | 3 | 4 | -1 | 5 | -10 | 7 |
**Output:**
```plaintext
Max Sum: 11
Subarray: 3 4 -1 5
```
**Example 2:**
For the given array A with it's length as N we have,
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Array | -3 | 4 | 6 | 8 | -10 | 2 | 7 |
**Output:**
```plaintext
Max Sum: 18
Subarray: 4 6 8
```
---
### Question
For the given array A, what is the maximum subarray sum ?
A[ ] = { 4, 5, 2, 1, 6 }
**Choices**
- [ ] 6
- [x] 18
- [ ] No Idea
- [ ] 10
```plaintext
Max Sum: 18
Subarray: 4 5 2 1 6
```
### Question
For the given array A, what is the maximum subarray sum ?
A[ ] = { -4, -3, -6, -9, -2 }
**Choices**
- [ ] -9
- [ ] 18
- [x] -2
- [ ] -24
```plaintext
Max Sum: -2
Subarray: -2
```
---
### Find Maximum Subarray Sum Brute Force
#### Brute Force
No of possible subarrays: `N * (N + 1) / 2`
Iterate over all subarrays, calculate sum and maintain the maximum sum.
#### Psuedocode:
```java
ans = A[0];
for (i = 0; i < N; i++) { // start to N
for (j = i; j < N; j++) { // end
for (k = i; k <= j; k++) {
sum += A[k];
}
ans = Math.max(ans, sum);
sum = 0; // Reset sum for the next iteration
}
}
return ans;
```
#### Complexity
**Time Complexity:** `O(N^2 * N) = O(N^3)`
**Space Complexity:** `O(1)`
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
---
### Find Maximum Subarray Sum using Carry Forward
#### Optimized Solution using Carry Forward
We don't really need the third loop present in brute force, we can optimise it further using Carry Forward technique.
#### Psuedocode
```java
ans = A[0]
for (i = 0 to N - 1) { //start to N
sum = 0
for (j = i to N - 1) { //end
sum += A[k]
ans = max(ans, sum)
}
}
return ans;
```
#### Complexity
**Time Complexity:** O(N^2)
**Space Complexity:** O(1)
---
### Find Maximum Subarray Sum using Kadanes Algorithm
#### Observation:
**Case 1:**
If all the elements in the array are positive
Arr[] = `[4, 2, 1, 6, 7]`
**Answer:**
To find the maximum subarray we will now add all the positive elements
Ans: `(4 + 2 + 1 + 6 + 7) = 20`
**Case 2:**
If all the elements in the array are negative
Arr[] = `[-4, -8, -9, -3, -5]`
**Answer:**
Here, since a subarray should contain at least one element, the max subarray would be the element with the max value
Ans: `-3`
**Case 3:**
If positives are present in between
Arr[] = [-ve -ve -ve `+ve +ve +ve +ve` -ve -ve -ve]
**Answer:**
Here max sum would be the sum of all positive numbers
**Case 4:**
If all negatives are present either on left side or right side.
Arr[ ] = [-ve -ve -ve `+ve +ve +ve +ve`]
OR
Arr[ ] = [`+ve +ve +ve +ve` -ve -ve -ve -ve]
**Answer:**
All postives on sides
Case 5 :
**Hint:**
What if it's some ve+ followed by some ve- and then again some more positives...
```plaintext
+ve +ve +ve -ve -ve -ve +ve +ve +ve +ve +ve
```
#### Solution:
We will take all positives, then we consider negatives only if the overall sum is positive because in the future if positives come, they may further increase this positivity(sum).
**Example** -
```plaintext
A[ ] = { -2, 3, 4, -1, 5, -10, 7 }
```
Answer array: 3, 4, -1, 5
**Explanation**:
3+4 = 7
7 + (-1) = 6 (still positive)
6+5 = 11 (higher than 7)
#### Dry Run
```plaintext
0 1 2 3 4 5 6 7 8
{ -20, 10, -20, -12, 6, 5, -3, 8, -2 }
```
| i | currSum | maxSum | |
|:---:|:-------:|:------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------:|
| 0 | -20 | -20 | reset the currSum to 0 and do not propagate since adding a negative will make it more negative and adding a positive will reduce positivity of that element. |
currSum = 0
| i | currSum | maxSum | |
|:---:|:-------------:|:------:|:------------------:|
| 1 | 10 | 10 | |
| 2 | 10 + (-20)= -10 | 10 | reset currSum to 0 |
currSum = 0
| i | currSum | maxSum | |
|:---:|:-------:|:------:|:------------------:|
| 3 | -12 | 10 | reset currSum to 0 |
currSum = 0
| i | currSum | maxSum | |
|:---:|:---------:|:------:|:---------------------------------------------------------------------------:|
| 4 | 6 | 10 | |
| 5 | 6 + 5 | 11 | |
| 6 | 6 + 5 - 3 = 8 | 11 | Keep currSum as 8 only since if we find a positive, it can increase the sum |
| i | currSum | maxSum | |
|:---:|:-------:|:------:| --------------------------------------------------------------------------- |
| 7 | 8 + 8 = 16 | 16 | |
| 8 | 16 - 2 = 14 | 16 | Keep currSum as 8 only since if we find a positive, it can increase the sum |
Final maxSum = 16
---
### Question
Tell the output of the below example after running the Kadane's Algorithm on that example
A[ ] = { -2, 3, 4, -1, 5, -10, 7 }
**Choices**
- [ ] 9
- [ ] 7
- [x] 11
- [ ] 0
---
### Find Maximum Subarray Sum Kadanes Pseudocode
#### Pseudocode
```cpp
int maximumSubarraySum(int[] arr, int n) {
int maxSum = Integer.MIN_VALUE, currSum = 0;
for (int i = 0; i <= n - 1; i++) {
currSum += arr[i];
if (currSum > maxSum) {
maxSum = currSum;
}
if (currSum < 0) {
currSum = 0;
}
}
return maxSum;
}
```
#### Complexity
**Time Complexity:** O(n)
**Space Complexity:** O(1)
The optimized method that we just discussed comes under **Kadane's Algorithm** for solving maximum subarray problem
---
### Problem 2 Perform multiple Queries from i to last index
#### Problem Statement
Given an integer array A where every element is 0, return the final array after performing multiple queries
**Query (i, x):** Add x to all the numbers from index i to N-1
**Example**
Let's say we have a zero-filled array of size 7 with the following queries:
Query(1, 3)
Query(4, -2)
Query(3, 1)
Let's perform these queries and see how it works out.
**Example Explanation**
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
| ----- | --- | --- | --- | --- | --- | --- | ----- |
| **Array** | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| **Q1** | : | +3 | +3 | +3 | +3 | +3 | +3|
| **Q2** | : | : | : | : | -2 | -2 | -2|
| **Q3** | : | : | : | +1 | +1 | +1 | +1
| **Ans[]** | 0 | 3 | 3 | 4 | 2 | 2 | 2 |
---
### Question
Return the final array after performing the queries
**Note:**
- **Query (i, x):** Add x to all the numbers from index i to N-1
- 0-based Indexing
```cpp
A = [0, 0, 0, 0, 0]
Query(1, 3)
Query(0, 2)
Query(4, 1)
```
**Choices**
- [ ] [6, 6, 6, 6, 6]
- [x] [2, 5, 5, 5, 6]
- [ ] [2, 3, 3, 3, 1]
- [ ] [2, 2, 5, 5, 6]
---
#### Explanation
| Index | 0 | 1 | 2 | 3 | 4 |
| ----- | --- | --- | --- | --- | --- |
| **Array** | 0 | 0 | 0 | 0 | 0 |
| **Q1** | : | +3 | +3 | +3 | +3 |
| **Q2** | +2 | +2 | +2 | +2 | +2 |
| **Q3** | : | : | : | : | +1 |
| **Ans[]** | 2 | 5 | 5 | 5 | 6 |
---
### Perform multiple Queries from i to last index Solution Approaches
#### Brute force Approach
One way to approach this question is for a given number of Q queries, we can traverse the entire array each time.
#### Complexity
**Time Complexity:** O(Q * N)
**Space Complexity:** O(1)
#### Optimized Solution
#### Hint:
* Wherever we're adding the value initially, the value is to be carried forward to the very last of the array isn't it?
* Which is the concept that helps us carry forward the sum to indices on right hand side ?
Expected: **Prefix Sum!**
* Idea is that first we add the values at the ith indices as per given queries.
* Then, at the end, we can propagate those sum to indices on right.
* This way, we're only iterating over the array once unlike before.
#### Dry Run
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
| --------- | --- | --- | --- | --- | --- | --- | --- |
| **Array** | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| **Q1** | : | +3 | : | : | : | : | : |
| **Q2** | : | : | : | : | +2 | : | |
| **Q3** | : | : | : | +1 | : | : | : |
| **Ans[]** | 0 | 3 | 0 | 1 | 2 | 0 | 0 |
| **psum[]** | 0 | 3 | 3 | 4 | 6 | 6 | 6 |
#### Pseudocode
```cpp
for (i = 0; i < Q.length; i++) {
index = B[i][0];
val = B[i][1];
A[index] += val;
}
for (i = 1; i < N; i++) {
A[i] += A[i - 1];
}
return A;
```
#### Complexity
**Time Complexity:** O(Q + N)
**Space Complexity:** O(1) since we are only making changes to the answer array that needs to be returned.
---
### Problem 3 Perform multiple Queries from index i to j
#### Problem Statement
Given an integer array A such that all the elements in the array are 0. Return the final array after performing multiple queries
`Query: (i, j, x)`: Add x to all the elements from index i to j
Given that `i <= j`
**Examples**
Let's take an example, say we have the zero-filled array of size 7 and the queries are given as
q1 = (1, 3, 2)
q2 = (2, 5, 3)
q3 = (5, 6, -1)
---
### Question
Find the final array after performing the given queries on array of size **8**.
|i | j | x |
|- | - | - |
| 1 | 4 | 3 |
| 0 | 5 |-1 |
| 2 | 2 | 4 |
| 4 | 6 | 3 |
**Choices**
- [ ] 1 2 6 3 5 2 3 0
- [ ] -1 2 6 2 5 2 3 3
- [x] -1 2 6 2 5 2 3 0
- [ ] 1 2 6 3 5 2 0 3
---
#### Observations
In the provided query format `Query: (i, j, x)`
here, start (i) and end (j) are specifiying a range wherein the values (x) needs to be added to the elements of the given array
#### Brute force Solution Approach
In this solution we can iterate through the array for every query provided to us and perform the necessary operation over it.
#### Dry Run
The provided queries we have are
q1 = (1, 3, 2)
q2 = (2, 5, 3)
q3 = (5, 6, -1)
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
| ------ | --- | --- | --- | --- | --- | --- | --- |
| Arr[7] | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| V1 | | 2 | 2 | 2 | | | |
| V2 | | | 3 | 3 | 3 | 3 | |
| V3 | | | | | | -1 | -1 |
| Ans | 0 | 2 | 5 | 5 | 3 | 2 | -1 |
#### Complexity
**Time Complexity:** O(Q * N)
**Space Complexity:** O(1)
#### Optimized Solution
* This time, wherever we're adding the value initially, the value is to be carried forward only till a particular index, right?
* Can we use the Prefix Sum concept here are well ?
* How can we make sure that the value only gets added up till index j ?
* What can help us negate the effect of **+val** ?
#### Idea
* We can add the value at the starting index and subtract the same value just after the ending index which will help us to only carry the effect of **+val** till a specific index.
* From the index(k) where we have done **-val**, the effect will neutralise i.e, from (k to N-1)
#### Pseudocode:
```cpp
zeroQ(int N, int start[], int end[], int val[]) {
long arr[N] = 0;
for (int i = 0; i < Q; i++) {
//ith query information: start[i], end[i], val[i]
int s = start[i], e = end[i], v = val[i];
arr[s] = arr[s] + v;
if (e < n - 1) {
arr[e + 1] = arr[e + 1] - v;
}
}
//Apply cumm sum a psum[] on arr
for (i = 1; i < N; i++) {
arr[i] += arr[i - 1];
}
return arr;
}
```
#### Complexity
**Time Complexity:** O(Q + N)
**Space Complexity:** O(1)
**Problem Statement**
Given N buildings with height of each building, find the rain water trapped between the buildings.
#### Example Explanation
Example:
arr[] = {2, 1, 3, 2, 1, 2, 4, 3, 2, 1, 3, 1}
We now need to find the rainwater trapped between the buildings
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/100/original/rain_trap.png?1706008133" width=600/>
**Ans: 8**
#### Hint:
If we get units of water stored over every building, then we can get the overall water by summing individual answers.
#### Observations
1. How much water is stored over **building 2** ? **-> 4 units**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/138/original/upload_1e8c00eedae54cb6b93c3d87945d152a.png?1695374556" width=300 />
2. Now, how much water is stored over **building 2** ? **still -> 4 units**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/139/original/upload_48646dcd1fd44599afb23abe521026c8.png?1695374587" width=300 />
3. Now, how much water is stored over **building 2** ? **still -> 4 units**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/140/original/upload_b6c255326a25dc18d22e80c225b962ab.png?1695374617" width=300 />
4. Now, how much water is stored over **building 2** ? **Now it is 6**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/141/original/upload_3faddfa43fec2bdff4817ab567b236c3.png?1695374641" width=300 />
5. Now, how much water is stored over **building 2** ? **Now it is 8**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/142/original/upload_78cd8d3521ef7b1141f700a6a4947945.png?1695374662" width=300 />
#### Conclusion:
It depends on the height of the minimum of the largest buildings on either sides.
**Example:**
Water stored over building 5 depends on minimum of the largest building on either sides.
**i.e, min(10, 12) = 10**
**Water stored over 5 is 10 - 5 = 5 units.**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/143/original/upload_1a3b70b3067fb4fd72a1240dae787f62.png?1695374697" width=300 />
---
### Question
Given N buildings with height of each building, find the rain water trapped between the buildings.
`A = [1, 2, 3, 2, 1]`
**Choices**
- [ ] 2
- [ ] 9
- [x] 0
- [ ] 3
**Explanation:**
No water is trapped, Since the building is like a mountain.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/060/323/original/imageee.png?1703834723" width=300 />
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
---
### Rain Water Trapping Brute Force Approach
For **ith** building,
We need to find maximum heights on both the left and right sides of **ith** building.
NOTE: For **0th** and **(N-1)th** building, no water will be stored on top.
#### Pseudocode (Wrong)
```cpp
ans = 0
for (int i = 1; i < N - 1; i++) {
maxL = max(0 to i - 1); //loop O(N)
maxR = max(i + 1 to N - 1); //loop O(N)
water = min(maxL, maxR) - A[i];
ans += water;
}
```
#### Edge Case
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/144/original/upload_fed83d7b202f6c0959ad932d3d5234f2.png?1695374778)" width=500 />
For building with height 4, the Lmax = 3 and Rmax = 3
min(3, 3) = 3
water = **3 - 4 < 0**
So, for such case, we'll take water stored as 0.
#### Pseudocode (Correct)
```cpp
ans = 0
for (int i = 1; i < N - 1; i++) {
maxL = max(0 to i - 1); //loop O(N)
maxR = max(i + 1 to N - 1); //loop O(N)
water = min(maxL, maxR) - A[i];
if (water > 0) {
ans += water;
}
}
```
#### Complexity
**Time Complexity:** O(N^2) {Since for every element, we'll loop to find max on left and right}
**Space Complexity:** O(N)
---
### Rain Water Trapping Optimised Approach
We can store the max on right & left using carry forward approach.
* We can take 2 arrays, lmax[] & rmax[].
* Below is the calculation for finding max on left & right using carry forward approach.
* This way, we don't have to find max for every element, as it has been pre-calculated.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/145/original/upload_f948bda6a2057500be48a7c0fd0d5da7.png?1695374834" width=500 />
#### Pseudocode
```cpp
ans = 0;
int lmax[N] = {
0
};
for (int i = 1; i < N; i++) {
lmax[i] = max(lmax[i - 1], A[i - 1]);
}
int rmax[N] = {
0
};
for (int i = N - 2; i >= 0; i--) {
rmax[i] = max(rmax[i + 1], A[i + 1]);
}
for (int i = 1; i < N - 1; i++) {
water = min(lmax[i], rmax[i]) - A[i];
if (water > 0) {
ans += water;
}
}
```
#### Complexity
**Time Complexity:** O(N) {Since we have precalculated lmax & rmax}
**Space Complexity:** O(N)

View File

@@ -0,0 +1,568 @@
# Advanced DSA : Arrays 2: Two Dimensional
---
## Problem 1 Find in rowise and colwise sorted matrix
### Problem Statement
Given a row wise and column wise sorted matrix, find out whether element **k** is present or not.
**Example**
Observe that rows and columns are both sorted.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/573/original/Screenshot_2023-09-25_at_3.51.10_PM.png?1695652091" width=400 />
**Test Case 1**
13 => Present (true)
**Test Case 2**
2 => Present (true)
**Test Case 3**
15 => Not Present (false)
---
### Question
What is the brute force approach and the time complexity of it?
**Choices**
- [ ] Iterate over first row; T.C - O(M)
- [ ] Iterate over last col; T.C - O(N)
- [x] Iterate over all rows & cols; T.C - O(N * M)
- [ ] Iterate over first col; T.C - O(N)
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Idea
* We shall exploit the property of the matrix being sorted.
* Start with the cell from where we can decide the next step.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/662/original/Screenshot_2023-09-25_at_8.07.35_PM.png?1695706871" width=300 />
Search for: 0
Say we stand at **top left cell i.e, -5**.
Now, **-5 < 0**, can we determined the direction to search based on this?
No, because on rightside as well as downwards, the elements are in increasing order, so 0 can be present anywhere.
Now, say we stand at **top right cell i.e, 13**.
Now,**13 > 0**, should we go left or down ? Can we decide ?
Yes, if we move down the elements are > 13, but we are looking for an element < 13, so we should move left.
It means, all elements below 13, can be neglected.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/664/original/Screenshot_2023-09-25_at_8.08.43_PM.png?1695707082" width=50 />
**Move Left**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/665/original/Screenshot_2023-09-26_at_11.14.03_AM.png?1695707132" width=150 />
Now, where shall we move ?
---
### Question
Say we are at 1 and want to find 0, where should we move ?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/662/original/Screenshot_2023-09-25_at_8.07.35_PM.png?1695706871" width=300 />
**Choices**
- [x] left
- [ ] bottom
- [ ] let's move in both the directions
- [ ] let's move everywhere
---
### Find in rowise and colwise sorted matrix Optimised Approach Continued
Since, **1 > 0**, again all elements below 1 are greater than 1, hence can be neglected.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/667/original/Screenshot_2023-09-25_at_8.09.08_PM.png?1695707195" width=200 />
**Move Left**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/670/original/Screenshot_2023-09-26_at_11.17.20_AM.png?1695707280)" width=250 />
Now, **-2 < 0**, all elements on left of -2 are lesser than -2, hence can be neglected.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/672/original/Screenshot_2023-09-25_at_8.09.29_PM.png?1695707327" width=300 />
**Move Down**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/674/original/Screenshot_2023-09-25_at_8.09.51_PM.png?1695707362" width=300 />
#### Approach
* We can start at top right cell.
* If A[i][j] < K, move down, else move left.
* Repeat until the element is found, our the search space is exhausted.
**NOTE:** We could have also started at bottom left cell.
#### Pseudocode
```cpp
int i = 0, j = M - 1
while (i < N && j >= 0) {
if (arr[i][j] == K) {
return true;
} else if (arr[i][j] < K) {
i++; //move down; next row
} else {
j--; //move left; previous column
}
}
return false;
```
#### Time & Space Complexity
**Time Complexity:** O(M+N) since at every step, we are either discarding a row or a column. Since total rows+columns are N+M, hence Iterations will be N+M.
**Space Complexity:** O(1)
---
### Problem 2 Row with maximum number of 1s
Given a binary sorted matrix A of size N x N. Find the row with the maximum number of 1.
NOTE:
* If two rows have the maximum number of 1 then return the row which has a lower index.
* Assume each row to be sorted by values.
**Example 1:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/693/original/Screenshot_2023-09-26_at_11.34.48_AM.png?1695708357" width=300 />
**Output 1:** 0th row
**Example 2:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/694/original/Screenshot_2023-09-26_at_11.35.13_AM.png?1695708413" width=300 />
**Output 2:** 3th row
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force
We can iterate over each row and maintain the max number of 1s.
#### Complexity
**Time Complexity:** O(N * N)
---
### Question
Find the row with the maximum number of 1.
Note : If there are two rows with same no. of 1, consider the smaller row.
| **0** | **1** | **1** | **1** |
|---|---|---|---|
| **0** | **0** | **0** | **1** |
| **1** | **1** | **1** | **1** |
| **1** | **1** | **1** | **1** |
**Choices**
- [ ] 0th Row
- [ ] 1st Row
- [x] 2nd Row
- [ ] 3rd Row
---
### Optimisation Approach
We know that rows are sorted, how can we utilise this property of the matrix ?
#### Idea
Say we start from top right of first row and saw that there are 2 ones.
Now, in the next row, we don't want to see 2 1s, rather we'll check if 3rd 1 is present or not?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/699/original/Screenshot_2023-09-26_at_11.47.14_AM.png?1695709081" width=400 />
If yes, it means we have three 1s, but then we want to check if more 1s are there, so we'll move towards left in the same row and check.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/698/original/Screenshot_2023-09-26_at_11.46.55_AM.png?1695709065" width=400 />
Now, in the subsequent rows, we'll proceed in the same manner.
In 2nd and 3rd rows, 1 is not present at 1st index.
In 4th row, it is present. So, we check on left if more 1s are present.
In 4th row, we found the maximum 1s, i.e 5 in total. Hence that is our answer.
#### Algorithm
1. Start at i = 0, j = M - 1
2. If 1 is present, decrement j i.e, move towards the left column.
* Whenever j is decremented, it means that row has more 1s, so we can update our answer to that particular row number
4. If 0 is present, then we want to check in next row that if 1 is present, so we increment i
#### Pseudocode
```cpp
i = 0, j = N - 1
while (i < N && j >= 0) {
while (j >= 0 && arr[i][j] == 1) {
j--;
ans = i;
}
i++;
}
return ans;
```
#### Complexity
**Time Complexity:** O(M + N) since at every step, we are either discarding a row or a column. Since total rows+columns are N+M, hence Iterations will be N+M.
**Space Complexity:** O(1)
---
### Problem 3 Print Boundary Elements
Given an matrix of N X N i.e. Mat[N][N], print boundary elements in clockwise direction.
**Example:**
```cpp
N = 5
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/280/original/upload_e6cc36d5ca7bfae043291c37bc581960.png?1697631210" width=300 />
**Output:** [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6]
---
### Question
Given N and matrix mat, select the correct order of boundary elements traversed in clockwise direction.
```cpp
N = 3
```
mat :-
| 1 | 2 | 3 |
|:---:|:---:|:---:|
| **4** | **5** | **6** |
| **7** | **8** | **9** |
**Choices**
- [x] [1, 2, 3, 6, 9, 8, 7, 4]
- [ ] [1, 4, 7, 8, 9, 6, 3, 2]
- [ ] [1, 2, 3, 4, 5, 6, 7, 8]
- [ ] [2, 3, 4, 5, 6, 7, 8, 9]
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* Print N - 1 elements of first row from left to right
* Print N - 1 elements of last column from top to bottom
* Print N - 1 elements of last row from right to left
* Print N - 1 elements of first column from bottom to top
#### Pseudocode
```cpp
function printBoundaryElements(Mat[][], N) {
i = 0 j = 0
// Print N - 1 elements of first row from left to right
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
j++
}
// Print N - 1 elements of last column from top to bottom
// i and j will already be 0 and 4 respectively after above loop ends
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
i++
}
// Print N - 1 elements of last row from right to left
// i and j will already be 4 and 4 respectively after above loop ends
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
j--
}
// Print N - 1 elements of first column from bottom to top
// i and j will already be 4 and 0 respectively after above loop ends
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
i--
}
}
```
#### Complexity
**Time Complexity : O(N)**
**Space Complexity : O(1)**
---
### Problem 4 Spiral Matrix
Given an matrix of N X N i.e. Mat[N][N]. Print elements in spiral order in clockwise direction.
**Example**
```cpp
N = 5
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/086/original/p4-t1.png?1681249639" width=400 />
Here is the depiction to understand the problem better
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/087/original/p4-t1e.png?1681249819" width=400 />
```cpp
Solution = [1,2,3,4,5,6,12,18,24,30,36,35,34,33,32,31,25,19,13,7,8,9,10,11,17,23,29,28,27,26,20,14,15,16,22,21]
```
The red arrow represents direction of traversal(clockwise) and fashion in which elements are traversed.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* We can break the problem into several boundary printing problem discussed above
* So first print boundary of matrix of N x N
* Then we print boundary of next submatrix with top left element being (1,1) and Bottom right element being (N - 2 , N - 2).
* After every boundary, to print the next boundary, N will be reduced by 2 and i & j will be incremented by 1.
* We do this till matrix of size least size is reached.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/088/original/abs.png?1681249921" width=600/>
Boundaries of submatricies are highlighted in different color.
#### Edge Case
Will the above code work if matrix size is 1 ?
No, since the loops run N-1 times, therefore we have to handle it separately.
---
### Question
Print elements in spiral order in clockwise direction.
|**13**|**14**|**12**|**8**|
|-----|-----|-----|-----|
|**9**|**1**|**2**|**7**|
|**0**|**4**|**3**|**0**|
|**10**|**5**|**6**|**11**|
**Choices**
- [ ] [13, 9, 0, 10, 5, 6, 11, 0, 7, 8, 12, 14, 1, 4, 2, 3]
- [ ] [13, 14, 12, 8, 9, 1, 2, 7, 0, 4, 3, 0, 10, 5, 6, 11]
- [x] [13, 14, 12, 8, 7, 0, 11, 6, 5, 10, 0, 9, 1, 2, 3, 4]
- [ ] [13, 14, 12, 8, 10, 5, 6, 11, 9, 1, 2, 7, 0, 4, 3, 0]
#### Pseudocode
```cpp
Function printBoundaryElements(Mat[][], N) {
i = 0 j = 0
while (N > 1) {
// Print N-1 elements of first row from left to right
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
j++
}
// Print N-1 elements of last column from top to bottom
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
i++
}
// Print N-1 elements of last row from right to left
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
j--
}
// Print N-1 elements of first column from bottom to top
for (idx = 1; idx < N; idx++) {
print(Mat[i][j] + ",")
i--
}
N = N - 2
i++
j++
}
if (N == 1) {
print(Mat[i][j] + ",")
}
}
```
#### Complexity
**Time Complexity : $O(N^2)$**
**Space Complexity : O(1)**
---
## What is a submatrices and how can we uniquely identify it
### What is a submatrix?
Same as how a subarray is continuous part of an Array, a submatrix is continuous sub-matrix of a matrix.
Example,
| 11 | 12 |
|:------:|:------:|
| **15** | **16** |
is submatrix of the below matrix.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/028/original/Screenshot_2023-09-27_at_12.18.30_PM.png?1695797348" width=400 />
### How can we uniquely indentify a rectangle ?
A rectangle is made up of 4 coordinates.
1. Top Left (TL)
2. Top Right (TR)
3. Bottom Left (BL)
4. Bottom Right (BR)
**If we pick any two diagonal coordinates, we can uniquely identify a rectangle.**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/690/original/Screenshot_2023-09-26_at_11.28.55_AM.png?1695707964" width=300 />
So, let's say we pick TL and BR.
**Example -**
If TL = (3,2) and BR = (2,3)
Then we know which rectangle we are talking about(shown below).
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/026/original/Screenshot_2023-09-27_at_12.10.03_PM.png?1695796828" width=300 />
So, with the help of TL and BR coordinates(or TR & BL), we can uniquely identify a submatrices.
---
### Problem 5 Sum of all Submatrices Sum
Given a matrix of N rows and M columns determine the sum of all the possible submatrices.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/688/original/Screenshot_2023-09-26_at_11.27.23_AM.png?1695707884)" width=300 />
All Possible sub-matrices are -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/689/original/Screenshot_2023-09-26_at_11.27.38_AM.png?1695707901)" width=600 />
Total Sum = 166
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
This question sounds same as "Sum of all Subarray Sums". We did that question is Intermediate - Subarrays. The technique used was Contribution Technique, where for every element we had to find that in how many subarrays it was part of.
In "Sum of all Submatrices Sums", we have to find that in how many submatrices a particular element is part of.
If we are able to find that, then we just have to add up the individual results.
#### In what all submatrices, a particular element is part of ?
Let's look at the red cell in below figure.
If we combine all the top left cells(marked with green color) with all the bottom right cells(marked with blue color), then in all those submatrices, the red cell will be present.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/691/original/Screenshot_2023-09-26_at_11.29.51_AM.png?1695708017)" width=400 />
#### How to find the number of TL cells and BR cells in which (i,j) is part of.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/692/original/Screenshot_2023-09-26_at_11.31.14_AM.png?1695708100)" width=400 />
**TOP LEFT:**
rows: [0 i]
cols: [0 j]
total cells = (i+1) * (j+1)
**BOTTOM RIGHT:**
rows: [i N-1]
cols: [j M-1]
total cells = (N-i) * (M-j)
#### Now, to find the total submatrices of whish (i,j) is part of -
**contribution of (i,j) = TOP LEFT * BOTTOM RIGHT**
Every top left cell can be combined with every bottom right cell.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/695/original/Screenshot_2023-09-26_at_11.32.42_AM.png?1695708437)" width=400 />
For (2,2)
TOP LEFT:
3 * 3 = 9
BOTTOM RIGHT
(5-2) * (6-2) = 3 * 4 = 12
Total matrices of which (2,2) is part of 9 * 12.
---
### Question
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/696/original/Screenshot_2023-09-26_at_11.33.03_AM.png?1695708473" width=400 />
In a matrix of size 4 * 5, in how many submatrices (1,2) is part of ?
**Choices**
- [ ] 56
- [x] 54
- [ ] 15
- [ ] 16
#### Pseudocode
```cpp
total = 0
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
top_left = (i + 1) * (j + 1);
bottom_right = (N - i) * (M - j);
contribution = A[i][j] * top_left * bottom_right;
total += contribution
}
}
return total
```

View File

@@ -0,0 +1,456 @@
# Lecture | Advanced DSA: Arrays 3 - Interview Problems
---
## Merge Intervals
An Interval is defined by start and end time, where start <= end.
Say we are given a list of Intervals, we will have to merge them if they overlap.
Let's look at them below -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/054/original/Screenshot.png?1696314602)" width=700 />
### Non-Overlapping Condition
Say there are two Intervals, I1 {s1 e1} & I2 {s2 e2}
Then the condition for them to not overlap is -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/055/original/Screenshot_2023-09-27_at_1.25.30_PM.png?1696314640)" width=500 />
```javascript
if(s2 > e1 || s1 > e2)
```
So, if above condition is not followed, it says that Intervals are overlapping!
### How to merge overlapping Intervals ?
**[I1.start , I1.end] & [I2.start , I2.end]**
After merging -
**[min(I1.start, I2.start) , max(I1.end, I2.end)]**
---
### Question
If the intervals [3, 8] and [5, 12] are given, do they overlap?
**Choices**
- [x] Yes
- [ ] No
### Explanation:
Answer: Yes
The intervals [3, 8] and [5, 12] overlap because 8 is greater than 5. The overlapping area is [5, 8]
---
### Question
What is the correct way to represent the merged result of intervals [6, 10] and [8, 15]?
**Choices**
- [x] [6, 15]
- [ ] [6, 8, 10, 15]
- [ ] [6, 10] and [8, 15]
- [ ] [8, 10]
### Explanation:
[6, 15]
This is because the merging of intervals involves combining overlapping intervals into a single, continuous interval
---
### Problem 1 : Merge sorted Overlapping Intervals
**Problem Statement**
Given a sorted list of overlapping intervals, sorted based on start time, merge all overlapping intervals and return sorted list.
**Input:**
Interval[] = {(0,2), (1,4), (5,6), (6,8), (7,10), (8,9), (12,14)}
**Output:**
{(0,4), (5,10), (12,14)}
#### Explanation:
| Interval 1 | Interval 2 | | Answer Interval List |
|:----------:|:----------:|:---------------:|:--------------------:|
| 0-2 | 1-4 | Overlapping | 0-4 |
| 0-4 | 5-6 | Not Overlapping | 0-4, 5-6 |
| 5-6 | 6-8 | Overlapping | 0-4, 5-8 |
| 5-8 | 7-10 | Overlapping | 0-4, 5-10 |
| 5-10 | 8-9 | Overlapping | 0-4, 5-10 |
| 5-10 | 12-14 | Not Overlapping | 0-4, 5-10, 12-14 |
#### The Array Is Sorted Based on Start Time. What Is the Overlapping Condition?
Say start time of A < start time of B
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/056/original/Screenshot_2023-09-27_at_1.55.29_PM.png?1696314693)" width=300 />
Overlapping Condition -
**If start of B <= end of A**
---
### Question
Given a sorted list of overlapping intervals, sorted based on start time, merge all overlapping intervals and return sorted list.
**Input:**
Interval[] = { (1,10), (2, 3), (4, 5), (9, 12)}
**Choices**
- [x] (1, 12)
- [ ] (1, 10), (9, 12)
- [ ] (1, 9), (9, 12)
- [ ] No Change
#### Problem 1 Approach
* Create an array to store the merged intervals.
* If the current and ith intervals overlaps, merge them. In this case update the current interval with the merged interval.
* Else, insert the current interval to answer array since it doesn't overlap with any other interval and update the current Interval to ith Interval.
#### Dry Run
**Input:**
Interval[] = {(0,2), (1,4), (5,6), (6,8), (7,10), (8,9), (12,14)}
#### Explanation:
| current | ith | | After merging | answer list |
|:-------:|:-----:|:---------------:|:-------------:|:-----------:|
| 0-2 | 1-4 | Overlapping | 0-4 | |
| 0-4 | 5-6 | Not Overlapping | Not needed | 0-4 |
| 5-6 | 6-8 | Overlapping | 5-8 | 0-4 |
| 5-8 | 7-10 | Overlapping | 5-10 | 0-4 |
| 5-10 | 8-9 | Overlapping | 5-10 | 0-4 |
| 5-10 | 12-14 | Not Overlapping | Not needed | 0-4, 5-10 |
| 12-14 | end | | | |
At the end, we are left with the last interval, so add it to the list.
#### Pseudocode
```cpp
//Already a class/structure will be present for Interval
//We will only need to create an answer array of type Interval
list < Interval > ans;
// Current Segment
int cur_start = A[0].start, cur_end = A[0].end;
for (int i = 1; i < A.size(); i++) {
// if i'th interval overlaps with current interval
if (A[i].start <= cur_end) {
// merging them
cur_end = max(cur_end, A[i].end);
} else {
//adding current interval to answer.
//create a new Interval
Interval temp(cur_start, cur_end); //if struct is declared, otherwise if class is declared then we can simply use new keyword
ans.push_back(temp);
// update cur Interval to ith
cur_start = A[i].start;
cur_end = A[i].end;
}
}
Interval temp(cur_start, cur_end);
ans.push_back(temp);
return ans;
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 2 Sorted Set of Non Overlapping Intervals
Given a sorted list of overlapping intervals based on start time, insert a new interval such that the final list of intervals is also sorted and non-overlapping.
Print the Intervals.
**Example 1:**
**N = 9**
(1,3)
(4,7)
(10,14)
(16,19)
(21,24)
(27,30)
(32,35)
(38,41)
(43,50)
New Interval
**(12, 22)**
**Explanation:**
| ith | new Interval | Overlaps? | Print |
|-------|----------|----------|-----------------|
| (1,3) | (12,22) | No | (1,3) |
| (4,7) | (12,22) | No | (4,7) |
| (10,14) | (12,22) | Yes; merged: (10,22) ||
| (16,19) | (10,22) | Yes; merged: (10,22) ||
| (21,24) | (10,22) | Yes; merged: (10,24) ||
| (27,30) | (10,22) | No; small new Interval gets printed first |(10,22)|
| (32,35)| | |(32,35)|
| (38,41)| | |(38,41) |
| (43,50)| | | (43,50)|
**Please Note:** Once the new Interval gets printed, all the Intervals following it also gets printed.
**More Examples**
**Example 2:**
**N = 5**
(1,5)
(8,10)
(11,14)
(15,20)
(21,24)
New Interval
**(12, 24)**
| ith | new Interval | Overlaps? | Print |
|:-------:|:------------:|:--------------------:|:------:|
| (1,5) | (12, 24) | No | (1,5) |
| (8,10) | (12, 24) | No | (8,10) |
| (11,14) | (12, 24) | Yes; merged:(11, 24) | |
| (15,20) | (11, 24) | Yes; merged:(11, 24) | |
| (21,24) | (11, 24) | Yes; merged:(11, 24) | |
We are done with all the intervals but left the new Interval at the end; in this case we have to print the new Interval.
**Example 3:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/057/original/Screenshot_2023-09-27_at_2.30.39_PM.png?1696314838)" width=500 />
---
### Question
If the sorted set of non-overlapping intervals is [1, 5], [6, 10], and [12, 15], what happens if you add the interval `[4, 7]` such that the final list of intervals is also sorted and non-overlapping.?
**Choices**
- [x] [1, 10] and [12, 15]
- [ ] [1, 5], [4, 7], [6, 10], [12, 15]
- [ ] [1, 5] and [6, 10] only
- [ ] No change
#### Explanation:
(1,5)
(6,10)
(12,15)
New Interval
**(4, 7)**
| ith | new Interval | Overlaps? | Print |
|:-------:|:------------:|:--------------------:|:------:|
| (1,5) | (4, 7) | Yes; merged:(1, 7) | |
| (6,10) | (1, 7) | Yes; merged:(1, 10) | |
| (12,15) | (1, 10) | No; small new Interval gets printed first | (1, 10) |
| (12,15) | | | (12, 15) |
Thus after merging, the intervals are [1, 10] and [12, 15]
#### Problem 2 Pseudocode
```cpp
void merge(int Interval[], int nS, int nE) {
for (int i = 0; i < N; i++) {
int L = Interval[i].start, R = Interval[i].end;
//Not Overlapping
if (nS > R) {
print({
L,
R
});
}
// new Interval is not overlapping and is smaller
// print new Interval and then all the remaining Intervals
else if (L > nE) {
print({
nS,
nE
});
for (int j = i; j < N; j++) {
print({
Interval[j].start,
Interval[j].end
})
}
return;
} else {
nS = min(L, nS);
nE = max(R, nE);
}
}
print({
nS,
nE
});
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 3 Find First Missing Natural Number
Given an unsorted array of integers, Find first missing Natural Number.
**Examples**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/058/original/Screenshot_2023-09-27_at_2.42.15_PM.png?1696314889" width=500 />
---
### Question
In the array [5, 3, 1, -1, -2, -4, 7, 2], what is the first missing natural number?
**Choices**
- [x] 4
- [ ] 6
- [ ] -3
- [ ] 8
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
---
### Find First Missing Natural Number Solution Approach
#### Approach 1: Brute Force
Check for all the numbers from 1 till we get the answer
**T.C -** O(N * ans)
Here, in the worst case answer can go uptil N+1, in case if all numbers from 1 to N are present in the array.
**Example -** {4, 1, 3, 2}
Here we will have to iterate till 5, ie. N+1.
#### Idea
**Can we utilise the fact that answer can be out of 1 to N+1?**
If any number other than 1 to N is present, then missing is out of 1 to N only.
If all elements from 1 to N are present, then it will be N+1.
Say we start checking if 1 is present or not, we somehow want to mark the presence of 1.
Now, since we can't use extra space, so we can use indices to mark the presence of a number.
Index 0 can be used to mark presence of 1.
Index 1 can be used to mark presence of 2.
Index 2 can be used to mark presence of 3.
so on....
**Now how do we mark the presence ?**
**One Solution:**
```plaintext
We can set element at that index as negative.
```
*But what if negative number is part of the input?*
**Let's assume only positive numbers are present**
We can use indices to mark the presence of a number.
We can set element at that index as negative.
**A[ ] = {8, 1, 4, 2, 6, 3}**
```plaintext
N = 6
Answer can be from [1 7]
So, if any number is beyond this range, we don't care!
```
| index | element | presence marked at index | state of the array |
|:-----:|:-------:|:-------------------------------------:|:-----------------------:|
| 0 | 8 | don't care, since out of answer range | |
| 1 | 1 | 0 | {-8, 1, 4, 2, 6, 3} |
| 2 | 4 | 3 | {-8, 1, 4, -2, 6, 3} |
| 3 | 2 | 1 | {-8, -1, 4, -2, 6, 3} |
| 4 | 6 | 5 | {-8, -1, 4, -2, 6, -3} |
| 5 | 3 | 2 | {-8, -1, -4, -2, 6, -3} |
Now, we can just iterate from left to right and whichever element is not ve-, we can return i+1 as the answer.
**Example: {-8, -1, -4, -2, 6, -3}**
Here, index: 4 is +ve, hence 5 is the answer.
**NOTE:** Since we are marking elements as negative, so when checking presence of a certain number, we'll have to consider the absolute value of it.
#### Pseudocode
```cpp
for (int i = 0; i < N; i++) {
int ele = abs(A[i]);
if (ele >= 1 && ele <= N) {
int idx = ele - 1;
A[idx] = -1 * abs(A[i]);
}
}
```
---
### Find First Missing Natural Number For Negative Numbers
#### How to resolve for negative numbers ?
Will negatives ever be our answer?
**NO!**
So, we don't have to care about them!
Should we change them to ve+ ?
**NO!** They may fall in our answer range.
Should we mark them 0?
**NO!** Then we will not be able to mark the presence of a number!
***We can just change negative number to a number that is out of our answer range. **It can be N+2**.***
```cpp
for (int i = 0; i < N; i++) {
if (A[i] <= 0) {
A[i] = N + 2;
}
}
for (int i = 0; i < N; i++) {
int ele = abs(A[i]);
if (ele >= 1 && ele <= N) {
int idx = ele - 1;
A[idx] = -1 * abs(A[i]);
}
}
for (int i = 0; i < N; i++) {
if (A[i] > 0) return i + 1;
}
return N + 1;
```
>Please show a dry run on - {4, 0, 1, -5, -10, 8, 2, 6}
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)

View File

@@ -0,0 +1,482 @@
# Backtracking
---
### Question
What is the output of below code for N = 7 ?
```
int magicfun( int N) {
if ( N == 0)
return 0;
else
return magicfun(N/2) * 10 + (N % 2);
}
```
**Choices**
- [ ] 100
- [x] 111
- [ ] 99
- [ ] 112
**Explanation**
```cpp
magicfun(7)
magicfun(3) * 10 + 1
magicfun(1) * 10 + 1
magicfun(0) * 10 + 1
0
```
---
### Question
Time complexity of below code is?
```
int magicfun( int N) {
if ( N == 0)
return 0;
else
return magicfun(N/2) * 10 + (N % 2);
}
```
**Choices**
- [x] O(log N)
- [ ] O(1)
- [ ] O(N)
- [ ] O(N/2)
Everytime we are dividing N by 2. Hence complexity will be log N.
---
### Question
Output of below code is?
```
void fun(char s[], int x) {
print(s)
char temp
if(x < s.length/2) {
temp=s[x]
s[x] = s[s.length-x-1]
s[s.length-x-1]=temp
fun(s, x+1)
}
}
```
Run for fun("SCROLL", 0)
**Choices**
- [ ] SCROLL
SCROLL
SCROLL
SCROLL
- [x] SCROLL
LCROLS
LLROCS
LLORCS
- [ ] LLORCS
SCROLL
LCROLS
LLROCS
We start with
(SCROLL, 0); line 2 runs; print => SCROLL
since 0 < 6/2, we run the if block and index 0 gets swapped with 5
(LCROLS, 1); line 2 runs; print => LCROLS
since 1 < 6/2, we run the if block and index 1 gets swapped with 4
(LLROCS, 2); line 2 runs; print => LLROCS
since 2 < 6/2, we run the if block and index 2 gets swapped with 3
(LLORCS, 3); line 2 runs; print => LLORCS
since 3 not less than 6/2, we skip if block and come back from recursion
---
### Question
Time Complexity of below code is?
```
void fun(char s[], int x) {
print(s)
char temp
if(x < s.length/2) {
temp=s[x]
s[x] = s[s.length-x-1]
s[s.length-x-1]=temp
fun(s, x+1)
}
}
```
**Choices**
- [ ] O(N^2)
- [ ] O(1)
- [x] O(N)
- [ ] O(N/2)
We are only iterating till half of the string. In the worst case, we can start at 0th index.
Therefore, #iterations = N/2
Hence, T.C = O(N)
S.C is also O(N) since call will be made for half of the string.
---
## What is Backtracking
The above process is known as **Backtracking**.
Let's try to understand the concept of backtracking by a very basic example. We are given a set of words represented in the form of a tree. The tree is formed such that every branch ends in a word.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/170/original/backtracking1.jpeg?1696932758" width="500" />
Our task is to find out if a given word is present in the tree. Let's say we have to search for the word **AIM**. A very brute way would be to go down all the paths, find out the word corresponding to a branch and compare it with what you are searching for. You will keep doing this unless you have found out the word you were looking for.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/171/original/backtracking2.jpeg?1696932836" width="500" />
In the diagram above our brute approach made us go down the path for ANT and AND before it finally found the right branch for the word AIM.
The backtracking way of solving this problem would stop going down a path when the path doesn't seem right. When we say the path doesn't seem right we mean we come across a node which will never lead to the right result. As we come across such node we back-track. That is go back to the previous node and take the next step.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/172/original/backtracking3.jpeg?1696932854" width="500" />
In the above diagram backtracking didn't make us go down the path from node N. This is because there is a mismatch we found early on and we decided to go back to the next step instead. Backtracking reduced the number of steps taken to reach the final result. This is known as pruning the recursion tree because we don't take unnecessary paths.
---
### Problem 1 : Print Valid Parenthesis Continued
#### Explanation
As shown in the picture below: ) is an invalid string, so every string prefixed with it is also invalid, and we can just drop it.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/173/original/5.png?1696932991" width="500" />
To ensure that the current string is always valid during the backtracking process, we need two variables `left_count` and `right_count` that record the number of left and right parentheses in it, respectively.
Therefore, we can define our recursive function as `solve(cur_string, left_count, right_count)` that takes the current string, the number of left parentheses, and the number of right parentheses as arguments. This function will build valid combinations of parentheses of length 2n recursively.
The function adds more parentheses to cur_string only when certain conditions are met:
* If **`left_count < n`**, it suggests that a left parenthesis can still be added, so we add one left parenthesis to cur_string, creating a new string new_string = cur_string + (, and then call `solve(new_string, left_count + 1, right_count)`.
* If **`left_count > right_count`**, it suggests that a right parenthesis can be added to match a previous unmatched left parenthesis, so we add one right parenthesis to cur_string, creating a new string new_string = cur_string + ), and then call solve(new_string, left_count, right_count + 1).
This function ensures that the generated string of length 2n is valid, and adds it directly to the answer. By only generating valid strings, we can avoid wasting time checking invalid strings.
#### Dry Run for N = 2, means overall length will be 4.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/059/943/original/Screenshot_2023-12-21_at_7.38.01_PM.png?1703167693" width="500"/>
- Here **"(())" and "()()"** are valid answers.
#### PseudoCode
```cpp
void solve(str, N, opening, closing) { //also taking given N value in parameter
// base case
if (str.length() == 2 N) {
print(str);
return;
}
if (opening < N) {
solve(N, str + '(', opening + 1, closing)
}
if (closing < opening) {
solve(N, str + ')', opening, closing + 1)
}
}
```
#### Complexity
- **Time Complexity:** O(2<sup>N</sup>)
- **Space Complexity:** O(N)
---
### Definition of Subset and Subsequences
#### Definition of Subset and Example
A subset is often confused with subarray and subsequence but a subset is nothing but any possible combination of the original array (or a set).
For example, the subsets of array arr = [1, 2, 3, 4, 5] can be:
[3, 1]
[2, 5]
[1, 2], etc.
So, we can conclude that subset is the superset of subarrays i.e. all the subarrays are subsets but vice versa is not true.
#### Definition of Subsequence and Example
As the name suggests, a subsequence is a sequence of the elements of the array obtained by deleting some elements of the array. One important thing related to the subsequence is that even after deleting some elements, the sequence of the array elements is not changed. Both the string and arrays can have subsequences.
The subsequence should not be confused with the subarray or substring. The subarray or substring is contiguous but a subsequence need not to be contiguous.
For example, the subsequences of the array arr : [1, 2, 3, 4] can be:
[1, 3]
[2, 3, 4]
[1, 2, 3, 4], etc.
Note: A subarray is a subsequence, a subsequence is a subset but the reverse order is not correct.
---
### Problem 2 Subsets
Given an array with distinct integers. Print all the subsets using recursion.
**Example**
**Input:** [1, 2, 3]
**Output:** {[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]}
Total Subsets possible are **2^N**
For every element, there can be two options:
- It is **considered** as part of a subset
- It is **not considered** as part of a subset
Say there are **3 elements**, for each of them we have above two options, hence **2 * 2 * 2 = 2^N^** are the total options.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
The approach to solve the problem is to use backtracking.
For each element, I have two choices whether to keep it or not, I execute my choice and then ask recursion to do the remaining work.
Let us take an example of `[1, 2, 3]`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/611/original/Screenshot_2023-10-14_at_12.48.48_PM.png?1697267948" width="700"/>
#### Psuedocode
```cpp
list < list < int >> ans;
void subsets(list < int > A, list < int > currset, int idx) {
//base case
if (idx == A.size()) {
ans.add(currset);
return;
}
//for every ele in A, we have 2 choices
//choice 1 : keep it in currset
currset.add(A[idx]);
subsets(A, currset, idx + 1);
//choice 2 : Don't keep it in currset
currset.remove_back();
subsets(A, currset, idx + 1);
}
```
NOTE: For producing individual sorted subsets, we need to sort the given array first. We will get the desired result with this since elements are being processed in sequence.
#### Dry Run
A = {2, 6, 9}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/621/original/IMG_ACCE165F2ED6-1.jpeg?1697272534" width="800"/>
Continued
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/622/original/IMG_7A8C88629961-1.jpeg?1697272592" width="800"/>
#### Complexity
- **Time Complexity:** O(2^N^)
- **Space Complexity:** O(N)
---
### Question
What is the count of total permutations of a string with unique characters? (N=String length)
**Choices**
- [ ] N$^2$
- [ ] N + (N + 1) / 2
- [ ] N * (N - 1) / 2
- [x] N!
---
### Problem 3 : Permutation
Given a character array with distinct elements. Print all permutations of it without modifying it.
**Example**
For string **abc**, of length 3, we have total 3! = 6 permutations:
- abc
- acb
- bac
- bca
- cab
- cba
**Input:** abc
**Output:** abc acb bac bca cab cba
**Constraint**
We don't have duplicate characters in a string.
---
## Permutations Idea
- Every permutation has n number of characters, where n is the length of the original string.
- So initially we have n number of empty spots.
`_ _ _`
- And we need to fill these empty spots one by one.
- Let us start with the first empty spot, which means from the 0th index.
- For the 0th index we have three options, `a, b, and c`, any of the three characters can occupy this position.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/171/original/upload_0abf2bd81e5b53817696c11f014cc9ca.png?1697613060" width="200"/>
- If `a` will occupy 0th index, then we have `a _ _`, and if `b` will occupy 0th index, then we have `b _ _`, and if `c` will occupy 0th index, then we have `c _ _`,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/172/original/upload_364bad15c465630226ebbc98779a6d3c.png?1697613083" width="300"/>
- Now the first spot is occupied, now we have to think about the second spot.
- Now for a second spot we have only options left.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/174/original/upload_2a38e8136fc2617770465018b5af1300.png?1697613113" width="400"/>
- Now when the character occupies the second spot, then we get.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/175/original/upload_66f805654ae3f8cd1fda572e55b0c34a.png?1697613142" width="500"/>
- Now for the last spot, every string has left with a single character, like in `a b _`, we are only left with the character `c`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/177/original/upload_436a54570d0816cdfe3aa5e8bbfabe51.png?1697613229" width="500"/>
- Now this character will occupy the last spot.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/178/original/upload_6c85f4358549b98ac08cf4f97c8171a8.png?1697613260" width="500"/>
We are setting characters at positions one by one. So **We need to keep track of visited/used characters.**
---
### Permutations PsuedoCode
```cpp
void permutations1(char[] arr, idx, ans[N], visited[N]) {
if (idx == arr.length) {
print(ans[])
return
}
for (i = 0; i < N; i++) { // All possibilities
if (visited[i] == false) { // valid possibilities
visited[i] = true;
ans[idx] = arr[i];
permutations1(arr, idx + 1, ans, visited); // recursive call for next index
visited[i] = false; //undo changes
}
}
}
```
### Permutations - Dry Run
Let us suppose we have the string `arr[] = a b c` , and initially ans array is empty, `ans[] = _ _ _`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/179/original/upload_078759cd3474f5320a513fb2a368988b.png?1697613308" width="500"/>
- Initially, we are at index 0,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/180/original/upload_09b0f2e04af2646653401912f7bdf11e.png?1697613336" width="500"/>
- Now i vary from 0 to `n-1`, so it will go from 0 to 2, as here the length of the string is 3.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/181/original/upload_6a469a8219e1a655017a207a21d09a20.png?1697613366" width="500"/>
- Now when `i = 0`, we will check that `visited[i] == false`, so this condition is true, we mark `visited[i] == true` and `ans[0] = arr[0] = a`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/182/original/upload_e4640b1635abf383ca90d29bc8d5c358.png?1697613396" width="500"/>
- Now it makes a recursive call for the next index, `permutations1(arr, 1, ans, visited)`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/183/original/upload_88edd4512c97a6dde2d3c315f711e918.png?1697613421" width="500"/>
- Inside this call, `idx != arr.length`, so we will continue further, now inside this call, the loop will go from 0 to 2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/184/original/upload_0d20be040bcf8c504abc12224bcadd57.png?1697613451" width="500"/>
- But in case `i = 0`, now `visited[0] != false`, so in this iteration we will not enter inside the if condition, i will simply get incremented.
- Now `i = 1`, we will check that `visited[i] == false`, so this condition is true, we mark `visited[1] == true` and `ans[1] = arr[1] = b`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/185/original/upload_b27ef00f4cf93cd4b7f09cc8dbe9aa2e.png?1697613482" width="500"/>
- Now it will make recussive call for `idx + 1`, `permutations1(arr, 2, ans, visited)`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/186/original/upload_576781e6dedc3c669d373a23b090798c.png?1697613508" width="500" />
- Now inside this new recursive again loop will run from 0 to 2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/187/original/upload_fde4ce4ddcc35d80971d5cd59443ecea.png?1697613538" width="500" />
- Now when `i = 0`, now `visited[0] != false`, so in this iteration, we will not enter inside the if condition, i will simply get incremented.
- Now `i = 1`, again `visited[1] != false`, so in this iteration, we will not enter inside the if condition, i will simply get incremented.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/188/original/upload_359a967fc34e931c591a6a1905528841.png?1697613567" width="500" />
- Now `i = 2`, we will check that `visited[i] == false`, so this condition is true, we mark `visited[2] == true` and `ans[2] = arr[2] = c`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/190/original/upload_a58c34a007477508cf23705adccd3cbf.png?1697613618" width="500" />
- Now it will make recussive call for `idx + 1`, `permutations1(arr, 3, ans, visited)`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/191/original/upload_bbfc59007f79a5a86ba08ac548919790.png?1697613649" width="500"/>
- Inside this call, our `idx == arr.length`, so print `ans`, so **abc will be printed**, and it will return. And after returning `visited[2] = false`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/192/original/upload_07d6ae1b0fed0c6bedfc84b683e474d0.png?1697613689" width="500" />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/193/original/upload_11c5e9b4db673d5f7ea44a7a032efa05.png?1697613725" width="500" />
- Now for `arr, 2, ans, visited`, all iterations are completed. So it will also return and `visited[1] = false`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/194/original/upload_0028a2144ea0380f98c6647b95f62530.png?1697613757" width="500" />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/195/original/upload_f50656c21e03faf10aaadd839d20ea50.png?1697613780" width="500" />
- Now for `arr, 1, ans, visited`, we are left for the iteration `i = 2`, so it will check for `visited[i] == false`, as `visited[2] = false`, so go inside the if condition and `visited[2] == true` and `ans[1] = arr[2] = c`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/196/original/upload_a978fb05a4dac41b99dfcb5a635d3b67.png?1697613812" width="500" />
- Now it will make the recursive call for `arr, 2, ans, visited`. And inside this call again loop will run from 0 to 2. Now `visited[0] == true`, so it will for `i = 1`, and so it will check for `visited[i] == false`, as `visited[1] = false`, so go inside the if condition and `visited[1] == true` and `ans[2] = arr[1] = b`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/197/original/upload_25cac80b472a378908a107f9a9a6bdb0.png?1697613836" width="500" />
- Now it will make recussive call for `idx + 1`, `permutations1(arr, 3, ans, visited)`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/198/original/upload_7444728790ca1e74595a2c3d3aaeae07.png?1697613863" width="500"/>
- Now inside this call `idx == arr.length`, so it will print `ans`, so **acb will be printed**, and it will return.
In this way, all the permutations will be printed.

View File

@@ -0,0 +1,455 @@
# Bit Manipulation 1
## Truth Table for Bitwise Operators
Below is the truth table for bitwise operators.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/031/original/Screenshot_2023-10-03_at_11.07.51_AM.png?1696311508" width="350" />
## Basic AND XOR OR Properties
### Basic AND Properties
1. **Even/Odd Number**
In binary representation, if a number is even, then its least significant bit (LSB) is 0.
Conversely, if a number is odd, then its LSB is 1.
* **A & 1 = 1** (if A is odd)
```cpp
181 = 10110101 //181 is odd, therefore LSB is 1
10110101 & 1 = 1 // Performing Bitwise AND Operation
Since, 181 is odd, Bitwise AND with 1 gave 1.
```
* **A & 1 = 0** (if A is even)
```cpp
180 = 10110100 //180 is even, therefore LSB is 0
10110100 & 1 = 0 // Performing Bitwise AND Operation
Since, 180 is even, Bitwise AND with 1 gave 0.
```
2. **A & 0 = 0** (for all values of A)
3. **A & A = A** (for all values of A)
### Basic OR Properties
1. **A | 0 = A** (for all values of A)
2. **A | A = A** (for all values of A)
### Basic XOR Properties
1. **A ^ 0 = A** (for all values of A)
2. **A ^ A = 0** (for all values of A)
### Commutative Property
The order of the operands does not affect the result of a bitwise operation.
```cpp
A & B = B & A // Bitwise AND
A | B = B | A // Bitwise OR
A ^ B = B ^ A // Bitwise XOR
```
### Associative Property
* It states that the grouping of operands does not affect the result of the operation.
* In other words, if we have three or more operands that we want to combine using a bitwise operation, we can group them in any way we want, and the final result will be the same.
```cpp
(A & B) & C = A & (B & C) // Bitwise AND
(A | B) | C = A | (B | C) // Bitwise OR
(A ^ B) ^ C = A ^ (B ^ C) // Bitwise XOR
```
---
### Question
Evaluate the expression: a ^ b ^ a ^ d ^ b
**Choices**
- [ ] a ^ b ^ a ^ b
- [ ] b
- [ ] b ^ d
- [x] d
We can evaluate the expression as follows:
```cpp
a ^ b ^ a ^ d ^ b = (a ^ a) ^ (b ^ b) ^ d // grouping the a's and the b's
= 0 ^ 0 ^ d // since a ^ a and b ^ b are both 0
= d // the result is d
```
Therefore, the expression a ^ b ^ a ^ d ^ b simplifies to d.
### Question
Evaluate the expression: 1 ^ 3 ^ 5 ^ 3 ^ 2 ^ 1 ^ 5
**Choices**
- [ ] 5
- [ ] 3
- [x] 2
- [ ] 1
We can evaluate the expression as follows:
```cpp
1 ^ 3 ^ 5 ^ 3 ^ 2 ^ 1 ^ 5 = ((1 ^ 1) ^ (3 ^ 3) ^ (5 ^ 5)) ^ 2 // grouping the pairs of equal values and XORing them
= (0 ^ 0 ^ 0) ^ 2 // since x ^ x is always 0
= 0 ^ 2 // since 0 ^ y is always y
= 2 // the result is 2
```
Therefore, the expression 1 ^ 3 ^ 5 ^ 3 ^ 2 ^ 1 ^ 5 simplifies to 2.
### Left Shift Operator (<<)
* The left shift operator (<<) shifts the bits of a number to the left by a specified number of positions.
* The left shift operator can be used to multiply a number by 2 raised to the power of the specified number of positions.
Example: a = 10
Let's see a dry run on smaller bit representation(say 8)
Binary Representation of 10 in 8 bits: 00001010
```cpp
(a << 0) = 00001010 = 10
(a << 1) = 00010100 = 20 (mutiplied by 2)
(a << 2) = 00101000 = 40 (mutiplied by 2)
(a << 3) = 01010000 = 80 (mutiplied by 2)
(a << 4) = 10100000 = 160 (mutiplied by 2)
(a << 5) = 01000000 = 64 (overflow, significant bit is lost)
```
In general, it can be formulated as:
```cpp
a << n = a * 2^n
1 << n = 2^n
```
However, it's important to note that left shifting a number beyond the bit capacity of its data type can cause an **overflow** condition.
In above case, if we shift the number 10 more than 4 positions to the left an overflow will occur.
```cpp
(a << 5) = 01000000 = 64
//(incorrect ans due to overflow)
// correct was 320 but it is too large to get stored in 8 bits
```
**Note:** We can increase the number of bits, but after a certain point it will reach limit and overflow will occur.
### Right Shift Operator (>>)
* The right shift operator (>>) shifts the bits of a number to the right by a specified number of positions.
* When we right shift a binary number, the most significant bit (the leftmost bit) is filled with 0.
* Right shift operator can also be used for division by powers of 2.
Lets take the example of the number 20, which is represented in binary as 00010100. Lets suppose, it can be represented just by 8 bits.
```cpp
(a >> 0) = 00010100 = 20
(a >> 1) = 00001010 = 10 (divided by 2)
(a >> 2) = 00000101 = 5 (divided by 2)
(a >> 3) = 00000010 = 2 (divided by 2)
(a >> 4) = 00000001 = 1 (divided by 2)
(a >> 5) = 00000000 = 0 (divided by 2)
```
In general, it can be formulated as:
```cpp
a >> n = a/2^n
1 >> n = 1/2^n
```
Here, overflow condition doesn't arise.
### Question
What will we get if we do 1 << 3 ?
**Choices**
- [ ] 1
- [x] 8
- [ ] 3
- [ ] 4
---
### Power of Left Shift Operator
### OR( | ) Operator
**Left Shift Operator** can be used with the **OR** operator to **SET** the **i<sup>th</sup>** bit in the number.
```
N = (N | (1<<i))
```
It will SET the **i<sup>th</sup>** bit if it is UNSET else there is no change.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/167/original/or_operator.png?1706037170" width=500/>
### XOR( ^ ) Operator
**Left Shift Operator** can be used with the **XOR** operator to **FLIP(or TOGGLE)** the **i<sup>th</sup>** bit in the number.
```
N = (N ^ (1<<i))
```
After applying the operation, if the **i<sup>th</sup>** bit is SET, then it will be UNSET or vice-versa.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/165/original/xor_operator.png?1706037082" width=500/>
### AND( & ) Operator
**Left Shift Operator** can be used with **AND** operator to check whether the **i<sup>th</sup>** bit is set or not in the number.
```
X = (N & (1<<i))
```
if the value of X is 0 then the **i<sup>th</sup>** bit is unset. Else the *i-th* bit is set.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/168/original/And_operator.png?1706037268" width=500/>
---
### Problem 1 Check whether ith bit in **N** is SET or not
Check whether the **i<sup>th</sup>** bit in **N** is SET or not.
#### Approach
Taking **AND with 1** can help us.
0 & 1 = 0
1 & 1 = 1
1. We can shift 1 to the ith bit.
2. If `X = (N & (1<<i))`
* if X > 0, then **i<sup>th</sup>** bit is set.
* else **i<sup>th</sup>** bit is not set.
**Example**
Suppose we have
```
N = 45
i = 2
```
The binary representation of 45 is:
```
1 0 1 1 0 1
```
The binary representation of (1<<2) is:
```
0 0 0 1 0 0
```
45 & (1<<2) is
```
0 0 0 1 0 0
```
It is greater than 0. Hence **i<sup>th</sup>** bit is SET.
#### Pseudocode
```cpp
function checkbit(int N, int i) {
if (N & (1 << i)) {
return true;
} else {
return false;
}
}
```
#### Complexity
**Time Complexity** - O(1).
**Space Complexity** - O(1).
---
### Problem 2 Count the total number of SET bits in N
Given an integer **N**, count the total number of SET bits in **N**.
**Input**
```
N = 12
```
**Output**
```
2
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach 1
Iterate over all the bits of integer(which is maximum 32) and check whether that bit is set or not. If it is set then increment the answer(initially 0).
```cpp
function countbit(int N) {
int ans = 0;
for (i = 0; i < 32; i++) {
if (checkbit(N, i)) {
ans = ans + 1;
}
}
return ans;
}
```
Here, checkbit function is used to check whether the **i<sup>th</sup>** bit is set or not.
#### Approach 2
To count the number of SET bits in a number, we can use a Right Shift operator as:
* Initialize a count variable to zero.
* While the number is not equal to zero, do the following:
* Increment the count variable if the **0<sup>th</sup>** bit of the number is 1.
* Shift the number one bit to the right.
* Repeat steps a and b until the number becomes zero.
* Return the count variable.
```cpp
function countbit(int N) {
int ans = 0;
while (N > 0) {
if (N & 1) {
ans = ans + 1;
}
N = (N >> 1);
}
return ans;
}
```
---
### Question
What is the time complexity to count the set bits ?
**Choices**
- [x] log N
- [ ] N
- [ ] N^2
- [ ] 1
**Explanation**
For both of the above approaches,
* **Time Complexity** - O(log<sub>2</sub>(N))
Since N is being repeatedly divided by 2 till it is > 0.
* **Space Complexity** - O(1).
---
### Problem 3 Unset the ith bit of the number N if it is set
**UNSET** the **i<sup>th</sup>** bit of the number **N** if it is set.
**Example**
Suppose we have a number ```N = 6```
Binary Representation of 6:
```
1 1 0 0
```
We have to unset its 2nd bit
```
1 0 0 0
```
#### Approach
First of all, we can check if the bit is set or not by taking & with 1.
```
X = (N & (1<<i))
```
Then, we have two condition:
* if X > 0, it means the **i<sup>th</sup>** bit is SET. To UNSET that bit do:
`N = (N ^ (1<<i))` {XOR with 1 toggles the bit}
* else if it is UNSET, no need to do anything.
#### Pseudocode
```cpp
Function unsetbit(int N, int i) {
int X = (N & (1 << i));
if (checkbit(N, i)) {
N = (N ^ (1 << i));
}
}
```
#### Complexity
**Time Complexity** - O(1)
**Space Complexity** - O(1)
---
### Problem 4 SET bits in a range
A group of computer scientists is working on a project that involves encoding binary numbers. They need to create a binary number with a specific pattern for their project. The pattern requires A 0's followed by B 1's followed by C 0's. To simplify the process, they need a function that takes A, B, and C as inputs and returns the decimal value of the resulting binary number. Can you help them by writing a function that can solve this problem efficiently?
**Constraints:**
```
0 <= A, B, C <= 20
```
**Example:**
```
A = 4
B = 3
C = 2
```
**Output:**
```
28
```
**Explanation:**
```
The corresnponding binary number is "000011100" whose decimal value is 28.
```
#### Solution Explanation:
We can take a number 0 and set the bits from C to B+C-1 (0 based indexing from right)
Say initially we have -
| 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| --- | -------- | -------- | -------- | -------- | -------- | -------- |-------- | -------- |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
```
A = 4
B = 3
C = 2
```
It means, we will set the bits from 2( C) to 4(B+C-1) from right
This is how the number will look like finally -
| 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| -- | -------- | -------- | -------- | -------- | -------- | -------- |-------- | -------- |
| 0| 0 | 0 | 0 | **1** | **1** | **1** | 0 | 0 |
**How to set a bit ?**
We can take OR(|) with (1<<i)
#### Pseudocode
```cpp
long solve(int A, int B, int C) {
long ans = 0;
for (int i = C; i < B + C; i++) {
ans = ans | (1 << i);
}
return ans;
}
```
**Please NOTE:** We have taken ans as long because A+B+C can go uptil total 60 bits as per constraints which can be stored in long but not in integers.

View File

@@ -0,0 +1,437 @@
# Bit Manipulation 2
---
## Problem 1 Single Number 1
We are given an integer array where every number occurs twice except for one number which occurs just once. Find that number.
**Example 1:**
**Input:** [4, 5, 5, 4, 1, 6, 6]
**Output:** 1
`only 1 occurs single time`
**Example 2:**
Input: [7, 5, 5, 1, 7, 6, 1, 6, 4]
Output: 4
`only 4 occurs single time`
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force
Traverse the array and count frequency of every element one by one.
T.C - O(N^2)
S.C - O(1)
#### Using HashMap
Traverse the array and store frequency of every element.
T.C - O(N)
S.C - O(N)
#### Idea
What is A^A ?
ans = A^A is 0
---
### Question
Value of 120 ^ 5 ^ 6 ^ 6 ^ 120 ^ 5 is -
**Choices**
- [ ] 120
- [ ] 210
- [ ] 6
- [ ] 5
- [x] 0
#### Approach 1:
Since ^ helps to cancel out same pairs, we can use it.
Take XOR of all the elements.
#### Pseudocode
```cpp
int x = 0;
for (int i = 0; i < arr.size(); ++i) {
x = x ^ arr[i]; // XOR operation
}
print(x);
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Approach 2:
*Interesting Solution!*
Bitwise operators work on bit level, so let's see how XOR was working on bits.
For that, let's write binary representation of every number.
#### Observations:
For every bit position, if we count the number of 1s the count should be even because numbers appear in pairs, but it can be odd if the bit in a single number is set for that position.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/235/original/upload_78bd6aa4f42a31b3a8672e977ec90a58.png?1696401624" width=500/>
* We will iterate on all the bits one by one.
* We will count the numbers in the array for which the particular bit is set
* If the count is odd, in the required number that bit is set.
#### Pseudocode
```cpp
int ans = 0;
for (int i = 0; i < 32; i++) { // go to every bit one by one
int cnt = 0;
for (int j = 0; j < arr.size(); j++) { // iterate on array
// check if ith bit is set
if ((arr[j] & (1 << i)) cnt++;
}
if (cnt & 1) // If the count is odd
ans = ans | 1 << i; // set ith bit in ans
}
print(ans);
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 2 Single number 2
Given an integer array, all the elements will occur thrice but one. Find the unique element.
**Example**
**Input:** [4, 5, 5, 4, 1, 6, 6, 4, 5, 6]
**Output:** 1
`Only 1 occurs a single time`
#### Approach 1: Brute Force
Using two for loops and counting the occurence of each number.
#### Complexity
**Time Complexity:** O(N^2)
**Space Complexity:** O(1)
#### Approach 2: Hashmaps
Iterate on array and store frequency of each number in Hashmap.
Iterate on array/map and return the number with frequency 1.
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
:::warning
Please take some time to think about the optimsed approach on your own before reading further.....
:::
#### Approach 3: Best Approach
Hint can be taken from the previous question.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/237/original/upload_0afb41111a02da1bd77c0005ef443a69.png?1696401793)" width=500/>
* Iterate on every bit.
* If the count of numbers in which ith bit is set is a multiple of 3, then in answer ith bit is NOT SET.
* If the count of numbers in which ith bit is of the form (3 * x) + 1, then in answer ith bit is SET.
#### Pseudocode
```cpp=
int ans = 0;
for (int i = 0; i < 32; i++) { // go to every bit one by one
int cnt = 0;
for (int j = 0; j < arr.size(); j++) { // iterate on array
// check if ith bit is set
if ((arr[j] & (1 << i)) cnt++;
}
if (cnt % 3 == 1) // If the count is not the multiple of 3
ans = ans | 1 << i; // set ith bit in ans
}
print(ans);
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 3 Single number 3
Given an integer array, all the elements will occur twice except two. Find those two elements.
**Input:** [4, 5, 4, 1, 6, 6, 5, 2]
**Output:** 1, 2
#### Hint:
* Will finding XOR help ? May be!
* What do we get if we XOR all numbers ? XOR of the two unique numbers!
* From that can we identify/separate the two numbers ? Not Really! Why?
* Example: If XOR is 7, we aren't sure which 2 numbers are they. (2, 5), (1, 6), (3, 4), ... have xor = 7, so we won't be able to identify!
***Is there any way in which we can identify the two numbers from their XOR ?***
Suppose if two unique numbers are **a** and **b**. Their XOR is **c**.
In **c** if say 0th bit is set, what does that tell about a and b ?
In one of the numbers the bit is set and in other the bit is unset! So, can we identify the numbers based on that ?
#### Idea:
* We will find the position of any set bit in XOR c, it will denote that this bit is different in a and b.
* Now, we divide the entire array in two groups, based upon whether that particular bit is set or not.
* This way a and b will fall into different groups.
* Now since every number repeats twice, they will cancel out when we take XOR of the two groups individually leaving a and b.
#### Pseudocode
```cpp
int xorAll = 0;
// XOR of all numbers in the array
for (int i = 0; i < N; i++) {
xorAll ^= A[i];
}
// Find the rightmost set bit position
// Note: Any other bit can be used as well
int pos;
for (pos = 0; pos < 32; pos++) {
if (checkbit(xorAll, pos))
break;
}
num1 = 0;
num2 = 0;
// Divide the array into two groups based on the rightmost set bit
for (int i = 0; i < N; i++) {
if (checkbit(A[i], pos)) {
num1 ^= A[i];
} else {
num2 ^= A[i];
}
}
print(num1);
print(num2);
```
---
### Question
What is the time complexity to find two unique elements where every element is present 2 times except for two unique elements?
**Choices**
- [ ] O(1)
- [ ] O(log(N))
- [x] O(N)
- [ ] O(32 * N)
---
### Problem 4 Maximum AND pair
Given N array elements, choose two indices(i, j) such that **(i != j)** and **(arr[i] & arr[j])** is maximum.
**Input:** [5, 4, 6, 8, 5]
**Output:** [0, 4]
If we take the **&** of 5 with 5, we get 5 which is the maximum possible value here. The required answer would be their respective indices i.e. **0,4**
---
### Question
Max & Pair in this array (arr[] = 21,18,24,17,16) is
**Choices**
- [x] 21&17
- [ ] 24&21
- [ ] 17&16
- [ ] 24&18
---
### Question
Max & Pair in this array (arr[] =5,4,3,2,1) is
**Choices**
- [x] 5&4
- [ ] 1&2
- [ ] 1&4
- [ ] 4&3
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Maximum AND pair Approach
#### Brute Force
Using two for loops and calculating **bitwise &** for all possible pairs and storing the maximum of all of them.
#### Complexity
**Time Complexity:** O(N^2)
**Space Complexity:** O(1)
#### Observation
1. When bit is set in both the numbers, that bit in their **&** will be 1
2. For answer to be maximum, we will want the set bit to be present towards as left as possible.
3. This indicates that we should start processing the numbers from MSB.
#### Optimized Solution
* Iterate from the Most significant bit to Least significant bit and for all the numbers in the array, count the numbers for which that bit is set
* If the count comes out to be greater than 1 then pairing is possible, so we include only the elements with that bit set into our vector. Also, set this bit in your answer.
* If the count is 0 or 1, the pairing is not possible, so we continue with the same set and next bit position.
#### Dry Run
Example: { 26, 13, 23, 28, 27, 7, 25 }
26: 1 1 0 1 0
13: 0 1 1 0 1
23: 1 0 1 1 1
28: 1 1 1 0 0
27: 1 1 0 1 1
07: 0 0 1 1 1
25: 1 1 0 0 1
1. Let's start with MSB, **at position 4**, there are 5 numbers with set bits. Since count is >=2, we can form a pair. Therefore, in answer 1 will be present at this position.
ans:
| 1 | _ | _ | _ | _ |
| -------- | -------- | -------- | -------- | -------- |
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/520/original/Screenshot_2023-10-05_at_4.30.17_PM.png?1696503637" width="200" />
We will remove all numbers where 0 is present.
[13 and 7 gets removed or are set to 0]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/525/original/Screenshot_2023-10-05_at_4.31.31_PM.png?1696503708" width="243" />
2. At position 3, there are 4 numbers with set bits(which haven't been cancelled). Since count is >=2, we can form a pair. Therefore, in answer 1 will be present at this position.
ans:
| 1 | 1 | _ | _ | _ |
| -------- | -------- | -------- | -------- | -------- |
We will remove all numbers where 0 is present.
[23 gets removed or is set to 0]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/527/original/Screenshot_2023-10-05_at_4.37.18_PM.png?1696504048" width="250" />
3. At position 2, there is 1 number with set bit. Since count is less than 2, we can't form a pair. Therefore, in answer 0 will be present at this position.
ans:
| 1 | 1 | 0 | _ | _ |
| -------- | -------- | -------- | -------- | -------- |
We will NOT remove any number.
4. At position 1, there are 2 numbers with set bits. Since count is >=2, we can form a pair. Therefore, in answer 1 will be present at this position.
ans:
| 1 | 1 | 0 | 1 | _ |
| -------- | -------- | -------- | -------- | -------- |
We will remove all numbers where 0 is present.
[28 and 25 gets removed or are set to 0]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/528/original/Screenshot_2023-10-05_at_4.40.05_PM.png?1696504233" width="200" />
5. At position 0, there is 1 number with set bit. Since count is <2, we can't form a pair. Therefore, in answer 0 will be present at this position.
ans:
| 1 | 1 | 0 | 1 | 0 |
| -------- | -------- | -------- | -------- | -------- |
We will NOT remove any number.
**We are done and answer final answer is present in variable ans**.
---
### Maximum AND pair Pseudocode
#### Pseudocode
```cpp
int ans = 0;
for (int i = 31; i >= 0; i--) {
//count no. of set bits at ith index
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[j] & (1 << i))
cnt++;
}
//set that bit in ans if count >=2
if (count >= 2) {
ans = ans | (1 << i);
//set all numbers which have 0 bit at this position to 0
for (int j = 0; j < n; j++) {
if (arr[j] & (1 << i) == 0)
arr[j] = 0;
}
}
}
print(ans);
//The numbers which cannot be choosen to form a pair have been made zero
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
Similarly, if we have to find maximum & of triplets then we will do for count>=3 and for quadruples as count >= 4 and so on ...
---
### Problem 5 Count of pairs with maximum AND
Calculate the Count of Pairs for which bitwise & is maximum (GOOGLE Interview Question)
#### Solution:
Do exactly as above and then traverse on the array and find the number of elements which are greater than 0
Required answer will be Nc2 or N(N-1)/2
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)

View File

@@ -0,0 +1,342 @@
# DP 1: One Dimentional
---
## Fibonacci Series
`0 1 1 2 3 5 8 13 21 ...`
### fibonacci Expresion
* `fib(n) = fib(n-1) + fib(n-2)`
* base case for the fibonacci expression -> `fib(0) = 0; fib(1) = 1`
### Psuedocode
```java
int fib(n) {
if (n <= 1) return n;
return fib(n - 1) + (n - 2);
}
```
> Time complexity for the above code : **O(2^N)**
> Space Complexity for the above code : **O(N)**
---
### Problem 1 Fibonacci Series
#### Properties of Dynamic Programming
* **Optimal Substructure** - i.e. solving a problem by solving smaller subproblems
* **Overlapping Subproblems** - solving some subproblems multiple times
#### Solution for Dynamic Programming
* Store the information about already solved sub-problem and use it
#### Psuedocode of Fibonacci series using dynamic Programming
```java
int f[N + 1] // intialize it with -1
int fib(n) {
if (N <= 1) return n;
// if already solved, don't repeat
if (f[N] != -1) return f[N];
// store it
f[N] = fib(n - 1) + (n - 2);
return f[N];
}
```
**Two main operations performed in the above code of dynamic programming:**
* If we have already solved a problem just return the solution, don't repeat the step
* If not solved, solve and store the solution
#### Dry Run
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/661/original/upload_e554134a63cd8d0282c8e28bc7b7a885.png?1695234686" width=600 />
We're going to figure out what **`fib(5)`** is using a method called recursion, and we'll keep track of our answers in an array. Here's how it works, step by step:
* **Starting Point:**
We want to find out what fib(5) is. Our array, where we store our results, starts with -1 in every spot because we haven't calculated anything yet.
* **Breaking it Down:**
To get fib(5), we first need to know fib(4) and fib(3).
* **Going Deeper:**
For fib(4), we need fib(3) and fib(2). And for fib(3) (the one we saw earlier), we also need fib(2) and fib(1).
* **Even Deeper:**
To find fib(2), we look at fib(1) and fib(0).
* **Simple Answers:**
Now, fib(1) and fib(0) are easy; they are 1 and 0. We use these to find out fib(2), which is 1 (0 + 1). Store it before moving forward.
* **Building Up:**
We keep using these small answers to find the bigger ones. If we already know an answer (like fib(2)), we don't have to calculate it again; we just use the answer from our array.
By the end, we'll have the answer to fib(5), and all the smaller fib numbers stored in our array!
#### Time and Space Complexity
**Time Complexity for the above code is O(N)** and **space complexity is O(N)**. Thus, we were able to reduce the time complexity from O(2^N) to O(N) using dynamic programing
---
### Dynamic Programming Types
#### Types of DP Solution:
*Dynamic programming solution can be of two types*:
* **`Top-Down`** [Also know as **Memoization**]
* It is a recursive solution
* We start with the biggest problem and keep on breaking it till we reach the base case.
* Then store answers of already evaluated problems.
* **`Bottom-Up`**
* It is an iterative solution
* We start with the smallest problem, solve it and store its result.
* Then we keep on moving to the bigger problems and use the already calculated results from sub-problems.
#### Bottom Up Approach for Fibonacci series
#### Psuedocode
```java
int fib[N + 1];
fib[0] = 0;
fib[1] = 1;
for (i = 2, i <= N; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
> Through this approach we were able to eliminate recursive stack.
#### Further optimising the Space Complexity
If seen closely, the above approach can be optimised by using just simple variables instead of an array. In this way, we can further optimize the space.
#### Pseudocode
```java
int a = 0;
int b = 1;
int c;
for (int i = 2; i <= N; i++) {
c = a + b;
a = b;
b = c;
}
```
> In the above code we were able to optimize the space complexity to O(1).
---
### Question
What is the purpose of memoization in dynamic programming?
**Choices**
- [ ] To minimize the space complexity of the algorithm
- [x] To store and reuse solutions to subproblems
- [ ] To calculate results of all calls
- [ ] To improve the readability of the code
---
### Question
Which approach is considered as an iterative process?
**Choices**
- [ ] Top-down approach
- [x] Bottom-up approach
- [ ] Both are iterative
- [ ] Neither is iterative
---
### Problem 2 Climbing Staircase
*Calculate the number of ways to reach the Nth stair. You can take 1 step at a time or 2 steps at a time.*
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/664/original/upload_233b00b5a73ec318e416b6bdbe360c77.png?1695234754" width=300 />
**`CASE 1: (number of stairs = 1)`**
{1}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/665/original/upload_0907cd565ba887db4960bd86be837498.png?1695234776" width=100 />
Number of ways to reach first stair : 1 (as shown in fig)
**`CASE 2: (number of stairs = 2)`**
{1, 1}
{2}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/666/original/upload_af1980732ba13970f361053716dfd465.png?1695234797" width=150 />
Number of ways to reach two stairs : 2 (as shown in fig)
**`CASE 3: (number of stairs = 3)`**
{1, 2}
{1, 1, 1}
{2, 1}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/667/original/upload_7907becd6ea9f76cf6fc19b43795efa2.png?1695234818" width=200 />
Number of ways to reach two stairs : 3 (as shown in fig)
**`CASE 4: (number of stairs = 4)`**
{1, 1, 2}
{2, 2}
{1, 2, 1}
{1, 1, 1, 1}
{2, 1, 1}
---
### Question
In Stairs Problems, the result for N=4
**Choices**
- [ ] 4
- [x] 5
- [ ] 6
- [ ] 7
**Explanation:**
To reach 1st staircase : 1 way
To reach 2nd staircase : 2 ways
To reach 3rd staircase : 3 ways
To reach 4th staircase : 5 ways
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Problem 2 Climbing Staircase Approach
#### Approach
We can come to 4th stair from 2nd and 3rd step.
* If I get to know #steps to reach stair 3, we can take length 1 step and reach stair 4.
* Similarly, if I get to know #steps to reach stair 2, we can take length 2 step and reach stair 4.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/062/093/original/Screenshot_2024-01-16_at_8.33.25_PM.png?1705417480" width=400 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/062/092/original/Screenshot_2024-01-16_at_8.33.38_PM.png?1705417465" width=400 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/062/091/original/Screenshot_2024-01-16_at_8.33.43_PM.png?1705417444" width=400 />
* Number of ways we can reach to the nth step is either by (n - 1) or (n - 2).
* Answer will be summation of number of ways to reach (n - 1)th step + number of ways to reach (n - 2)th step
We can see that the above has been deduced to fibonacii expression
---
### Problem 3 Get Minimum Squares
*Find minimum number of perfect squares required to get sum = N. (duplicate squares are allowed)*
*example 1 --> N = 6*
sum 6 can be obtained by the addition of following squares:
* `1^2+1^2+1^2+1^2+1^2+1^2`
* `1^2+1^2+2^2` --> minimum number of squares is 3 in this case
*example 2 --> N = 10*
sum 10 can be obtained by the addition of following squares:
* `1^2+1^2+..... 10 times`
* `2^2 + 1^2..... 6 times`
* `2^2 + 2^2 + 1^2 + 1^2`
* `3^2 + 1^2 `--> minimum number of squares is 2 in this case
*example 3 --> N = 9*
sum 10 can be obtained by the addition of following squares:
* `1^2+1^2+..... 9 times`
* `2^2 + 1^2..... 5 times`
* `2^2 + 2^2 + 1^2 `
* `3^2` --> minimum number of squares is 1 in this case
---
### Question
What is the minimum number of perfect squares required to get sum = 5. (duplicate squares are allowed)
**Choices**
- [ ] 5
- [ ] 1
- [x] 2
- [ ] 3
**Explanation**:
sum 5 can be obtained by the addition of following squares:
* `1^2 + 1^2 + 1^2 + 1^2 + 1^2`
* `2^2 + 1^2` --> minimum number of squares is 2 in this case
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Get Minimum Squares Approach
#### Approach 1
* Can we simply do **`N - (nearest perfect square)`** ?
* Verifying approach 1 with example N=12
* 12-9 (closest square) = 3
* 3-1 = 2
* 2-1 = 1
* 1-1 = 0
* We are using 4 perfect squares, whereas the minimum number of square is 3 (2^2 + 2^2 +2^2) so approach 1 is not useful in this case
#### Brute Force Approach
* Try every possible way to form the sum using brute force to solve a example N = 12
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/672/original/upload_b2d3a0ce0edd55a79e60fb9cc25f7422.png?1695234985" width=500 />
The above image shows all possiblities to achieve 12.
Now, to get minimum sum of 12 we will find minimum square of 11 or minimum square of 8 or minimum square of 3 + 1.
The above is a recursive problem where we can see overalapping subproblems, like for N=7.
#### Dynamic Programming Approach
Here optimal structure has been obtained as well as overlapping subproblems
So, we can say that
`square(i) = 1 + min{ squares(i - x^2) for all x^2 <= i} `and base case is square[0] = 0
#### Psuedocode
```java
int dp[N + 1]; //initialise (-1)
int psquares(int N, int dp[]) {
if (n == 0) return 0;
if (dp[N] != -1) return dp[N];
ans = int - max;
for (x = 1; x * x <= N; x++) {
ans = min(ans, psquares(N - x ^ 2)); // dp
}
dp[N] = 1 + ans;
return dp[N];
}
```
Time complexity for the above code is O(N(sqrt(N))) and space complexity is O(N).

View File

@@ -0,0 +1,724 @@
# DP 2: Two Dimensional
---
## Problem 1 Maximum Subsequence Sum
Find maximum subsequence sum from a given array, where selecting adjacent element is not allowed.
**Examples**
Example 1: ar[] = {9, 4, 13}
Output 1: 22. Since out of all possible non adjacent element subsequences, the subsequence (9, 13) will yield maximum sum.
Example 2: ar[] = {9, 4, 13, 24}
Output 2: 33 (24 + 9)
---
### Question
Find maximum subsequence sum from `[10, 20, 30, 40]`, where selecting adjacent element is not allowed.
**Choices**
- [ ] 70
- [x] 60
- [ ] 100
- [ ] 50
**Explanation**:
Maximum Subsequence is 60. Since, Out of all possible non adjacent element subsequences, the subsequence (20, 40) will yield maximum sum of 60.
---
### Maximum Subsequence Sum Brute Force Approach
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
#### Brute Force Approach
- Consider all the valid subsequences **`(this a backtracking step)`**.
- For creating subsequences, for every element we can make a choice, whether to select it or reject it.
- Say, we start from right most element. If we keep it, then (n - 1)th element can't be considered, so jump to (n - 2)th. If we don't, then (n - 1)th element can be considered. So on...
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/331/original/upload_092f6de3c6b895d5870ff2a4edc751b9.png?1695530157" width=400 />
The above image shows tree which has all the choices of selection. Here we can see that the choices are overlapping.
Moreover, as the problem can be broken into smaller problems and has overlapping sub problems, we can use **dynamic programming**.
---
### Maximum Subsequence Sum Top Down Approach
#### Top Down Approach
So for **maxSum(i)** there are two options:
* either we can select element present at index i
* if we select that element we will include its value ie ar[i] and the recursive call will be **maxSum(i-2)**
* or we cannot select the element present at index i
* so in this case we will not include its value and will make recursive call which is **maxSum(i-1)**
`dp[i] = stores the maximum value that can be obtained by selecting 0 to ith toy.`
The maximum of the choice we make will give us the final answer
#### Psuedocode
```cpp
int dp[N] //initialize it with negative infinity
// i will be initialised with N-1, i.e we start with the last element
int maxSum(int[] arr, i, dp[N]) {
if (i < 0) {
return 0
}
if (dp[i] != -infinity) {
return dp[i]
}
//Don't consider the ith element, in this case we can consider (i-1)th element
f1 = maxSum(arr, i - 1, dp);
//Consider the ith element, in this case we can't consider (i-1)th element, so we jump to (i-2)th element
f2 = arr[i] + maxSum(arr, i - 2, dp);
ans = max(f1, f2)
dp[i] = ans;
return ans
}
```
#### Time & Space Complexity
**Time complexity:** O(N). As we are filling the DP array of size N linearly, it would take O(N) time.
**Space complexity:** O(N), because of dp array of size N.
---
### Maximum Subsequence Sum Bottom Up Approach
**Problem 1**
**`dp[i] is defined as the maximum subsequence sum from [0 - i] provided no adjacent elements are selected`**
arr = {9, 4, 13, 24}
We can start from arr[0] and we have two choices: either we can select arr[0] or reject.
* If we select it, the maximum value we can acheive is arr[0] = 9
* If we reject it, the value which we will get is 0
* So, we will store arr[0] in dp[0]
* Now, we will look at arr[0] and arr[1] to find the maximum
* As arr[0] > arr[1], we will store arr[0] in dp[1]
* Similary we will repeat the above steps to fill dp[].
#### Psuedocode
```cpp
dp[N]
for(i = 0; i < N; i++){
dp[i] = max(dp[i - 1], arr[i] + dp[i - 2])
}
return dp[N - 1]
```
#### Time & Space Complexity
**Time complexity:** O(N). As we are filling the DP array of size N linearly, it would take O(N) time.
**Space complexity:** O(N), because of dp array of size N.
---
### Problem 2 Count Unique Paths
Given mat[n][m], find total number of ways from (0,0) to (n - 1, m - 1). We can move 1 step in horizontal direction or 1 step in vertical direction.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/332/original/upload_cb3858a3235bba18e6037c9699d300f3.png?1695530323a" width=400 />
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/333/original/upload_44295f53f281281555a9264d2acee1d4.png?1695530363" width=400 />
> `h` represents movement in horizontal direction and `v` represents movement in vertical direction
**Ans:** 6
---
### Question
Find the total number of ways to go from (0, 0) to (1, 2)
| o | | |
|---|---|---|
| | | **o** |
**Choices**
- [ ] 1
- [ ] 2
- [x] 3
- [ ] 4
**Explanation**:
The 2D matrix dp is
| | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 1 | 2 | 3 |
From here, the number of ways to go from (0, 0) to (1, 2) is 3.
---
### Count Unique Paths Brute Force Approach
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force Appoarch
**Backtracking**, i.e., start from (0, 0) and try all possible scenarios to reach (n - 1, m - 1)
#### Observation
Can we break it into subproblems?
- We can reach (n - 1, m - 1) in one step (by moving vertically) from (n - 2, m - 1)
- We can reach (n - 1, m - 1) in one step (by moving horizontally) (n - 1, m - 2)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/334/original/upload_3fc7c3e0b6a26618888979ff3b4bfa4a.png?1695530388" width=500 />
#### Recursive Relation
**ways(i, j) = ways(i - 1, j) + ways(i, j - 1)**
#### Base Condition
- When i == 0, we have only one path to reach at the end, i.e., by moving vertically.
- Similary, when j == 0, we have only one path to reach at the end, i.e., by moving horizontally.
Therefore, **ways(0, j) = ways(i, 0) = 1**
#### Pseudocode:
```java
int ways(i, j) {
if (i == 0 || j == 0) {
return 1;
}
return ways(i - 1, j) + ways(i, j - 1);
}
```
Time Complexity: O(2 ^ (N * M)), as at every step we have two options, and there are total of N * M cells.
---
### Count Unique Paths Optimization
#### Optimization using DP
We can see the **optimal substructure** in this problem as it can be defined in terms of smaller subproblems.
**Are there overlapping subproblems as well?**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/335/original/upload_6c4137711a6c49b0ed6def7c230fc475.png?1695530519" width=400 />
We can see that, `(i - 1, j - 1)` are the overlapping subproblems.
***Since there is optimal substructure and overlapping subproblems, DP can be easily applied.***
*Which type of array should be used?*
Since two args (i and j) are varying in above method, 2-d storage is needed of size N x M.
#### Top Down Approach
**`dp[i][j] = It is defined as the total ways to reach from 0,0 to i,j`**
#### Pseudocode
```java
int dp[N][M]; // initialized with -1
int ways(i, j) {
if (i == 0 || j == 0) {
return 1;
}
if (dp[i][j] != -1) {
return dp[i][j];
}
ans = ways(i - 1, j, dp) + ways(i, j - 1, dp);
dp[i][j] = ans;
return ans;
}
```
#### Complexity
**Time Complexity:** O(N * M), as we are filling a matrix of size N * M.
**Space Complexity:** O(N * M), as we have used dp matrix of size N * M.
> *In how many ways can we reach (0, 0) starting from (0, 0)?*
>
> If you say 0, that means there is no way to reach (0, 0) or (0, 0) is unreachable. Hence, to reach (0, 0) from (0, 0), there is 1 way and not 0.
#### Bottom Up Approach:
Consider a 2D matrix `dp` of size N * M.
`dp[i][j] = It is defined as the total ways to reach from 0,0 to i,j`
In bottom up approach, we start from the smallest problem which is (0, 0) in this case.
- No. of ways to move (0, 0) from (0, 0) = ways(0, 0) = 1
- Similarly, ways(0, 1) = ways(0, 2) = . . . = 1
- Also, ways(1, 0) = ways(2, 0) = . . . = 1
- Now, ways(1, 1) = ways(1, 0) + ways(0, 1) = 2
- Similarly, ways(1, 2) = ways(1, 1) + ways(0, 2) = 3, and so on.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/336/original/upload_91d6c51f6c8e74ac6934f9096ed1e7d2.png?1695530605" width=500 />
#### Pseudocode
```java
dp[N][M];
// Initialize `dp` row - 0 and col - 0 with 1.
for (i = 1; i <= N; i++) {
for (j = 1; j <= M; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[N - 1][M - 1];
```
Time Complexity: O(N * M)
Space Complexity: O(N * M)
#### Can we further optimize the space complexity?
- The answer of every row is dependent upon its previous row.
- So, essentially, we require two rows at a time - (1) current row (2) previous row. Thus, the space can be optimized to use just two 1-D arrays.
---
### Problem 3 Total number of ways to go to bottom right corner from top left corner
Find the total number of ways to go to bottom right corner (N - 1, M - 1) from top left corner (0, 0) where cell with value 1 and 0 represents non-blocked and blocked cell respectively.
We can either traverse one step down or one step right.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/337/original/upload_99f88e61619dbf00e937df23ee3548f2.png?1695530745" width=300 />
#### Solution
| 1 | 1 | 1 | 1 |
| - | - | - | - |
| 1 | 0 | 1 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 2 |
| 0 | 0 | 1 | 3 |
The given problem is just a variation of above problem. Only advancement is that if cell value has 0, then there is no way to reach the bottom right cell.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Pseudocode (Recursive Approach)
```cpp
if (mat[i][j] != 0) {
ways(i, j) = ways(i - 1, j) + ways(i, j - 1);
} else {
ways[i][j] = 0;
}
```
Similar base condition can be added to top-down and bottom-up approach to optimize it using DP.
---
### Question
How many unique paths in the grid from (0, 0) to (2, 2) ?
| 1 | 1 | 1 |
|-------|-------|-------|
| **0** | **0** | **0** |
| **1** | **1** | **1** |
where cell with value 1 and 0 represents non-blocked and blocked cell respectively.
**Choices**
- [x] 0
- [ ] 1
- [ ] 2
- [ ] 3
**Explanation**:
On the Grid, Row 1 is completely blocked. So there is no path from (0, 0) to (2, 2).
Thus, the Total number of unique paths is 0.
---
### Problem 4 Dungeons and Princess
Find the minimum health level of the prince to start with to save the princess, where the negative numbers denote a dragon and positive numbers denote red bull.
Redbull will increase the health whereas the dragons will decrease the health.
The prince can move either in horizontal right direction or vertical down direction.
If health level <= 0, it means prince is dead.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/338/original/upload_f334edd38b0378a2a03a45fa9e3043d5.png?1695530793" width=300 />
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Observation
One might argue to solve it by finding the path with minimum sum or maximum sum.
Let's check does it even work or not?
#### Using path with minimum sum(fails)
- For the above matrix, the path with minimum sum is -3 -> -6 -> -15 -> -7 -> 5 -> -3 -> -4, which yields sum as 33. So, minimum health level should be (3 + 6 + 15 + 7) + 1 = 32, right?
- No because if we start with **health 4** and follow the path -3 -> 2 -> 4 -> -5 -> 6 -> -2 -> -4, we can definitely reach the princess with lesser initial health.
- Thus, finding the path with minimum sum doesn't work/
#### Using path with maximum sum(fails)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/339/original/upload_873abf9a3e58fd0f728719430a0e887c.png?1695530837" width=300 />
- For the above matrix, the path with maximum sum is -2 -> -8 -> 100 -> 1, which yields sum as 91. So, minimum health level should be (2 + 8) + 1 = 11, right?
- No because if we start with **health 7** and follow the path -2 -> -1 -> -3 -> 1, we can definitely reach the princess with lesser initial health.
- Similarly, finding the path with maximum sum doesn't work.
> NOTE:
> Finding the path with maximum or minimum sum is a greedy approach, which doesn't work for this problem.
#### How to approach the problem then?
Let's start with finding the smallest problem.
***Where does smallest problem lie?* (0, 0) ?*** **NO**
The smallest problem lies at **`(M - 1, N - 1)`**, because we need to find the minimum health to finally enter that cell to save the princess.
***Now, what should be the minimum health to enter a cell?***
Suppose the cell(M - 1, N - 1) has value -4, then to enter the cell needed is: minimum_health + (-4) > 0 => minimum_health + (-4) = 1 => minimum_health = 5
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/340/original/upload_843b46c743fe4d12773a667600e07d54.png?1695530898" width=300 />
There are two ways to enter the cell:
**(1)** via TOP **(2)** via LEFT.
***Which one to choose?***
We know, to enter the cell with value -4, the minimum health should be 5. Therefore, if we want to enter from top cell with value -2, then x + (-2) = 5; x = 7, where 'x' is minimum health to enter top cell.
Similary, y + (-3) = 5; y = 8.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/341/original/upload_51f3ab59c91e9ade5cb5eef24a9bbd19.png?1695530962" width=600 />
Hence, we should choose minimum of these and enter the cell via top.
**What is the minimum health required to enter a cell (i, j) which has two options to move ahead?**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/342/original/upload_1440f8d741c7f418205eb25601dfd9bf.png?1695531018" width=300 />
</br>
</br>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/343/original/upload_6dcf579d339349697c4675985a1e1a10.png?1695531068" width=600 />
> If the minimum health evaluates to negative, we should consider 1 in place of that as with any health <= 0, the prince will die.
Let's fill the matrix using the same approach.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/344/original/upload_951ca69af1ec1a1a6aab85b61d583e1b.png?1695531111" width=600 />
Here, `dp[i][j]` = min health with which prince should take the entry at (i, j) so that he can save the princess.
---
### Question
What is the Time Complexity to find minimum cost path from (0,0) to (r-1, c-1)?
**Choices**
- [ ] O(max(r, c))
- [ ] O(c )
- [x] O(r * c)
- [ ] O(r + c)
---
### Dungeons and Princess Algorithm and Pseudocode
#### Algorithm
```java
arr[i][j] + x = min(dp[i + 1][j], dp[i][j + 1])
x = min(dp[i + 1][j], dp[i][j + 1]) - arr[i][j]
```
Since `x` should be > 0
```java
x = max(1, min(dp[i + 1][j], dp[i][j + 1]) - arr[i][j])
```
#### Pseudocode:
```java
declare dp[N][M];
if (arr[N - 1][M - 1] > 0) {
dp[N - 1][M - 1] = 1;
} else {
dp[N - 1][M - 1] = 1 + abs(arr[N - 1][M - 1]);
}
// Fill the last column and last row
for (i = N - 2; i >= 0; i--) {
for (j = M - 2; j >= 0; j--) {
x = max(1, min(dp[i + 1][j], dp[i][j + 1]) - arr[i][j]);
dp[i][j] = x;
}
}
return dp[0][0];
```
#### Complexity
**Time Complexity:** O(N * M)
**Space Complexity:** O(N * M)
---
### Catalan Numbers
The Catalan numbers form a sequence of natural numbers that have numerous applications in combinatorial mathematics. Each number in the sequence is a solution to a variety of counting problems. The Nth Catalan number, denoted as Cn, can be used to determine:
* The number of correct combinations of N pairs of parentheses.
* The number of distinct binary search trees with N nodes, etc.
Here is the sequence,
```
C0 = 1
C1 = 1
C2 = C0 * C1 + C1 * C0 = 2
C3 = C0 * C2 + C1 * C1 + C2 * C0 = 5
C4 = C0 * C3 + C1 * C2 + C2 * C1 + C3 * C0 = 14
C5 = C0 * C4 + C1 * C3 + C2 * C2 + C3 * C1 + C4 * C0 = 42
```
#### Formula
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/800/original/catalan-formula.jpg?1706639109" width = 500 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/799/original/catalan.jpg?1706639038" width = 500 />
#### Psuedo Code
```cpp
int C[N + 1];
C[0] = 1;
C[1] = 1;
for (int i = 2; i <= N; i++) {
for (int j = 0; j < i; j++) {
C[i] += C[j] * C[N - 1 - j];
}
}
```
#### Complexity
**Time Complexity:** O(N^2^)
**Space Complexity:** O(N)
Now, Let's look into a problem, which can be solved by finding the **Nth catalan number**.
---
### Problem 5 Total Number of Unique BSTs
You are given a number N, Count Total number of Unique Binary Search Trees, that can be formed using N distinct numbers.
**Example**
**Input:**
N = 3
**Output:**
5
**Explanation:**
The Unique binary Search Trees are
```
30 10 30 10 20
/ \ / \ / \
10 20 20 30 10 30
\ \ / /
20 30 10 20
```
---
### Question
Count Total number of Unique Binary Search Trees, that can be formed using 2 distinct numbers
**Choices**
- [ ] 1
- [x] 2
- [ ] 5
- [ ] 4
**Explanation**:
Lets take 2 distinct numbers as [10, 20]
The possible BSTs are
```
20 10
/ \
10 20
```
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Total Number of Unique BSTs Dryrun
Lets take N = 5, the numbers are [10, 20, 30, 40, 50].
Lets keep each number as the root! one by one.
**10 as root**
```
10
\
\
\
20, 30, 40, 50
```
Here we notice that, 20, 30, 40 and 50 can be structured by various sub-roots. So, lets denote by C4.
Also on the right side, there is no elements. So denoting by C0.
`10 as root => C0 * C1`
**20 as root**
```
20
/ \
/ \
/ \
10 30, 40, 50
```
There are 1 element on the left side and 3 elements on the right side.
`20 as root => C1 * C3`
**30 as root**
```
30
/ \
/ \
/ \
10, 20 40, 50
```
There are 2 element on the left side and 2 elements on the right side.
`30 as root => C2 * C2`
**40 as root**
```
40
/ \
/ \
/ \
10, 20, 30 50
```
There are 3 element on the left side and 1 elements on the right side.
`40 as root => C0 * C1`
**50 as root**
```
50
/
/
/
10, 20, 30, 40
```
There are 4 element on the left side and 1 elements on the right side.
`10 as root => C4 * C0`
C5 = C0 * C4 + C1 * C3 + C2 * C2 + C3 * C1 + C4 * C0
which is 42.
#### Solution
The Solution for finding the total number of Unique BSTs is the **Nth Catalan Number**.
---
### Total Number of Unique BSTs Pseudo Code
#### Psuedo Code
The pseudo code is same as the Catalan Number Psuedo code.
```cpp
function findTotalUniqueBSTs(int N) {
int C[N + 1];
C[0] = 1;
C[1] = 1;
for (int i = 2; i <= N; i++) {
for (int j = 0; j < i; j++) {
C[i] += C[j] * C[N - 1 - j];
}
}
return C[N];
}
```
#### Complexity
**Time Complexity:** O(N^2^)
**Space Complexity:** O(N)

View File

@@ -0,0 +1,312 @@
# DP 3: Knapsack
---
## Knapsack Problem
Given N objects with their values Vi profit/loss their weight Wi. A bag is given with capacity W that can be used to carry some objects such that the total sum of object weights W and sum of profit in the bag is maximized or sum of loss in the bag is minimized.
We will try Knapsack when these combinations are given:
* number of objects will be N
* every object will have 2 attributes namingly value and weight
* and capacity will be given
---
### Problem 1 Fractional Knapsack
Given N cakes with their happiness and weight. Find maximum total happiness that can be kept in a bag with capacity = W (cakes can be divided)
**Example**:
N = 5; W = 40
Happiness of the 5 cakes = [3, 8, 10, 2, 5]
Weight of the 5 cakes = [10, 4, 20, 8, 15]
Goal - happiness should be maximum possible and the total sum of weights should be <= 40.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach**
**`Since we can divide the objects, hence they can be picked based on their value per unit weight.`**
**`For per unit weight, below are the happiness values:`**
* Cake 1: `happiness = 0.3`;
* Cake 2: `happiness = 2`;
* Cake 3: `happiness = 0.5`;
* Cake 4: `happiness = 0.25`;
* Cake 5: `happiness = 0.33`;
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/281/original/upload_72db79387a8a773bb3e539c979b5156d.png?1695931887" width=500/>
**Solution**
**`Arrange the cakes in descending order with respect to happiness/weight and start picking the element`**
* Select the 2nd cake (happiness = 2), reducing capacity to 36(40-4).
* Choose the 3rd cake (happiness = 0.5), further reducing capacity to 16(36-20).
* Opt for the 5th cake (happiness = 0.33), leaving a capacity of 1(16-15).
* Take a part of the 1st cake (happiness = 0.3), using up the remaining capacity.
* Total happiness achieved: 23.3 (8 + 10 + 5 + 0.3).
**Time complexity** of the above solution is O(Nlog(N)) because it requires sorting with respect to `happiness/weight`.
**Space complexity** of the above solution is O(1).*
#### Pseudo Code
```cpp
public class Solution {
class Items {
double cost;
int weight, value, ind;
Items(int weight, int value, double cost) {
this.weight = weight;
this.value = value;
this.cost = cost;
}
}
public int solve(int[] A, int[] B, int C) {
Items[] iVal = new Items[A.length];
for (int i = 0; i < A.length; i++) {
double cost = (A[i] * 1.0) / B[i];
iVal[i] = new Items(B[i], A[i], cost);
}
Arrays.sort(iVal, new Comparator < Items > () {
@Override
public int compare(Items o1, Items o2) {
if (o1.cost >= o2.cost) {
return -1;
}
return 1;
}
});
double totalValue = 0.0;
for (int i = 0; i < A.length; i++) {
int curWt = iVal[i].weight;
int curVal = iVal[i].value;
if (C >= curWt) {
C = C - curWt;
totalValue += curVal;
} else {
totalValue += (C * iVal[i].cost);
break;
}
}
return (int)(totalValue * 100);
}
}
```
---
### Flipkart's Upcoming Special Promotional Event
Flipkart is planning a special promotional event where they need to create an exclusive combo offer. The goal is to create a combination of individual items that together offer the highest possible level of customer satisfaction (indicating its popularity and customer ratings) while ensuring the total cost of the items in the combo does not exceed a predefined combo price.
---
### Problem 2 : 0-1 Knapsack
## 0-1 Knapsack
In this type of knapsack question, **division of object is not allowed.**
### Question
Given N toys with their happiness and weight. Find maximum total happiness that can be kept in a bag with capacity W. Division of toys are not allowed.
---
### Question
In the Fractional Knapsack problem, what is the key difference compared to the 0/1 Knapsack?
**Choices**
- [ ] Items can only be fully included or excluded.
- [x] Items can be partially included, allowing fractions.
- [ ] The knapsack has infinite capacity.
- [ ] The knapsack has a fixed capacity.
**Explanation**
In the Fractional Knapsack problem, items can be included in fractions, enabling optimization of the total value based on weight.
**Example**:
N = 4; W = 7
Happiness of the 4 toys = [4, 1, 5, 7]
Weight of the 4 toys = [3, 2, 4, 5]
> If we buy toys based on maximum happiness or maximum happiness/weight we may not get the best possible answer.
:::warning
Please take some time to think about the bruteforce approach on your own before reading further.....
:::
#### Brute Force Approach:
* Consider all subsets of items and select the one with highest summation of happiness.
Since there are in total 2^N^ subsequences and we have to consider each of them. Therefore the time complexity is: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/285/original/Screenshot_2023-09-29_015000.png?1695932414" width=120/>
#### Dry Run of Brute Force Apporach
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/286/original/upload_1da8c9bd0252023a1565544101017689.png?1695932481" width=700/>
In the above figure each element is taken and its selection is determined based on happiness and weight.
> Here we can notice optimal sub structure as well as overlapping sub problems.
> *Thus we can use dynamic progamming in this case*
If index and capacity can define one unique state total number of unique states are `O(N * (W + 1))` which is `O(N * W)`, as index will go from 0 to N - 1 and weight will go from 0 to W.
```cpp
dp[N][W] = max happiness (considering N objects and capacity W)
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/288/original/upload_714587c8730fa95bdd9fb19f8674a224.png?1695932582" width=500/>
> Here taking N = i and W = j, we have two choices either to select dp[i][j] or to reject it. On selecting it will result into` h[i] + dp[i - 1][j - wt[i]]`(h[i]=happiness of i) and on rejecting it will be `dp[i - 1][j]`.
#### Base Case
* for all j when i = 0, dp[0][j] = 0
* for all i when j = 0, dp[i][0] = 0
#### Psuedocode
```java
//for all i,j dp[i][j]=0
for (i--> 1 to N) { // 1based index for input
for (j--> 1 to W) {
if (wt[i] <= j) {
dp[i][j] = max(dp[i - 1][j], h[i] + dp(i - 1)(j - wt[i]))
} else {
dp[i][j] = dp[i - 1][j]
}
}
}
return dp[N][w]
}
```
The dimensions should be (N + 1) * (W + 1) as the final answer would be at dp[N][W]
#### Dry run
taking the N = 4 and W = 7
Happiness of the 4 toys = [4, 1, 5, 7]
Weight of the 4 toys = [3, 2, 4, 5]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/289/original/upload_be304bd2a67fc2d8a5ce4be744955f8b.png?1695932731" width=700/>
* Initially, we filled the `dp` matrix with zeros. Now, we will fill every position one by one.
- At i = 1, j = 1
wt[i] = wt[1] = 3
since wt[i] > j, dp[i][j] = dp[i - 1][j] => dp[1][1] = dp[0][1] = 0
* At i = 1, j = 2
wt[i] = wt[1] = 3
since wt[i] > j, dp[i][j] = dp[i - 1][j] => dp[1][2] = dp[0][2] = 0
* At i = 1, j = 3
wt[i] = wt[1] = 3
since wt[i] <= j, dp[i][j] = max(dp[i - 1][j], h[i] + dp[i - 1][j - wt[i]])
=> dp[1][3] = max(dp[0][2], h[1] + dp[0][0]) = max(0, 4 + 0) = 4
Similary we wil follow the above to fill the entire table.
> Time complexity for the above code is O(N * W)
> Space Complexity for the above code is O(N * W), we can furture optimize space complexity by using 2 rows. So the space complexity is O(2W) which can be written as O(W).
---
### Problem 3 Unbounded Knapsack
## Unbounded Knapsack or 0-N Knapsack
* objects cannot be divided
* same object can be selected multiple times
#### Question
Given N toys with their happiness and weight. Find more total happiness that can be kept in a bag with capacity W. Division of toys are not allowed and infinite toys are available.
#### Example
N = 3; W = 8
Happiness of the 3 toys = [2, 3, 5]
Weight of the 3 toys = [3, 4, 7]
*In this case we will select second index toy 2 times. Happiness we will be 6 and weight will be 8.*
Now here as we do not have any limitation on which toy to buy index will not matter, only capacity will matter.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
#### Dry Run for Brute Force Appoarch
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/292/original/upload_ad6449c2f3d6f906c8147fdd39fd37bb.png?1695961094" width=700/>
Step 1:
* if we select toy with index 1, capacity left will be `8 - wt of toy 1 = 8 - 3 = 5`. And the happiness will be `h = 2`
* Similarily if we select toy with index 2, capacity left will be `8 - wt of toy 2 = 8 - 4 = 4`. And the happiness will be `h = 3`
* if we select toy with index 3, capacity left will be `8 - wt of toy 3 = 8 - 7 = 1`. And the happiness will be `h = 5`
Step 2:
After buying toy 1
* Now if we buy toy 1, capacity will reduce to 2 and happiness will become 4
* Similary if we buy toy 2, capacity will reduce to 1 and happiness will become 5
* We cannot buy toy 3 as the capacity will be exceeded.
We will follow similar steps to find all the possiblity.
> We will pick the toy with maximum happiness that is 6 in this case after selecting toy 2 firstly and then selecting toy 2 again.
Here we can notice optimal sub structure as well as overlapping sub problems. Thus we can apply dynamic programming.
* Unqiue states here will be` W + 1 = O(W)` because the capacity can be from 0 to W
Base case for the above question:
* if capacity is 0, happiness is 0. So, `dp[0] = 0`
Equation `dp[i] = max(h[i] + dp[i - wt[j]])` for all toys j
#### Psuedocode
```java
for all i, dp[0] = 0
for (i--> 1 to W) {
for (j--> 1 to N) {
if (wt[j] <= i)
dp[i] = max(h[i] + dp[i - wt[j]])
}
}
return dp[W]
```
#### Complexity
**Time Complexity:** O(N * W)
**Space Complexity:** O(W)
---
### Question
We have Weight Capacity of 100
- Values = {1, 30}
- Weights = {1, 50}
What is the maximum value you can have?
**Choices**
- [ ] 0
- [x] 100
- [ ] 60
- [ ] 80
**Explanation**
There are many ways to fill knapsack.
- 2 instances of 50 unit weight item.
- 100 instances of 1 unit weight item.
- 1 instance of 50 unit weight item and 50
instances of 1 unit weight items.
We get maximum value with option 2, i.e **100**

View File

@@ -0,0 +1,274 @@
# DP 4: Applications of Knapsack
---
### Question
Time Complexity of the unbounded 0-1 knapsack problem?
- W : capacity of knapsack
- N : no. of elements
- K : Max weight of any item
- P : max value of any item
**Choices**
Chose the correct answer
- [x] O(NW)
- [ ] O(NK)
- [ ] O(NP)
- [ ] O(WK)
- [ ] O(WP)
- [ ] O(KP)
**Explanation**
For every node, we need to go to its left, that's the only way we can reach the smallest one.
---
## Introduction to the knapsack and DP
### What Is Dynamic Programming?
In the context of dynamic programming, the ``knapsack problem`` refers to a classic optimization problem that can be solved using dynamic programming techniques.
### Example
Suppose we are working on solving the fibonacci series problesm, then we can break it into step by step as follows:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/223/original/upload_14dd358fcd92e5a9b581704b1eefb28e.png?1696398568" width=600 />
Let us now solve some questions related to dynamic programming.
---
### Problem 1 Cut the rod for maximum profit
A rod of length `N` and an array `A` of length `N` is given. The elements (`i`) of the array contain the length of the rod (1-based indexing). Find the maximum values that can be obtained by cutting the rod into some pieces and selling them.
**Example**
Suppose we have the length on `N = 5` and we have to divide it then the division can be done as:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/227/original/upload_654db3cc55ff51f138c6e6464656a522.png?1696399161" width=500 />
Now, we can see that $9$ is the maximum value that we can get.
#### Solution
A naive approach to solving this problem would involve considering all possible combinations of cutting the rod into pieces and calculating the total value for each combination. This can be achieved using recursion and backtracking, where for each possible cut, the value of the cut piece is added to the recursively calculated value of the remaining part of the rod. The maximum value obtained among all combinations is the desired result.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Our Approach
As we can visualize from the example, there is an overlapping subproblem and an optimal sub-structure. So, we should opt for the DP approach.
> **Note**: We can observe three things here:
1. The maximum capacity is the length of the order.
2. `A[i]` is storing the length of the piece of the rod.
3. The sum of the length of each piece must be less than or equal to ``N``
The general observation that we can get here from these three things is that it is a knapsack problem.
---
### Question
The cutting rod question is:
**Choices**
- [ ] Fractional Knapsack
- [ ] `0-1` Knapsack
- [x] Unbounded Knapsack (or `0-N` Knapsack)
---
### Cut the rod for maximum profit Approach
#### Approach
- First, define the state of the dp i.e. `dp[i]`, it will be the maximum value that can be received by the rod of length `i`.
- The base case will be 0 in the case when the length of the rod is 0. This means `dp[0] = 0`.
We will loop over the array, and then calculate the maximum profit, and finally store the maximum profit in the current dp state.
Let us now see the pseudo-code for the problem.
#### Pseudocode
```cpp
for all values of i: dp[i] = 0
for (i = 1 to N) // length of rod to sell = i
{
for (j = 1 to i) {
dp[i] = max(dp[i], A[j] + dp[i - j])
}
}
return dp[N]
```
#### Time and Space Complexity
- **Time Complexity**: $O(N^2)$, as we are traversing the N-length array using nested for loops (Simply, we can also say that the capacity is `N` and the length of the array is also `N`).
- **Space Complexity**: `O(N)`, as we are using an extra dp array to store the current state of profit.
---
### Problem 2 Count the number of ways using coins (ordered selection)
In how many ways can the sum be equal to ``N`` by using coins given in the array? One coin can be used multiple times.
**Example**
There are 2 ways to solve this problem
a. **Ordered selection of coin**
Let us create the set of numbers that cummulate the value of `N`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/229/original/upload_ee7458626da770d0126593383bcb1ae3.png?1696399952" width=500 />
So, we can see that we have the value we get is $6$.
Now, let's look at the selection tree of the coin selection. We can divide the number by selecting the choices of subraction.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/230/original/upload_4617ad387a2fcb33297b8285a43843b7.png?1696399988" width=500 />
#### Solution - Ordered Selection of Coin
The naive approach to solving this problem involves using a recursive approach with backtracking. For each coin value in the array, subtract it from the target sum N, and recursively find the number of ways to form the remaining sum using the same coin set. Repeat this process for all coins and sum up the results.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
As we can observe from the examples above, we have to calculate the number of ways of selection, it is similar to the unbounded knapsack problem (as one coin can be selected multiple times).
---
### Question
What is the number of ways to get `sum = 0`
**Choices**
- [ ] 0
- [x] 1
- [ ] 2
- [ ] Undefined
---
### Count the number of ways using coins Pseudocode
#### Pseudocode
```cpp
for all values of i: dp[i] = 0
dp[0] = 1
for (i = 1 to N) {
for (j = 1 to(A.length - 1)) {
if (A[j] <= i) {
dp[i] += dp[i - A[j]]
}
}
}
return dp[N]
```
#### Time and Space Complexity
- **Time Complexity**: $O(N * (length~ of ~the ~array))$.
- **Space Complexity**: $O(N)$.
---
### Problem 3 Count the number of ways using coins (un-ordered selection)
Given a set of coins and a target sum, find the number of ways to make the target sum using the coins, where each coin can only be used once.
**Example**
Suppose we have a situation same as the last one.
N = 5 and coins we have [3, 1, 4].
So here we have 3 possible ways.
Now, let us try to arrage the coins to get the desired value.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/232/original/upload_a9fce62d196b3c81c037d1bf91d643bc.png?1696400235" width=700 />
So, what we can observe out of it is:
- The current state of dp, i.e. `dp[i]` is to select the number of ways to get the sum equal to i by selecting coins from L to R in the array.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Solution: Un-ordered Selection of Coin
How we can solve it:
- Initialize an array dp with all values set to 0. This array will be used to store the number of ways to make change for each possible sum from 0 to N.
- Set the initial value of `dp[0]` to 1. This step indicates that there is one way to make change for an amount of 0, which is by not using any coins.
- Iterate through the different coin denominations represented by the array A. This loop will consider each coin one by one.
- For each coin denomination `A[j]`, iterate through the possible sums from 1 to N. This loop will consider each sum value from 1 to N and calculate the number of ways to make change for that sum.
- Inside the inner loop, check if the current coin denomination `A[j]` is less than or equal to the current sum `i`. If it is, then it's possible to use this coin to make change for the current sum.
- If the condition is met, update the `dp` array for the current sum i by adding the number of ways to make change for the remaining amount (`i - A[j]`). This is where dynamic programming comes into play, as you are building up the solutions for larger sums based on the solutions for smaller sums.
- After both loops complete, the `dp[N]` value will represent the number of ways to make change for the desired amount N using the given coin denominations.
- Finally, return the value stored in `dp[N]`.
#### Pseudocode
```cpp
for all values of i: dp[i] = 0
dp[0] = 1
for (j = 0 to(A.length - 1)) // coins
{
for (i = 1 to N) // sum
{
if (A[j] <= i) {
dp[i] += dp[i - A[j]]
}
}
}
return dp[N]
```
#### Time and Space Complexity
- **Time Complexity**: $O(N * (length~ of~ the~ array))$.
- **Space Complexity**: `O(N)`.
---
### Problem 4 Extended 0-1 Knapsack Problem
We are given `N` toys with their happiness and weight. Find max total happiness that can be kept in a bag with the capacity `W`. Here, we cannot divide the toys.
The constraints are:
$- 1 <= N <= 500$
$- 1 <= h[i] <= 50$
$- 1 <= wt[i] <= 10^9$
$- 1 <= W <= 10^9$
---
### Question
What is the MAX value we can get for these items i.e. (weight, value) pairs in 0-1 knapsack of capacity W = 8.
Items = [(3, 12), (6, 20), (5, 15), (2, 6), (4, 10)]
Chose the correct answer
**Choices**
- [x] 27
- [ ] 28
- [ ] 29
- [ ] 30
**Explanation**
Simple 0-1 Knapsack, after trying all combinations 27 is the highest value we can have inside the knapsack.
---
### Extended 0-1 Knapsack Problem Approach and Explanation
#### Approach and Calculations
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/233/original/upload_961829dd2d7bebc7db57166a33ace5ff.png?1696400455" width=600 />
The normal approach to solve this problem would involve using a recursive or iterative algorithm to consider all possible combinations of toys and select the one with the maximum happiness that doesn't exceed the weight limit. However, due to the constraints provided (N up to 500, `wt[i]` up to $10^9$, ``W`` up to $10^9$), this approach would be extremely slow and inefficient.
By employing dynamic programming, we can optimize the solution significantly. The DP approach allows us to break down the problem into subproblems and store the results of these subproblems in a table to avoid redundant calculations. In this case, we can use a 2-D DP table where `dp[i][w]` represents the maximum happiness that can be achieved with the first `i` toys and a weight constraint of `w`.
DP offers a much faster solution, as it reduces the time complexity from exponential to polynomial time, making it suitable for large inputs like those in the given constraints. Therefore, opting for a DP approach is essential to meet the time and pace constraints of this problem.

View File

@@ -0,0 +1,499 @@
# Graphs 1: Introduction with BFS & DFS
---
## Graphs Introduction
### Introduction
**Graph**: It is a collection of nodes and edges.
Some real life examples of Graph -
1. Network of computers
2. A Website
3. Google Maps
4. Social Media
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/778/original/Screenshot_2024-01-30_at_6.59.51_PM.png?1706621403" width="400" />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/779/original/Screenshot_2024-01-30_at_6.58.46_PM.png?1706621438" width="400" />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/780/original/Screenshot_2024-01-30_at_6.56.17_PM.png?1706621456" width="400" />
---
### Types of Graph
### Cyclic Graph
A cyclic graph contains at least one cycle, which is a closed path that returns to the same vertex.
Diagram:
```javascript
A -- B
| |
| |
D -- C
```
### Acyclic Graph
An acyclic graph has no cycles, meaning there are no closed paths in the graph.
Diagram:
```javascript
A -- B
| |
D C
```
### Directed Graph (Digraph)
In a directed graph, edges have a direction, indicating one-way relationships between vertices.
Diagram:
```javascript
A --> B
| |
v v
D --> C
```
### Undirected Graph
In an undirected graph, edges have no direction, representing symmetric relationships between vertices.
Diagram:
```javascript
A -- B
| |
| |
D -- C
```
### Connected Graph
A connected graph has a path between every pair of vertices, ensuring no isolated vertices.
Diagram
```javascript
A -- B
|
D -- C
```
### Disconnected Graph
A disconnected graph has at least two disconnected components, meaning there is no path between them.
Diagram:
```javascript
A -- B C -- D
| |
E -- F G -- H
```
### Weighted Graph
In a weighted graph, edges have associated weights or costs, often used to represent distances, costs, or other metrics.
Diagram (Undirected with Weights):
```javascript
A -2- B
| |
1 3
| |
D -4- C
```
### Unweighted Graph
An unweighted graph has no associated weights on its edges.
Diagram (Undirected Unweighted):
```javascript
A -- B
|
D -- C
```
### Degree of a Vertex
The degree of a vertex is the number of edges incident to it.
Diagram:
```javascript
B
|
A--C--D
```
### Outdegree of a Vertex
The outdegree of a vertex in a directed graph is the number of edges leaving that vertex.
Diagram:
```javascript
A --> B
| |
v v
D --> C
```
### Simple Graph
A simple graph has no self-loops or multiple edges between the same pair of vertices.
Diagram:
```javascript
A -- B
|
D -- C
```
---
### How to store a graph
### Graph:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/759/original/Screenshot_2024-01-30_at_3.01.38_PM.png?1706607105" width=400/>
### Adjacency Matrix:
All the edges in above graph has equal weights.
In adjacency matrix, `mat[i][j] = 1`, if there is an edge between them else it will be 0.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/760/original/Screenshot_2024-01-30_at_3.02.55_PM.png?1706607186" width=400/>
#### Pseudocode:
```cpp
int N, M
int mat[N+1][M+1] = {0}
for(int i=0; i < A.size(); i++) {
u = A[i][0];
v = A[i][1];
mat[u][v] = 1
mat[v][u] = 1
}
```
Note: In case of weighted graph, we store weights in the matrix.
**Advantage:** Easy to update new edges.
**Disadvantage:** Space wastage because of also leaving space for non-exitent edges.
Moreover,
If N<=10^5, it won't be possible to create matrix of size 10^10.
It is possible only if N <= 10^3
**Space Complexity:** O(N^2^)
### 2. Adjacency List:
An adjacency list is a common way to represent a graph in computer science. It's used to describe which nodes (or vertices) in the graph are connected to each other. Here's how it works:
#### Graph:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/759/original/Screenshot_2024-01-30_at_3.01.38_PM.png?1706607105" width=400/>
#### Adjacency List:
Stores the list of nodes connected corresponding to every node.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/761/original/Screenshot_2024-01-30_at_3.08.41_PM.png?1706607566" width=200/>
We can create map of <int, list> or an array of lists
```
map<int, list<int>> graph;
OR
list<int> graph[]
```
#### Pseudocode:
```javascript
int N
int M
list < int > graph[N + 1]
for (int i = 0; i < A.size(); i++) {
u = A[i][0]
v = A[i][1]
graph[u].add(v)
graph[v].add(u)
}
```
* We refer the adjacent nodes as **neighbours**.
---
### Question
Consider a graph contains V vertices and E edges. What is the **Space Complexity** of adjacency list?
**Choices**
- [ ] O(V^2)
- [ ] O(E^2)
- [x] O(V + E)
- [ ] O(V*E)
Space is defined by the edges we store. An Edge e comprise of two nodes, a & b. For a, we store b and for b, we store a. Hence, 2 * E.
Now, we are doing this for every node, hence +V.
Space Complexity: O(V+E)
---
### Graph traversal algorithm - DFS
There are two traversal algorithms - DFS (Depth First Search) and BFS(Breadth First Search).
In this session, we shall learn DFS and in next, BFS.
### DFS
Depth-First Search (DFS) is a graph traversal algorithm used to explore all the vertices and edges of a graph systematically. It dives deep into a graph as far as possible before backtracking, hence the name "Depth-First." Here's a basic explanation of the DFS process with an example:
### Process of DFS:
1. **Start at a Vertex:** Choose a starting vertex (Any).
2. **Visit and Mark:** Visit the starting vertex and mark it as visited.
3. **Explore Unvisited Neighbors:** From the current vertex, choose an unvisited adjacent vertex, visit, and mark it.
4. **Recursion:** Repeat step 3 recursively for each adjacent vertex.
5. **Backtrack:** If no unvisited adjacent vertices are found, backtrack to the previous vertex and repeat.
6. **Complete When All Visited:** The process ends when all vertices reachable from the starting vertex have been visited.
### Example/Dry-run:
Consider a graph with vertices A, B, C, D, E connected as follows:
```
A ------ B
| |
| |
| |
C D
\
\
\
\
E
```
**DFS Traversal:**
* Start at A: Visit A.
* Visit Unvisited Neighbors of A:
* Go to B (unvisited neighbor of A).
* Visit B.
* Visit Unvisited Neighbors of B:
* Go to D (unvisited neighbor of B).
* Visit D.
* Backtrack to B: Since no more unvisited neighbors of D.
* Backtrack to A: Since no more unvisited neighbors of B.
* Visit Unvisited Neighbors of A:
* Go to C (unvisited neighbor of A).
* Visit C.
* Visit Unvisited Neighbors of C:
* Go to E (unvisited neighbor of C).
* Visit E.
* End of DFS: All vertices reachable from A have been visited.
**DFS Order:**
The order of traversal would be: **A → B → D → C → E**.
#### Pseudocode:
We'll take a visited array to mark the visited nodes.
```javascript
// Depth-First Search function
int maxN = 10 ^ 5 + 1
list < int > graph[maxN];
bool visited[maxN];
void dfs(int currentNode) {
// Mark the current node as visited
visited[currentNode] = true;
// Iterate through the neighbors of the current node
for (int i = 0; i < graph[currentNode].size(); i++) {
int neighbor = graph[u][i];
// If the neighbor is not visited, recursively visit it
if (!visited[neighbor]) {
dfs(neighbor);
}
}
}
```
><img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/784/original/IMG_1C2FED3C35EF-1.jpeg?1706628598" width="500" />
---
### Question
Time Complexity for DFS?
**Choices**
- [x] O(V + E)
- [ ] O(V)
- [ ] O(2E)
**Explanation**:
The time complexity of the DFS algorithm is O(V + E), where V is the number of vertices (nodes) in the graph, and E is the number of edges. This is because, in the worst case, the algorithm visits each vertex once and each edge once.
**Space Complexity:** O(V)
---
### Problem 1 Detecting Cycles in a Directed Graph
Check if given graph has a cycle?
**Examples**
1)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/787/original/Screenshot_2024-01-30_at_9.16.41_PM.png?1706629671" width="250"/>
2)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/786/original/Screenshot_2024-01-30_at_9.17.06_PM.png?1706629663" width="300"/>
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
Apply DFS, if a node in current path is encountered again, it means cycle is present!
With this, we will have to keep track of the path.
Example 1:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/786/original/Screenshot_2024-01-30_at_9.17.06_PM.png?1706629663" width="300"/>
>Say we start at 0 -> 1 -> 3
path[] = {0, 1, 3}
Now, while coming back from 3, we can remove the 3 from path array.
path[] = {0, 1}
Now, 0 -> 1 -> 2 -> 3
path[] = {0, 1, 2, 3} ***[Here, we came back to 3, but via different path, which is not an issue for us]***
Example 2:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/787/original/Screenshot_2024-01-30_at_9.16.41_PM.png?1706629671" width="250"/>
> Say we start at 0 -> 1 -> 2 -> 3
path[] = {0, 1, 2, 3}
Now, from 3, we come back to 1.
path[] = {0, 1, 2, 3, 1} ***[But 1 is already a part of that path, which means cycle is present]***
#### Pseudocode
```javascript
list < int > graph[] //filled
bool visited[] = {0}
int path[N] = {0}
bool dfs(int u) {
visited[u] = true
path[u] = 1
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i]
if (path[v] == 1) return true
else if (!visited[v] && dfs(v)) {
return true
}
}
path[u] = 0;
return false;
}
```
#### Complexity
**Time Complexity:** O(V + E)
**Space Complexity:** O(V)
---
### Problem 2 Number of Islands Statement and Approach
You are given a 2D grid of '1's (land) and '0's (water). Your task is to determine the number of islands in the grid. An island is formed by connecting adjacent (horizontally or vertically) land cells. Diagonal connections are not considered.
Given here if the cell values has 1 then there is land and 0 if it is water, and you may assume all four edges of the grid are all surrounded by water.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/523/original/upload_a58eb3b65d084e2319c537762414bba7.jpeg?1697742306" width=400/>
In this case we can see that our answer is 5.
**Que: Do we need adjacency list ?**
Ans: No, since the information is already present in form of matrix which can be utilised as it is.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach:
**Set a Counter:** Start with a counter at zero for tracking island count.
**Scan the Grid:** Go through each cell in the grid.
**Search for Islands:** When you find a land cell ('1'), use either BFS or DFS to explore all connected land cells.
**Mark Visited Cells:** Change each visited '1' to '0' during the search to avoid recounting.
**Count Each Island:** Increase the counter by 1 for every complete search that identifies a new island.
**Finish the Search:** Continue until all grid cells are checked.
**Result:** The counter will indicate the total number of islands.
---
### Number of Islands Dry Run and Pseudocode
#### Dry-Run:
```java
[
['1', '1', '0', '0', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '0', '0', '0'],
['0', '0', '0', '1', '1']
]
```
* Initialize variable islands = 0.
* Start iterating through the grid:
* At grid[0][0], we find '1'. Increment islands to 1 and call visitIsland(grid, 0, 0).
* visitIsland will mark all connected land cells as '0', and we explore the neighboring cells recursively. After this, the grid becomes:
```cpp-
[
['0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0'],
['0', '0', '1', '0', '0'],
['0', '0', '0', '1', '1']
]
```
* Continue iterating through the grid:
* At grid[2][2], we find '1'. Increment islands to 2 and call visitIsland(grid, 2, 2).
* visitIsland will mark connected land cells as '0', and we explore the neighboring cells recursively. After this, the grid becomes:
```java
[
['0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0'],
['0', '0', '0', '1', '1']
]
```
* Continue the iteration.
* At grid[3][3], we find '1'. Increment islands to 3 and call visitIsland(grid, 3, 3).
We can visit only 4 coordinates, considering them to be i, j; it means we can visit **(i,j-1), (i-1, j), (i, j+1), (i+1, j)**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/792/original/Screenshot_2024-01-30_at_9.58.09_PM.png?1706632097" width=500 />
#### Pseudocode
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/796/original/Screenshot_2024-01-30_at_10.04.29_PM.png?1706632480" width=400 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/794/original/Screenshot_2024-01-30_at_10.03.04_PM.png?1706632395" width=400 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/793/original/Screenshot_2024-01-30_at_10.02.10_PM.png?1706632342" width=400 />

View File

@@ -0,0 +1,417 @@
# DSA: Graphs 2: BFS, Matrix Questions & Topological Sort
---
## BFS
Breadth-First Search (BFS) is another graph traversal algorithm used to explore and navigate graphs or trees. It starts at a source node and explores all its neighbors at the current depth level before moving on to the next level. BFS uses a queue data structure to maintain the order of nodes to be visited.
### Approach:
* We use a queue to maintain the order of nodes to visit in a breadth-first manner.
* We start with a vector visited to keep track of whether each node has been visited. Initially, all nodes are marked as unvisited (false).
* We enqueue the startNode into the queue and mark it as visited.
* We enter a loop that continues until the queue is empty.
* In each iteration, we dequeue the front element (the current node) from the queue and process it. Processing can include printing the node or performing any other desired operation.
* We then iterate through the neighbors of the current node. For each neighbor that hasn't been visited, we enqueue it into the queue and mark it as visited.
* The BFS traversal continues until the queue is empty, visiting nodes level by level.
### Example/Dry-Run
```javascript
A --- B --- C
| |
+---------+
|
D
```
Suppose in this if we want to perform BFS then:
* Start from the source node (City A).
* Explore neighboring nodes level by level.
* Use a queue to maintain the order.
* Mark visited nodes (using adjaency list) to avoid repetition.
* Stop when the target node (City D) is reached.
* This guarantees the shortest path in unweighted graphs.
#### Pseudocode:
```javascript
void bfs(int startNode) {
vector < bool > visited(MAX_NODES, false); // Initialize all nodes as unvisited
queue < int > q;
q.push(startNode); // Enqueue the start node
visited[startNode] = true; // Mark the start node as visited
while (!q.empty()) {
int currentNode = q.front();
q.pop();
// Process the current node (e.g., print or perform an operation)
for (int neighbor: graph[currentNode]) {
if (!visited[neighbor]) {
q.push(neighbor); // Enqueue unvisited neighbors
visited[neighbor] = true; // Mark neighbor as visited
}
}
}
```
#### Compexity
**Time Complexity:** O(V + E)
**Space Complexity:** O(V)
---
### Question
Consider a graph with the following adjacency matrix:
```
[0, 1, 1, 0]
[1, 0, 0, 0]
[1, 0, 0, 1]
[0, 0, 1, 0]
```
What is the order in which the nodes will be visited when performing a breadth-first search (BFS) starting from node 0?
**Choices**
- [x] 0, 1, 2, 3
- [ ] 0, 1, 3, 2
- [ ] 0, 2, 3, 1
- [ ] 0, 1, 3, 1
The correct answer is (a) 0, 1, 2, 3.
BFS (Breadth-First Search) explores neighbor nodes first before moving to the next level. Starting from node 0, BFS visits its neighbors 1 and 2. It then moves to the next level and visits 1's neighbor 3. Finally, it moves to the next level but finds no more unvisited nodes. Therefore, the order of BFS traversal is 0, 1, 2, 3.
---
### Multisource BFS
There are N number of nodes and multisource(S1,S2,S3), we need to find the length of shortest path for given destination node to any one of the source node{S1,S2,S3}.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/088/original/upload_5bc332d89630700685c6151288b14228.png?1696918618" width=500 />
#### Solution
Length = 2
In the beginning, we need to push all source node at once and apply exact BFS,then return the distance of destination node.
#### Time and Space Complexity
* **TC -** O(N+E)
* **SC -** O(N+E)
---
### Rotten Oranges
There is given a matrix and there are 3 values where 0 means empty cell, 1 means fresh orange present and 2 means rotten orange prsent, we need to find the time when all oranges will become rotten.
**Note:** If not possible, return - 1.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/090/original/upload_3461de9fe730f97814a45fd8d8c6eb74.png?1696918669" width=300 />
#### Solution
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/091/original/upload_d8bb39bbd8d744419836f41e3bd6c606.png?1696918713" width=500 />
**Answer:** after 3 minutes all oranges will get rotten.
* Initially, We need to insert all rotten oranges in Queue (where each element in queue is in a pair),
* Then check if any fresh oranges has become rotten and if they did, return the time otherwise return -1.
#### Pseudocode
```java
public class RottingOranges {
private static final int[] dx = {-1, 1, 0, 0};
private static final int[] dy = {0, 0, -1, 1};
public int orangesRotting(int[][] grid) {
int rowCount = grid.length;
int colCount = grid[0].length;
Queue< int[] > queue = new LinkedList< >();
int freshOranges = 0;
int minutes = 0;
// Count fresh oranges and add rotten oranges to the queue
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
if (grid[i][j] == 2) {
queue.offer(new int[]{i, j, minutes});
} else if (grid[i][j] == 1) {
freshOranges++;
}
}
}
if (freshOranges == 0) {
// If there are no fresh oranges initially, they are already rotten.
return 0;
}
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int x = cell[0];
int y = cell[1];
minutes = cell[2];
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (isValid(grid, newX, newY) && grid[newX][newY] == 1) {
grid[newX][newY] = 2;
freshOranges--;
queue.offer(new int[] {newX, newY, minutes + 1});
}
}
}
return (freshOranges == 0) ? minutes : -1;
}
private boolean isValid(int[][] grid, int x, int y) {
int rowCount = grid.length;
int colCount = grid[0].length;
return x >= 0 && x < rowCount && y >= 0 && y < colCount;
}
```
---
### Possibility of finishing the courses
Given N courses with pre-requisites, we have to check if it is possible to finish all the course ?
**Example:**
N = 5
**Pre-requisites**
1 ---> 2 & 3 [1 is pre-req for 2 and 3]
2 ---> 3 & 5
3 ---> 4
4 ---> 2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/951/original/Screenshot_2024-02-01_at_6.42.52_PM.png?1706793211" width=300 />
The pre-req information is represented in above directed graph.
#### Explanantion:
**Que:** Which course shall we complete first?
The one having no pre-requisites. (say 1)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/952/original/Screenshot_2024-02-01_at_6.48.07_PM.png?1706793500" width=300 />
Next, which one shall we pick ?
We can't pick any course because of the dependencies. Hence, it means we can't finish courses in above example.
The reason is there's a cycle!
Have you heard of the term deadlock ? [*For experience we need job, for job we need experience like scenario :p* ]
**Conclusion:** If it's a cyclic graph, answer will always be false, else true.
**Observation:** To solve the problem, we need directed acyclic graph!
---
### Possibility of finishing courses approach
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/953/original/Screenshot_2024-02-01_at_6.53.36_PM.png?1706793868" width=320 />
Pick ? 1 [not dependant on any other course]
Next Pick ? 2
Next Pick ? 3
Next Pick ? 4
Next Pick ? 5
**Order:**
1 2 3 4 5
The above order is known as topological sort/ topological order.
**Que:** For one graph, can we have only one topological order?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/955/original/Screenshot_2024-02-01_at_6.57.14_PM.png?1706794109" width=300 />
Is the order 1 2 3 4 5 valid ? YES!
What about 1 3 2 4 5 ? YES!
What about 1 3 4 2 5 ? YES!
Hence, it is possible that we have multiple topological order for a given graph.
#### Definition
**Topological sort** is a linear ordering of the vertices (nodes) in a directed acyclic graph (DAG) such that for every directed edge (u, v), vertex u comes before vertex v in the ordering. In other words, it arranges the nodes in such a way that if there is a directed edge from node A to node B, then node A comes before node B in the sorted order.
---
## Topological Sort
Let's find topological ordering of below graph!
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/956/original/Screenshot_2024-02-01_at_7.04.26_PM.png?1706794475" width=350 />
**Indegree:** The count of incoming nodes is known as indegree of a node.
For above graph, the indegrees will be as follows -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/957/original/Screenshot_2024-02-01_at_7.08.52_PM.png?1706794742" width = 350 />
### Next Steps
* Insert all the nodes with indegree=0 in a queue
* Dequeue an element from the queue and update the indegree for all the neighbours, if the indegree for any nbr becomes 0 add that node in the queue.
### Approach:
* Create an array to store indegrees, initially set all values to zero.
* Iterate through each node in the graph using a loop.
* For each node, traverse its outgoing edges by iterating through its adjacency list.
* For each neighboring node in the adjacency list, increment its indegree count by one.
* Continue the loop until you've processed all nodes in the graph.
* The array now contains the indegree of each node, where the value at index i represents the indegree of node i.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/522/original/upload_8ed904670ed12810074a3d07c9d7ea10.png?1697742167" width=400/>
In the above photo we can refer the indegree of each of the nodes is written in green.
#### Pseudocode:
```java
in [N], i, in [i] = 0;
for (i = 0; i < n; i++) {
for (nbr: adj[i]) {
ibr[i] += 1;
}
}
```
#### Complexity
**Time Complexity:** O(N + E)
**Space Complexity:** 0(N)
---
### Topological Sort (Right to Left)
In a right-to-left topological order, you start from the "rightmost" vertex (i.e., a vertex with no outgoing edges) and proceed leftward. This approach can be useful in certain situations and can be thought of as a reverse topological ordering.
Here's how you can approach it:
#### Approach:
* Identify a vertex with no outgoing edges (in-degree = 0). If there are multiple such vertices, you can choose any of them.
* Remove that vertex from the graph along with all its outgoing edges. This removal may affect the in-degrees of other vertices.
* Repeat steps 1 and 2 until all vertices are removed from the graph. The order in which you remove the vertices constitutes the right-to-left topological order.
#### Example/Dry-Run:
```java
A -> B -> C
| |
v v
D E
```
To find the right-to-left topological order:
* Start with a vertex with no outgoing edges. In this case, you can start with vertex C.
* Remove vertex C and its outgoing edge. The graph becomes:
```java
A -> B
|
v
D E
```
Now, you can choose either B or E, both of which have no outgoing edges. Let's choose B and remove it:
```java
A
|
v
D E
```
* Continue with the remaining vertices. Choose A next:
```java
|
v
D E
```
* Finally, remove D and E:
```java
|
v
| |
```
The order in which you removed the vertices is a right-to-left topological order: C, B, A, D, E.
#### Pseudocode
```java
function topologicalSortRightToLeft(graph):
// Function to perform DFS and record nodes in the order they are finished
function dfs(node):
mark node as visited
for each neighbor in graph[node]:
if neighbor is not visited:
dfs(neighbor)
append node to order list
create an empty order list
initialize a visited array with False for all nodes
for each node in the graph:
if node is not visited:
dfs(node)
reverse the order list
return the reversed order list as the topological order (right-to-left)
```
#### Complexity
**Time Complexity:** O(V+E)
**Space Complexity:** O(V)
---
### Question
Which of the following is correct topological order for this graph?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/881/original/1.png?1706710397" width=300/>
**Choices**
- [x] TD,TA,TC,TB
- [ ] TA,TD,TC,TB
- [ ] TC,TA,TD,TB
---
### Another approach to BFS
Find the minimum number of edges to reach v starting from u in undirected simple graph.
**Graph:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/132/original/upload_25a85963d2c4d1d4dc148c24f6295ddd.png?1696922220)" width=550 />
#### Approach
Imagine you're playing a game where you have to find the quickest way from point A (vertex u) to point B (vertex v) in a giant maze. This is similar to using Breadth-First Search (BFS) in a graph.
**Think of BFS as your strategy for exploring the maze:**
**Start at Point A:** You're at the entrance of the maze (vertex u), ready to find the shortest path to the treasure (vertex v).
**Explore Closest Paths First:** Just like deciding which paths to take in the maze, BFS first checks all the paths that are one step away from your current position, then moves to paths two steps away, and so on.
**Layer by Layer:** It's like a ripple effect in a pond. You throw a stone (start at vertex u), and the ripples (paths) expand outward, reaching further away points one layer at a time.
**Reaching Point B:** As you follow this method, the moment you step on point B (vertex v) in the maze, you know you've found the shortest route. In BFS, when you first reach vertex v, it guarantees the minimum steps taken, just like finding the quickest path out of the maze.
So, by using BFS in our maze game (or graph), we ensure we're taking the most efficient route possible, avoiding any long detours or dead-ends. It's a smart and systematic way to reach our goal with the least amount of hassle!

View File

@@ -0,0 +1,239 @@
# Graphs 3: MST & Dijkstra
---
### Challenges in Flipkart's Logistics and Delivery
**Scenario:**
Suppose Flipkart has N local distribution centers spread across a large metropolitan city. These centers need to be interconnected for efficient movement of goods. However, building and maintaining roads between these centers is costly. Flipkart's goal is to minimize these costs while ensuring every center is connected and operational.
**Goal:** You are given number of centers and possible connections that can be made with their cost. Find minimum cost of constructing roads between centers such that it is possible to travel from one center to any other via roads.
**Explanation**
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/126/original/upload_b27e5dc6056098a838971ceb1ddf7aab.png?1696921885" width=300 />
**Output:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/127/original/upload_f8296197fcf4b61f3d2531921d4c9a43.png?1696921923" width=500 />
### Idea:
To achieve the lowest cost in our scenario, consider these key points:
1. **Aim for Fewer roads:** Minimizing the number of roads directly leads to reduced costs.
2. **Opt for a Tree Structure:** Why a tree? Well, in the world of data structures, a tree uniquely stands out when it comes to minimal connections. For any given N nodes, a tree is the only structure that connects all nodes with exactly N - 1 edges. This is precisely what we need - the bare minimum of edges to connect all points, ensuring the lowest possible number of roads.
**Another Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/846/original/Screenshot_2024-01-31_at_4.11.16_PM.png?1706697687" width=500 />
The end goal is that all centers should be connected.
**Possible Solutions -**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/847/original/Screenshot_2024-01-31_at_4.13.05_PM.png?1706697792" width=300 />
Here first is better because the sum of all edge weights is minimum.
The tree which spans (covers) all the vertices with the minimum number of edges needed to connect them is known as **Spanning Tree**.
### Minimum Spanning Tree
The minimum spanning tree has all the properties of a spanning tree with an added constraint of having the minimum possible weights among all possible spanning trees.
**Uniqueness of MST:** If all edge weights are unique, there's only one MST. If some weights are the same, multiple MSTs can exist.
**Algorithms for MST:** Kruskal's and Prim's algorithms are used to find MSTs. The MST found can vary based on the choices made for edges with equal weights. Both algorithms solve for same problem having same time and space complexities.
### Solution to Flipkart's problem
**Application of MST:**
* **Identify All Possible Connections:** First, identify all the possible routes that can connect these N centers. Imagine this as a network where each center is a node, and each possible road between two centers is an edge.
* **Assign Costs:** Assign a cost to each potential road, based on factors like distance, traffic, or construction expenses. In real-life terms, shorter and more straightforward routes would generally cost less.
* **Create the MST:** Now, apply the MST algorithm (like Kruskal's or Prim's). The algorithm will select routes that connect all the centers with the least total cost, without forming any loops or cycles.
* **Outcome:** The result is a network of roads connecting all centers with the shortest total length or the lowest cost.
---
## Prim's Algorithm
Let's consider the below **Graph:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/855/original/Screenshot_2024-01-31_at_4.34.43_PM.png?1706699091" width=350 />
Say we start with **vertex 5**, now we can choose an edge originating out of 5.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/856/original/Screenshot_2024-01-31_at_4.37.30_PM.png?1706699339" width=350 />
*Which one should we choose?*
The one with minimum weight.
We choose 5 ---- 3 with weight 2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/857/original/Screenshot_2024-01-31_at_4.41.06_PM.png?1706699512" width=350 />
Now, after this, since 5 and 3 are part of the MST, we shall choose a min weighted edge originated from either 3 or 5. That edge should connect to a vertex which hasn't been visited yet.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/858/original/Screenshot_2024-01-31_at_4.41.23_PM.png?1706699636" width=350 />
We choose 5 ---- 4 with weight 3
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/859/original/Screenshot_2024-01-31_at_4.44.49_PM.png?1706699696" width=350 />
Now, same process follows i.e, we can select a min weighted edge originating from 3, 4, or 5 such that it should connect to a vertex that hasn't been visited yet.
**After completing the entire process, we shall have below MST.**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/860/original/Screenshot_2024-01-31_at_4.47.55_PM.png?1706699884" width=350 />
### Execution
Say we have a black box(we'll name it later)
Now, say we start with 5. From 5, via weight 3 we can visit 4, via weight 5 we can visit 6, via weight 2 we can visit 3.
We'll information as - (weight, vertex)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/861/original/Screenshot_2024-01-31_at_4.51.52_PM.png?1706700121" width=350 />
From this, we'll get vertex reachable via min weight, which data structure can be helpful ?
**MIN HEAPS**
Now, we remove (2, 3) from heaps and connect 3 to 5.
From 3, the nodes that are reachable will be pushed to the heap.
*We'll insert only those vertices which haven't been visited yet.*
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/862/original/Screenshot_2024-01-31_at_4.56.18_PM.png?1706700386" width=350 />
Select the minimum weighted -> (3, 4)
Now, this shall continue.
#### Pseudocode
```java
while (!heap.isEmpty()) {
Pair p = heap.getMin();
if (vis[v] == true)
continue;
// Add the vertex to the MST and accumulate the weight
vis[v] = true;
ans += p.first
// Now, you can optionally iterate through the adjacent vertices of 'v' and update the heap with new edges
for ((u, w) in adj[v]) {
if (!vis[u]) {
// Add the unvisited neighbor edges to the heap
heap.add({w,u});
}
}
}
```
#### Complexity
**Time Complexity:** O(E * logE)
**Space Complexity:** O(V + E)
---
## Dijkstras Algorithm
There are N cities in a country, you are living in city-1. Find minimum distance to reach every other city from city-1.
We need to return the answer in the form of array
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/133/original/upload_3a593270efea8fe4f4dfe3a94fcb3e19.png?1696922261)" width=600 />
**Output:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/134/original/upload_188eeb11a6f84934ab19cecfd405325e.png?1696922288" width=400 />
**Initialize Data Structures:**
* Create an adjacency list (graph) to represent the cities and their distances.
* Initialize a distances list with infinity for all cities except city-1 (set to 0).
* Use a `Heap<pair>` (heap) to explore cities, starting with the pair (0, 0) (distance from city-1 is 0, and it's city-1 itself). The heap will contain `<Distance from the source vertex of a node, node>`.
**Explore Cities:**
* While heap is not empty:
* Pop the pair (dist, u) with the shortest known distance.
* If dist is greater than the known distance to the city u, skip it.
* Otherwise, update the distance and explore its neighbors.
**Explore Neighbors:**
* For each neighbor of city u in the graph:
* Calculate the distance from city-1 via city u.
* If this new distance is shorter, update it and add the pair (new_distance, v) to the heap, where v is the neighbor.
**Termination:**
* Continue until the heap is empty, exploring all cities.
**Return Result:**
* The distances list now holds the minimum distances from city-1 to all other cities.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/136/original/upload_b3f70ce6b686d6fd40039eba2568927b.png?1696922372" width=700 />
```java
while (!hp.isEmpty()) {
Pair rp = hp.poll(); // Extract the minimum element
int d = rp.first; // Distance
int u = rp.second; // City
// Skip if this distance is greater than the known distance
if (d > dist[u]) {
continue;
}
// Explore neighbors of u and update distances
for ( /* Loop through neighbors */ ) {
int v = /* Neighbor city */ ;
int w = /* Weight to reach v from u */ ;
// Calculate the new distance via u
int new_dist = dist[u] + w;
// If the new distance is shorter, update dist and add to heap
if (new_dist < dist[v]) {
dist[v] = new_dist;
hp.add(new Pair(new_dist, v));
}
}
}
}
```
* The time complexity of the Dijkstra's algorithm implementation with a min-heap of pairs is $O((E + V) * log(V))$, where E is the number of edges, V is the number of vertices (cities), and log(V) represents the complexity of heap operations.
* The space complexity of this implementation is O(V + E), where V is the space used to store the dist array (minimum distances) for all cities, and E is the space used to represent the graph (adjacency list).
### Can Dijkstra's algorithm work on negative wieghts?
Dijkstra's algorithm is not suitable for graphs with negative edge weights as it assumes non-negative weights to guarantee correct results. Negative weights can lead to unexpected behavior and incorrect shortest path calculations.

View File

@@ -0,0 +1,841 @@
# Advanced DSA: Greedy
---
## Introduction on Greedy
The greedy approach deals with maximizing our profit and minimizing our loss.
**Example 1:**
Suppose we want to buy an iPhone, and the price of an iPhone at Amazon is 1.3 lakhs, the price at Paytm at 1.2 lakhs and the price at Flipkart is 1.25 lakhs.
So we will buy an iPhone from Paytm as it has a minimum price.
Here we are considering only one factor i.e. the amount of an iphone.
**Example 2:**
Suppose we want to switch a company and we have three offer letters. The first company is given a 22 LPA offer, the second company is given a 25 LPA, and the third company is given a 28 LPA offer.
So we are going to select 28 LPA offer company. Here we are again considering the money factor, we are not considering the factors:
- Job is remote
- Work culture
- Timings
- Growth
But if 25 LPA company has other facilities better than 28 LPA offer company. 25 LPA company has flexible working hours, provides remote job and good work culture. Then we are going to choose 25 LPA offer company.
If we involve only one factor then selection will become easier and if multiple factors are involved then the decision becomes a bit difficult.
In this lecture, we are going to do questions which involve multiple factors.
---
### Problem 1 Flipkart's Challenge in Effective Inventory Management
In the recent expansion into grocery delivery, Flipkart faces a crucial challenge in effective inventory management. Each grocery item on the platform carries its own expiration date and profit margin, represented by arrays A[i] (expiration date for the ith item) and B[i] (profit margin for the ith item). To mitigate potential losses due to expiring items, Flipkart is seeking a strategic solution. The objective is to identify a method to strategically promote certain items, ensuring they are sold before their expiration date, thereby maximizing overall profit. Can you assist Flipkart in developing an innovative approach to optimize their grocery inventory and enhance profitability?
**A[i] -> expiration time for ith item**
**B[i] -> profit gained by ith item**
Time starts with **T = 0**, and it takes 1 unit of time to sell one item and the item **can only be sold if T < A[i].**
Sell items such that the sum of the **profit by items is maximized.**
**Example**
**`A[] = [3 1 3 2 3]`**
**`B[] = [6 5 3 1 9]`**
**`index: 0 1 2 3 4`**
### Idea 1 - Pick the highest profit item first
- We will first sell the item with the highest profit.
Initially T = 0
- We have the maximum profit item at index 4, so will sell it and increment T by 1.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 4 | 9 |
- Now the item at index 1 can't be sold as A[1] <= T. So we can not sell it.
- Now we will sell the item at 0 index.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 4 | 9 |
| 2 | 0 | 6 |
- Now the item at index 3 can't be sold as A[3] <= T. So we can not sell it.
- Now we will sell the item at 2 index.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 4 | 9 |
| 2 | 0 | 6 |
| 3 | 2 | 3 |
So we have a total profit: 18.
:bulb: **`But we can have a better answer than this answer. Let us try one more combination of selling items.`**
**`A[] = [3 1 3 2 3]`**
**`B[] = [6 5 3 1 9]`**
**`index: 0 1 2 3 4`**
Initially T = 0
- We have sold the item at index 1 and increment T by 1.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 1 | 5 |
- Now we have sold the item at index 4 and again increment T by 1.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 1 | 5 |
| 2 | 4 | 9 |
- Now the item at index 3 can't be sold as A[3] <= T. So we can not sell it.
- Now have sold the item at 0 index.
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 1 | 5 |
| 2 | 4 | 9 |
| 3 | 0 | 6 |
- Now the item at index 2 can't be sold as A[2] <= T. So we can not sell it
So we have a total profit 20.
Here we are getting the total profit greater than the total profit of the previously sold combination of items.
And we can achieve maximum profit 20.
**The greedy approach is selecting the path by greedy approach, in greedy we will select one path based on some conditions by assuming that this path will give us the solution.**
---
### Question
What is the maximum profit we can achieve if we have two items with expiration time in A and profit in B:
A = [1, 2]
B = [3, 1500]
**Choices**
- [ ] 3
- [ ] 1500
- [x] 1503
- [ ] 0
**Explanation**
A = [1, 2]
B = [3, 1500]
Initially T = 0
- We have selected the item at index 9 and incremented T by 1.
|T|Item Index|Profit|
|-|-|-|
|1|0|3|
- Now we have selected the item at index 1 and again increment T by 1.
|T|Item Index|Profit|
|-|-|-|
|1|0|3|
|2|1|1500|
So we have a total profit 1503.
---
### Solution - Effective Inventory Management
- Pick the highest profit item first approach is not giving us the maximum profit, so it will not work. We have to think of another approach.
#### Idea: Sell Everything
Our approach is always towards selling all the items so that we can achieve maximum profit.
So our approach is to first sell the item with the minimum end time.
For this, we have to sort the expiration time in ascending order.
**Example:**
A[] = [1, 3, 3, 3, 5, 5, 5, 8]
B[] = [5, 2, 7, 1, 4, 3, 8, 1]
Initially T = 0
- We can sell an item available at index 0, as A[0] = 1, and T < A[0]
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 0 | 5 |
- We can sell an item available at index 1, as A[1] = 3, and T < A[1]
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 0 | 5 |
| 2 | 1 | 2 |
- We can sell a item available at index 2, as A[2] = 3, and T < A[2]
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 0 | 5 |
| 2 | 1 | 2 |
| 3 | 2 | 7 |
- But we can not sell the item available at index 3, as A[3] = 3, and A[3] <= T, here the profit of the item at index 3 is 1, so we ignore it easily as it has very little profit.
- We can sell a item available at index 4, as A[4] = 5, and T < A[4].
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 0 | 5 |
| 2 | 1 | 2 |
| 3 | 2 | 7 |
| 4 | 4 | 4 |
- We can sell a item available at index 5, as A[5] = 5, and T < A[5].
| T | Item Index | Profit |
|:---:|:---------:|:------:|
| 1 | 0 | 5 |
| 2 | 1 | 2 |
| 3 | 2 | 7 |
| 4 | 4 | 4 |
| 5 | 5 | 3 |
- But we can not sell the item available at index 6, as A[6] = 5, and A[6] <= T. But we can say that we must have to select this item to get the maximum profit as it has the larger profit. But we are rejecting it.
- To select the item available at index 6, we have to remove one of the previously selected items.
- So we want to discard the item with the minimum profit among all the selected items.
| T | Item Index | Profit |
|:-----:|:---------:|:------:|
| 1 | 0 | 5 |
| ~~2~~ | ~~1~~ | ~~2~~ |
| 3 | 2 | 7 |
| 4 | 4 | 4 |
| 5 | 5 | 3 |
| 5 | 6 | 8 |
- We can sell item available at index 7, as A[7] = 8, and T < A[7].
|T|Item Index|Profit|
|-|-|-|
|1|0|5|
|~~2~~|~~1~~|~~2~~|
|3|2|7|
|4|4|4|
|5|5|3|
|5|6|8|
|6|7|1|
So we have a total profit 28.
**`At any point, if we weren't able to choose a item as T >= A[i] and realize we made a wrong choice before, we will get rid of the item with least profit we previously picked and choose the current one instead.`**
#### Approach
The solution to this question is just like the team selection. We have to select the strongest player, if we have any player who is stronger than the player in our team, then we will remove the weaker player from the team and add that player to our team.
**Example**: Solving using min-heap
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| -- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
|A[ ]| 1 | 3 | 3 | 3 | 5 | 5 | 5 | 8 |
|B[ ]| 5 | 2 | 7 | 1 | 4 | 3 | 8 | 1 |
**Solution**
Initially **T = 0** and we have a empty min-heap.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/025/original/upload_ab9dab0ba128180476a78481551a6052.png?1697558398" width=300/>
All the items are sorted in the ascending order of expiration time.
- We can sell a item available at index 0, as A[0] = 1, so here T < A[0], so we will sell the item available at index 0 and add its profit in min-heap.
**T = 1**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/026/original/upload_f0bd5fe80cb16c3d873110296372f790.png?1697558425" width=300/>
- We can sell a item available at index 1, as A[1] = 3, so here T < A[1], so we will sell the item available at index 1 and add its profit in min-heap.
**T = 2**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/027/original/upload_ef47138100a77d0f53ef1edd8443427d.png?1697558475" width=300/>
- We can sell a item available at index 2, as A[2] = 3, so here T < A[2], so we will sell the item available at index 2 and add its profit in min-heap.
**T = 3**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/028/original/upload_28ca6ab15d82a8c7b7c7aa350206f47d.png?1697558503" width=300/>
- But we can not sell the item available at index 3, as A[3] = 3, and A[3] <= T. Now we will check if we have taken any incorrect steps in the past.
- We check if we have any items in the heap with profit less than 1. So we have 2 minimum profit in the heap but 2 > 1, so it proves all our past decisions are correct. So we will skip the item available at index 3.
- We can sell a item available at index 4, as A[4] = 5, and T < A[4] and add its profit in min-heap.
**T = 4**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/029/original/upload_4a1b06fc1dcfa462631fd5568b2855ae.png?1697558734" width=300/>
- We can sell a item available at index 5, as A[5] = 5, so here T < A[5] and add its profit in min-heap.
**T = 5**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/031/original/upload_a0af46d2f7e9714644fff3cfb82895b6.png?1697558812" width=300/>
- But we can not sell the item available at index 6, as A[6] = 5, and A[6] <= T. Now we will check if we have made any incorrect decisions in the past.
- We have minimum profit 2 in the heap, so remove it from the heap and add the profit of the item available at index 6 in the heap.
**T = 5**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/032/original/upload_34b138f3eac0cc71f879656820275924.png?1697558882" width=300/>
- We can sell a item available at index 7, as A[7] = 8, so here T < A[7], so we will sell the item available at index 7 and add its profit in min-heap.
**T = 6**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/033/original/upload_e8e0a72b4eb9b973c9469195ca6c36af.png?1697558941" width=300/>
- Now we can find the answer by removing one-by-one elements from the heap and adding them to the answer.
So we have final answer = $1 + 3 + 4 + 5 + 7 + 8 = 28$
#### PseudoCode
```cpp
1. Sort them in increasing order of time.
2. Minheap heap:
T = 0
for (i = 0; i < N; i++) {
if (T < A[i]) {
heap.insert(B[i])
T++
} else {
if (B[i] <= root of heap) -> ignore {
}
else {
extractMin()
heap.insert(B[i])
}
}
}
3. Remove all elements from the heap and add them to get the answer.
```
---
### Question
What is the time and space complexity of this question?
**Choices**
- [ ] TC: O(N), SC: O(N)
- [x] TC: O(NlogN), SC: O(N)
- [ ] TC: O(N$^2$), SC: O(N)
- [ ] TC: O(N$^2$) , SC: O(N$^2$)
---
### Effective Inventory Management Complexity
**Time Complexity**
```cpp
1. Sort them in increasing order of time.-- -> NlogN
2. Minheap heap:
T = 0
for (i = 0; i < N; i++) {
-- -> N
if (T < A[i]) {
heap.insert(B[i]) -- -> logN
T++
} else {
if (B[i] <= root of heap) -> ignore {
}
else {
extractMin() -- -> logN
heap.insert(B[i]) -- -> logN
}
}
}
3. Remove all elements from the heap and add them to get the answer.
```
So overall time complexity = O(NlogN) + O(NlogN)
- **Time Complexity: O(NlogN)**
- **Space Complexity: O(N)**
---
### Problem 2 Candy Distribution
There are N students with their marks. The teacher has to give them candies such that
a) Every student should have at least one candy
b) Students with more marks than any of his/her neighbours have more candies than them.
Find minimum candies to distribute.
**Example**
**Input:** [1, 5, 2, 1]
**Explanation:** First we will give 1 candy to all students.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|1|5|2|1|
|candy|1|1|1|1|
Index 1 student has marks greater than their neighbours. So it must have candies greater than his neighbors.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|1|5|2|1|
|candy|1|~~1~~ 2 |1|1|
Index 2 student has marks greater than its right neighbour. So it must have candies greater than his right neighbour.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|1|5|2|1|
|candy|1|~~1~~ 2 |~~1~~ 2 |1|
Now index 1 student again has marks greater than both neighbors but its candies are not greater than its right neighbor's candies. So it must have candies greater than his both neighbors.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|1|5|2|1|
|candy|1|~~1~~ ~~2~~ 3 |~~1~~ 2 |1|
Now all the conditions of the question are satisfied, so total 7 candies are required to be distributed among students.
**Output:** 7
---
### Question
What is the minimum number of candies teacher has to use if the marks are: [4, 4, 4, 4, 4]
**Choices**
- [ ] 1
- [x] 5
- [ ] 10
- [ ] 20
**Explanation**
[4, 4, 4, 4, 4]
First, we will give 1 candy to all students.
|index|0|1|2|3|4|
|-|-|-|-|-|-|
|marks|4|4|4|4|4|
|candy|1|1|1|1|1|
Now any student does not have marks greater than its neighbors. So our candy distribution is perfect.
**So total 5 candies are required.**
---
### Candy Distribution Example
**Example**
**Input:** [8, 10, 6, 2]
First, we will give 1 candy to all students.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|8|10|6|2|
|candy|1|1|1|1|
- Now student at index 2 has marks greater than its right neighbor, so it receive 2 candies.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|8|10|6|2|
|candy|1|1|~~1~~ 2|1|
- Student at index 1 has marks greater than both neighbours, so it must candies greater than both neighbours. So it receives 3 candies.
|index|0|1|2|3|
|-|-|-|-|-|
|marks|8|10|6|2|
|candy|1|~~1~~ 3|~~1~~ 2|1|
So total 7 candies are required.
**Output:** 7
---
### Question
What is the minimum number of candies the teacher has to use if the marks are: [1, 6, 3, 1, 10, 12, 20, 5, 2]
**Choices**
- [ ] 15
- [x] 19
- [ ] 21
- [ ] 20
**Explanation**
[1, 6, 3, 1, 10, 12, 20, 5, 2]
First, we will give 1 candy to all students.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
First, let us consider the left nighbor of all the indexes.
- Now a student at index 1 has marks greater than its left neighbour, so it should receive at least 2 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------- | --- | --- | --- | --- | --- | --- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ 2 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
- Now student at index 2, and 3 does not have marks greater than their left neighbour.
- Student at index 4 has marks greater than its left neighbour, so it should receive at least 2 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------- | --- | --- | ------- | --- | --- | --- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ 2 | 1 | 1 | ~~1~~ 2 | 1 | 1 | 1 | 1 |
- Student at index 5 has marks greater than its left neighbour, so it should receive at least 3 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------- | --- | --- | ------- | ------- | --- | --- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ 2 | 1 | 1 | ~~1~~ 2 | ~~1~~ 3 | 1 | 1 | 1 |
- Student at index 6 has marks greater than its left neighbour, so it should receive at least 4 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------- | --- | --- | ------- | ------- | ------- | --- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ 2 | 1 | 1 | ~~1~~ 2 | ~~1~~ 3 | ~~1~~ 4 | 1 | 1 |
- Student at index 7 and index 8 does not have marks greater than their left neighbour.
Now let us consider the right neighbour.
- Student at index 7 has marks greater than its right neighbour, so it should receive at least 2 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------- | --- | --- | ------- | ------- | ------- | ------- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ 2 | 1 | 1 | ~~1~~ 2 | ~~1~~ 3 | ~~1~~ 4 | ~~1~~ 2 | 1 |
- Student at index 6 has marks greater than its right neighbour, so it should receive at least 3 candies but it has 4 candies already which is greater than its right neighbour candies, so it is fine.
- Student at index 5, 4 and 3 do not have marks greater than their right neighbour.
- Student at index 2 has marks greater than its right neighbour. So it receives at least 2 candies.
|index|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|-|
|marks|1|6|3|1|10|12|20|5|2|
|candy|1|~~1~~ 2|~~1~~ 2|1|~~1~~ 2|~~1~~ 3|~~1~~ 4|~~1~~ 2|1|
- Student at index 1 has marks greater than its right neighbour. So it receives at least 3 candies.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:| --- | ------------- | ------- | --- | ------- | ------- | ------- | ------- | --- |
| marks | 1 | 6 | 3 | 1 | 10 | 12 | 20 | 5 | 2 |
| candy | 1 | ~~1~~ ~~2~~ 3 | ~~1~~ 2 | 1 | ~~1~~ 2 | ~~1~~ 3 | ~~1~~ 4 | ~~1~~ 2 | 1 |
- Student at index 0 does not have marks greater than its right neighbour.
So a total 19 candies are required.
**Output:** 19
---
### Candy Distribution - Solution
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Step 1:** Assign 1 candy to all the students.
**Step 2:** For all the values of i, consider its left neighbour, if(A[i] > A[i - 1]) then C[i] > C[i - 1], means candy of ith index should be greater than (i-1)th index candy, so we will follow the greedy approach as we want to distribute a minimum number of candies, so we do `C[i] = C[i - 1] + 1`
```cpp
if(A[i] > A[i - 1]){
C[i] = C[i - 1] + 1
}
```
**Step 3:** For all the values of i, consider its right neighbour, if(A[i] > A[i+1]) then C[i] > C[i + 1], means candy of ith index should be greater than (i+1)th index candy, so first we check it has candies greater than his right neighbour or not if not then we will follow the greedy approach as we want to distribute a minimum number of candies, then we do `C[i] = C[i + 1] + 1`
```cpp
if(A[i] > A[i + 1]){
if(C[i] < C[i + 1] + 1)
C[i] = C[i + 1] + 1
}
```
#### PsuedoCode
```cpp
int C[N];
for all i, C[i] = 1
for (i = 1; i < N; i++) {
if (arr[i] > arr[i - 1]) {
C[i] = C[i - 1] + 1
}
}
for (i = N - 2; i >= 0; i--) {
if (arr[i] > arr[i + 1] && C[i] < C[i + 1] + 1) {
C[i] = C[i + 1] + 1
}
}
ans = sum of all values in C[]
```
#### Complexity
- **Time Complexity:** O(N)
- **Space Complexity:** O(N)
---
### Problem 3 Maximum jobs
Given N jobs with their start and end times. Find the maximum number of jobs that can be completed if only one job can be done at a time.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/036/original/upload_0ca0b899d1ddb61495488b3c3c3f37e9.png?1697563365" width=700/>
**Answer:** 5
We will select the jobs that are not overlapping:
- We select job `9 am - 11 am`, then we can not select `10 am - 1 pm` and `10 am - 2 pm`
- Then we select jobs `3 pm - 4 pm` and `4 pm - 6 pm`
- Then we select job `4 pm - 8 pm` and `8 pm - 10 pm` but we do not select job `7 pm - 9 pm`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/038/original/upload_601b84e96b4b18fa869cab47f002fead.png?1697563818" width=700/>
#### Approach
We have to select the job in such a way that the start time of a currently selected job is greater than or equal to the end time of the previous job.
`S[i] >= E[i - 1]`
---
### Question
What is the maximum number of jobs one person can do if only one job at a time is allowed, the start times and end times of jobs are:
S = [1, 5, 8, 7, 12, 13]
E = [2, 10, 10, 11, 20, 19]
**Choices**
- [ ] 2
- [x] 3
- [ ] 4
- [ ] 5
**Explanation**
S = [1, 5, 8, 7, 12, 13]
E = [2, 10, 10, 11, 20, 19]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/039/original/upload_ecd9a7d701d40cce82d3e88b79cc40e6.png?1697563907" width=700/>
We will pick jobs `1 - 2`, `5 - 10` and `12 - 20`. So we can pick total three jobs.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/040/original/upload_58bf0a3865d6741323e81c8af091a536.png?1697563951" width=700/>
---
### Maximum jobs - Solution
The first idea towards a solution is to first pick a job with minimum duration.
#### Idea 1 - Greedy based on duration
Pick the job in the ascending order of the minimum duration. Let us take an example:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/041/original/upload_a804adfecfd43aca2a0261f335c13a88.png?1697564132" width=400/>
In this case, if we select the minimum duration job first, then we will select the job `10 - 13`, then we can not select any other job because both overlap with it.
But if we have not selected `10 - 13`, then we can select both other jobs, which means we can select two jobs.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/042/original/upload_72b4c9c6b1f57b6c8806cdcd4db2a54e.png?1697564162" width=400/>
So selecting a job in the ascending order of the duration will not always give us the maximum number of jobs.
#### Idea 2 - Greedy based on start time
Pick the job in the ascending order of the start time. Let us take an example:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/044/original/upload_f35dc9fc9e42b4db0fb130a21d908250.png?1697564278" width=400/>
In this case, if we select the minimum start time job first, then we will select the job `2 - 20`, then we can not select any other job because both overlap with it.
But if we have not selected `2 - 20`, then we can select both other jobs, which means we can select two jobs.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/045/original/upload_3e89df3f9c13476b61f26929e380291c.png?1697564352" width=400/>
So selecting a job in the ascending order of the start time will not always give us the maximum number of jobs.
#### Observation
We have to take a combination of the above approaches means we have to start early with the minimum duration job.
start early + minimum duration
A combination of both is nothing but simply means ending early.
start early + minimum duration = end early
#### Solution
We have to be greedy based on the end time, so we have to select jobs in the ascending order of end times.
**Example:**
S = [1, 5, 8, 7, 12, 13]
E = [2, 10, 10, 11, 20, 19]
Sort these jobs based on the end time.
S = [1, 5, 8, 7, 13, 12]
E = [2, 10, 10, 11, 19, 20]
Initially ans = 0.
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|:----------:| --- | --- | --- |:---:|:---:|:---:|
| Start time | 1 | 5 | 8 | 7 | 13 | 12 |
| end time | 2 | 10 | 10 | 11 | 19 | 20 |
- We will start with the first job, which has an end time 2 but now the start time of any next job must be greater than the end time of this job.
**So we need to keep track of the last end time.**
Till now lastEndTime = 2
ans+=1, ans = 1
- Now the job at index 1 has start time = 5, lastEndTime <= start time, so can select this job and lastEndTime will be updated to the end time of the current job and the answer is incremented by 1.
lastEndTime = 10
ans+=1, ans = 2
- Now the job at index 2 has start time = 8, lastEndTime > start time, so we can not select this job.
- Now the job at index 3 has start time = 7, lastEndTime > start time, so we can not select this job.
- Now the job at index 4 has start time = 13, lastEndTime <= start time, so can select this job and lastEndTime will be updated to the end time of the current job and the answer is incremented by 1.
lastEndTime = 19
ans+=1, ans = 3
- Now the job at index 5 has start time = 20, lastEndTime > start time, so we can not select this job.
**Answer:** 3
#### PseudoCode
```cpp
1. Sort on the basis of end-time
2. ans = 1, lastEndTime = E[0]
for( i = 1 ; i < N ; i++){
if(S[i] >= lastEndTime){
ans++;
lastEndTime = E[i];
}
}
3. return ans;
```
#### Complexity
- **Time Complexity:** O(NlogN)
- **Space Complexity:** O(N)

View File

@@ -0,0 +1,561 @@
# Hashing 1: Introduction
---
## HashMap
Let's take an example:-
* Imagine we have a hotel called Reddison, which has 5 rooms.
* How can we maintain information on the status of rooms provided the hotel is old and hasn't adapted to technology yet?
Solution: The hotel may maintain a manual register for five rooms like:-
| Room no | occupied |
|:-------:|:--------:|
| 1 | Yes |
| 2 | No |
| 3 | Yes |
| 4 | No |
| 5 | No |
* After a few years, the hotel became a success, and the rooms increased to 1000.
* Provided the hotel decided to adapt to technology, what is the programmatically most straightforward approach to maintain the status of rooms?
* An array can be maintained where the index can denote the room number.
* If there are N rooms, we'll create an array of size + 1 where true denotes that room is occupied, and false denotes unoccupied.
* Pandemic hit, due to which footfall reduced significantly. Owner visits Numerologist who asks them to change room numbers to some random lucky numbers from [1-10<sup>9</sup>]. How can we maintain the status of the rooms now?
* Maintain boolean array of length 10<sup>9</sup> + 1 `bool arr[10^9 + 1]`.
* **ISSUE:** Status can be checked in O(1), but just for 1000 rooms, we require an array of size 10<sup>9</sup>.
* **Solution:** HashMaps
* HashMap is a data structure that stores <key, value> pair.
| Key | value |
|:------:|:--------:|
| 100003 | occupied |
| 3 | occupied |
| 10007 | occupied |
* **In HashMap, T.C of search is O(1) time and S.C is O(N)**
* Key must be unique
* Value can be anything
* **Note:** We'll discuss the internal working of Map in Advanced classes.
**In hashmap approach we can search in O(1) time and can have a space complexity of O(N)**
Let's see some questions based on Hashmap.
---
### Question
Which of the following HashMap will you use to store the population of every country?
**Choices**
- [ ] HashMap<String, Float>
- [ ] HashMap<String, Double>
- [ ] HashMap<String, String>
- [x] HashMap<String, Long>
* Key must be unique in Hashmap, so for that reason :
* We use the country name as the key.
* Since the country name is a `string`, the key would be of type `string`.
* In this case, value is a population that can be stored in `int` or `long` datatype.
* Solution:-
`hashmap<String,long> populationByCountry`.
---
### Question
Which of the following HashMap will you use to store the no of states of every country?
**Choices**
- [ ] HashMap<String, Float>
- [ ] HashMap<String, Double>
- [x] HashMap<String, int>
- [ ] HashMap<String, String>
* Key must be unique in Hashmap, so for that reason :
* We use the country name as the key.
* Since the country name is a `string`, the key would be of type `string`.
* We know that value can be anything. In this case :
* Value is the number of states stored in `int` or `long` datatype.
* Solution:-
`hashmap<String,int> numberOfStatesByCountry`
---
### Question
Which of the following HashMap will you use to store the name of all states of every country?
**Choices**
- [ ] HashMap<String, List < Float > >
- [x] HashMap<String, List < String > >
- [ ] HashMap<String, String>
- [ ] HashMap<String, Long>
* Key must be unique in Hashmap, so for that reason :
* We use the country name as the key.
* Since the country name is a `string`, the key would be of type `string`.
* Value can be anything. In this case:
* Value is the name of states.
* To store them, we would require a list of strings, i.e., `vector<string>` in C++ or `ArrayList<Sting>` in Java, etc., to store the name of states.
* Solution:-
`hashmap<String,list<String>> nameOfStatesByCountry`
---
### Question
Which of the following HashMap will you use to store the population of each state in every country?
**Choices**
- [ ] HashMap<String, Int>
- [ ] HashMap<String, List < Int > >
- [x] HashMap<String,HM < String , Int > >
- [ ] HashMap<String, Long>
* Key must be unique in Hashmap, so for that reason :
* We use the country name as the key.
* Since the country name is a `string`, the key would be of type `string`.
* Value can be anything. In this case :
* We need to store the name of states with its population.
* We will create another hashmap with the state name as key and population as value.
* Solution:-
`hashmap<String,hashmap<String,Long>> populationOfStatesByCountry`
We can observe that:-
* **Value can be anything.**
* **Key can only be a primitive datatype.**
---
## HashSet
Sometimes we only want to store keys and do not want to associate any values with them, in such a case; we use HashSet.
`Hashset<Key Type>`
* **Key must be unique**
* **Like HashMap, we can search in O(1) time in Set**
---
### HashMap and HashSet Functionalities
### HashMap
* **INSERT(Key,Value):** new key-value pair is inserted. If the key already exists, it does no change.
* **SIZE:** returns the number of keys.
* **DELETE(Key):** delete the key-value pair for given key.
* **UPDATE(Key,Value):** previous value associated with the key is **overridden** by the new value.
* **SEARCH(Key):** searches for the specified key.
### HashSet
* **INSERT(Key):** inserts a new key. If key already exists, it does no change.
* **SIZE:** returns number of keys.
* **DELETE(Key):** deletes the given key.
* **SEARCH(Key):** searches for the specified key.
**Time Complexity** of **all the operations** in both Hashmap and Hashset is **O(1)**.
Therefore, if we insert N key-value pairs in HashMap, then time complexity would be O(N) and space complexity would be O(N).
### Hashing Library Names in Different Languages
| | Java | C++ | Python | Js | C# |
|:-------:|:-------:|:-------------:|:----------:|:---:|:----------:|
| Hashmap | Hashmap | unordered_map | dictionary | map | dictionary |
| Hashset | Hashset | unordered_set | set | set | Hashset |
---
### Problem 1 Frequency of given elements
**Problem Statement**
Given N elements and Q queries, find the frequency of the elements provided in a query.
**Example**
N = 10
| 2 | 6 | 3 | 8 | 2 | 8 | 2 | 3 | 8 | 10 | 6 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
Q = 4
| 2 | 8 | 3 | 5 |
|:---:|:---:|:---:|:---:|
#### Solution
| Element | Frequency |
|:-------:|:---------:|
| 2 | 3 |
| 8 | 3 |
| 3 | 2 |
| 5 | 0 |
#### Idea 1
* For each query, find the frequency of the element in the Array.
* TC - **O(Q*N)** and SC - **O(1)**.
>How can we improve TC?
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* First, search for the element in the Hashmap.
* If the element does not exist, then insert the element as key and value as 1.
* If an element already exists, then increase its value by one.
#### Pseudeocode
```cpp
Function frequencyQuery(Q[], A[])
{
Hashmap<int,int> mp;
q = Q.length
n = A.length
for(i = 0 ; i < n ; i ++ )
{
if(mp.Search(A[i]) == true)
{
mp[Array[i]] ++
}
else{
mp.Insert(A[i],1)
}
}
for(i = 0 ; i < q; i ++ )
{
if(mp.Search(Q[i]) == true)
{
print(mp[Q[i]])
}
else{
print("0")
}
}
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Problem 2 First non repeating element
**Problem Statement**
Given N elements, find the first non-repeating element.
**Example**
Input 1:
```
N = 6
```
| 1 | 2 | 3 | 1 | 2 | 5 |
|:---:|:---:|:---:|:---:|:---:|:---:|
Output1 :
```plaintext
ans = 3
```
| 1 | 2 | 3 | 1 | 2 | 5 |
|:---:|:---:|:---:|:---:|:---:|:---:|
Input 2:
```
N = 8
```
| 4 | 3 | 3 | 2 | 5 | 6 | 4 | 5 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
Output 2:
```plaintext
ans = 2
```
Input 3:
```
N = 7
```
| 2 | 6 | 8 | 4 | 7 | 2 | 9 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
Output 3:
```plaintext
ans = 6
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution
**Idea 1**
* Use Hashmap to store the frequency of each element. Store <**key**:element, **value**:frequency>.
* Iterate over the Hashmap and find the element with frequency 1.
**Flaw in Idea 1**
* When we store in Hashmap, the order of elements is lost; therefore, we cannot decide if the element with frequency 1 is first non-repeating in the order described in the Array.
**Idea 2**
* Use Hashmap to store the frequency of each element. Store `<key:element, value:frequency>`.
* Instead of Hashmap, iterate over the Array from the start. If some element has a frequency equal to one, then return that element as answer.
#### Pseudeocode
```cpp
Function firstNonRepeating(A[]) {
Hashmap < int, int > mp;
n = A.length
for (i = 0; i < n; i++) {
if (mp.Search(A[i]) == true) {
mp[A[i]]++
} else {
mp.Insert(A[i], 1)
}
}
for (i = 0; i < n; i++) {
if (mp[A[i]] == 1) {
return A[i]
}
}
return -1
}
```
Time Complexity : **O(N)**
Space Complexity : **O(N)**
---
### Problem 3 Count of Distinct Elements
**Problem Statement**
Given an array of N elements, find the count of distinct elements.
**Example**
**Input:**
N = 5
| 3 | 5 | 6 | 5 | 4 |
|:---:|:---:|:---:|:---:|:---:|
**Output:**
```plaintext
ans = 4
```
**Explanation:** We have to return different elements present. If some element repeats, we will count it only once.
**Input:**
N = 3
| 3 | 3 | 3 |
|:---:|:---:|:---:|
**Output:**
```plaintext
ans = 1
```
**Input:**
N = 5
| 1 | 1 | 1 | 2 | 2 |
|:---:|:---:|:---:|:---:|:---:|
**Output:**
```plaintext
ans = 2
```
**Solution**
* Insert element in Hashset and return the size of HashSet.
> In Hashset, if a single key is inserted multiple times, still, its occurrence remains one.
#### Pseudeocode
```cpp
Function distinctCount(Array[]) {
hashset < int > set;
for (i = 0; i < Array.length; i++) {
set.insert(Array[i])
}
return set.size
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Problem 4 Subarray sum 0
**Problem Statement**
Given an array of N elements, check if there exists a subarray with a sum equal to 0.
Example
**Input:**
N = 10
| 2 | 2 | 1 | -3 | 4 | 3 | 1 | -2 | -3 | 2 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
**Output:**
if we add elements from index 1 to 3, we get 0; therefore, the answer is **true**.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Solution
* Traverse for each subarray check if sum == 0.
* Brute Force: Create all Subarrays, Time complexity: **O(n<sup>3</sup>)**.
* We can optimize further by using **Prefix Sum** or **Carry Forward** method and can do it in Time Complexity: **O(n<sup>2</sup>)**.
* How can we further optimize it?
#### Observations
* Since we have to find sum of a subarrays(range), we shall think towards **Prefix Sum**.
Initial Array: -
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| 2 | 2 | 1 | -3 | 4 | 3 | 1 | -2 | -3 | 2 |
Prefix sum array: -
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| 2 | 4 | 5 | 2 | 6 | 9 | 10 | 8 | 5 | 7 |
We need a subarray with **sum(i to j) = 0**
Using Prefix Sum Array,
**PrefixSum[j] - PrefixSum[i-1] = 0
PrefixSum[j] = PrefixSum[i-1]**
It implies, if there exist duplicate values in Prefix Sum Array, then the sum of a subarray is 0.
Example,
```cpp
PrefixSum[2] = 5
PrefixSum[8] = 5
sum of elements in intial array from index 3 to 8 = 0
```
**Summary**
* If numbers are repeating in Prefix Sum Array, then there exists a subarray with sum 0.
* Also, if the Prefix Sum Array element is 0, then there exists a subarray with sum 0.
* Example:
* A[] = {2, -1, 3, 5}
* PrefixSum[] = {2, -1, 0, 5}
* Here, 0 in PrefixSum Array implies that there exist a subarray with sum 0 starting at index 0.
#### Approach
* Calculate prefix sum array.
* Traverse over elements of prefix sum array.
* If the element is equal to 0, return true.
* Else, insert it to HashSet.
* If the size of the prefix array is not equal to the size of the hash set, return true.
* Else return false.
#### Pseudeocode
```cpp
// 1. todo calculate prefix sum array
// 2.
Function checkSubArraySumZero(PrefixSumArray[]) {
Hashset < int > s
for (i = 0; i < PrefixSumArray.length; i++) {
if (PrefixSumArray[i] == 0) {
return true
}
s.insert(PrefixSumArray[i])
}
if (s.size != PrefixSumArray.size)
return true
return false
}
```
Time Complexity : **O(N)**
Space Complexity : **O(N)**
---
### HINT for Count Subarrays having sum 0
Given an array A of N integers.
Find the count of the subarrays in the array which sums to zero. Since the answer can be very large, return the remainder on dividing the result with 109+7
**Input 1**
A = [1, -1, -2, 2]
**Output 1**
3
Explanation
The subarrays with zero sum are [1, -1], [-2, 2] and [1, -1, -2, 2].
**Input 2**
A = [-1, 2, -1]
**Output 2**
1
Explanation
The subarray with zero sum is [-1, 2, -1].

View File

@@ -0,0 +1,490 @@
# Hashing Problems
---
## Problem 1 Pair Sum K
Given arr[N] and K, check if there exists a pair(i, j) such that,
```kotlin
arr[i] + arr[j] == K && i != j
```
**Example**
Let's say we have an array of 9 elements and K, where K is our target sum,
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Array | 8 | 9 | 1 | -2 | 4 | 5 | 11 | -6 | 4 |
K = 6: arr[2] + arr[5] : such a pair exists
K = 22: does not exist
K = 8: arr[4] + arr[8]: such a pair exists
Hence if K = `6` or `8` the answer is `true`, for K = `22`, it will be `false`.
---
### Question
Check if there exists a pair(i, j) such that, arr[i] + arr[j] == K && i != j in the given array A = [3, 5, 1, 2, 1, 2] and K = 7.
**Choices**
- [x] true
- [ ] false
### Question
Check if there exists a pair(i, j) such that, arr[i] + arr[j] == K && i != j in the given array A = [3, 5, 1, 2, 1, 2] and K = 10.
**Choices**
- [ ] true
- [x] false
---
:::warning
Please take some time to think about the bruteforce approach on your own before reading further.....
:::
### Problem 1 Brute Force
#### Idea 1:
Iterate on all pairs(i, j) check if their sum == k
**Example 2**:
Take another example of arr[5]
| Index | 0 | 1 | 2 | 3 | 4 |
|:------:|:---:|:---:|:---:|:---:|:---:|
| arr[5] | 3 | 2 | 6 | 8 | 4 |
We can have following cases of pairs from an array of size 5
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/583/original/upload_3a54ba208d44d76c7063510180eb6da1.png?1695221986" alt= “” width ="500" height="400">
* Here, since we are not allowed to consider pairs where i == j these diagonal elements (marked in red) will not be considered.
* Now, as you can see the upper (blue) and lower (yellow) triangles represent the same pairs (order of pair doesn't matter here) our program would work with either one of these triangular parts.
*Now, considering upper triangle -*
#### Observation:
| i | j loops from [i...(N - 1)] |
|:---:|:------------------------:|
| 0 | [0..N-1] |
| 1 | [1..N-1] |
| 2 | [2..N-1] |
| 3 | [3..N-1] |
| 4 | - |
Here for every index of i, j loops from i to N - 1
For an `arr[i]`, the target will be `K-arr[i]`
#### Pseudocode:
```kotlin
boolean checkPair(int arr[], int K) {
int N = arr.length
for (int i = 0; i < N; i++) {
//target: K-arr[i]
for (int j = i; j < N; j++) {
if (arr[i] == K - arr[i]) {
return true;
}
}
}
return false;
}
```
#### Complexity
**Time Complexity:** O(N^2)
**Space Complexity:** O(1)
---
### Problem 1 Optimization with HashSet(Doesn't Work)
* We can insert all elements in the set initially.
* Now, iterate over every arr[i] and check if K-arr[i] is present in the set. If yes, return tue, else false.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/050/original/Screenshot_2023-10-27_at_4.11.32_PM.png?1698403308" alt= “” width ="600" height="200">
---
**ISSUE: (Edge Case)**
* For even K value, say arr[i] is K/2 and only one occurrence of it is present.
* Eg: A[] = {8, 9, 2, -1, 4, 5, 11, -6, 4}; K=4, we will end up considering 2(present at index 2) two times.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/051/original/Screenshot_2023-10-27_at_4.11.39_PM.png?1698403359" alt= “” width ="600" height="200">
We can see the above logic isn't working
### Resolution:
We need not insert all elements into set at once. Rather only insert from [0, i - 1].
---
### Problem 1 Optimization with HashSet(Works)
At ith index: Hashset should contain all the elements:[0...i - 1]
Let's take an example,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/585/original/upload_a4b1e5d20d55238fbec1e78884238f96.png?1695222089" alt= “” width ="600" height="200">
* Initially set is empty.
* For every element at ith index, search for target (arr[i] - K) in set.
* If found, it means it must have been previously inserted. If not, we'll insert arr[i], because in future if we'll find a pair, we'll be able to get the current element.
Let's take another example,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/586/original/upload_68f2bd2ab73bc0bb5384b5b758375222.png?1695222113" alt= “” width ="600" height="200">
#### Pseudocode:
```kotlin
boolean targetSum(int arr[], int K) {
int N = arr.length;
Hashset < int > bs;
for (int i = 0; i < N; i++) {
//target = K - arr[i]
if (bs.contains(K - arr[i])) {
return true;
} else {
bs.add(arr[i]);
}
}
return false;
}
```
---
### Question
Count pairs(i, j) such that, arr[i] + arr[j] == K && i != j in the given array.
A = [3, 5, 1, 2, 1, 2] and K = 3.
**Choices**
- [ ] 1
- [ ] 2
- [ ] 3
- [x] 4
In the given array A = [3, 5, 1, 2, 1, 2], pairs with sum = 3 are:
| Pairs |
| ------ |
| {2, 3} |
| {2, 5} |
| {3, 4} |
---
### Problem 2 Count no. of pairs with sum K
Given an `arr[n]`, count number of pairs such that
```kotlin
arr[i] + arr[j] = K && i != j
```
**Example**
Provided we have an arr[8] and K = 10, we have
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|:------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| arr[8] | 2 | 5 | 2 | 5 | 8 | 5 | 2 | 8 |
**Pairs:**
| Pairs: 9 |
|:--------:|
| {0, 4} |
| {0, 7} |
| {1, 5} |
| {1, 3} |
| {2, 4} |
| {2, 7} |
| {3, 5} |
| {4, 6} |
| {6, 7} |
Here (i, j) and (j, i) considered as same.
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
### Optimised Approach(Same as in previous question)
* Similar to our previous problem, we'll be searching for our target.
* This time we also need to consider the frequency of how many times a particular element appeared, so we shall be maintianing a map.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/587/original/upload_9aa1cbc2130f91fa21781e92fe645f64.png?1695222159" alt= “” width ="500" height="200">
### Pseudocode:
```kotlin
int countTargetSum(int arr[], int K) {
int N = arr.length;
Hashmap < int, int > hm;
int c = 0;
for (int i = 0; i < n; i++) {
//target = K-arr[i]
if (hm.contains(K - arr[i])) {
c = c + hm[K - arr[i]] //freq of target = pairs
}
//insert arr[i]
if (hm.contains(arr[i])) {
hm[arr[i]]++;
} else {
hm.put(arr[i], 1);
}
}
return c;
}
```
### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Problem 3 Subarray with Sum K
Given an array arr[n] check if there exists a subarray with sum = K
### Example:
We have the following array
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|:------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| arr[7] | 2 | 3 | 9 | -4 | 1 | 5 | 6 | 2 | 5 |
Possible subarrays for the following values of K are,
* k = 11: {2 3 9 -4 1}, {5, 6}
* k = 10: {2 3 9 -4}
* k = 15: {-4, 1, 5, 6, 2, 5}
---
### Question
Check if there exist a subarray with sum = 110 in the given array?
A = [ 5, 10, 20, 100, 105 ]
**Choices**
- [x] No
- [ ] YES
---
### Approach
To get subarray sum for any subarray in constant time, we can create a prefix sum array.
Now, a subarray sum `PF[i] - PF[j]` should be equal to `K`
OR
**a - b = K**
We can fix `a` and get the corresponding pair for it, given by `a - K`
> We can create a HashSet at the time of traversal simultaneously
> Here, instead of creating prefix sum initially, we are calculating it while iterating through the array.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/589/original/upload_6ecbb00a34003fd352ffa8d7a52cd79c.png?1695222337" alt= “” width ="600" height="200">
**Edge case:**
If subarray from index 0 has sum = K.
Say, K = 10
a = 10, b = 10-10=0, now 0 won't be present in the array.
Please take below example:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/590/original/upload_0ceb31b4f16f07cfda3dc4f4283b8135.png?1695222358" alt= “” width ="600" height="200">
**To resolve this, take 0 in the set initially.**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/591/original/upload_0efad47d63c86de9d905ecc34a17410f.png?1695222380" alt= “” width ="600" height="200">
#### Pseudocode:
```kotlin
boolean targetSubarray(int arr[], int K) {
int N = arr.length;
long a = 0;
//cumulative sum, long -> to avoid overflow
HashSet < long > hs;
hs.add(0);
for (int i = 0; i < N; i++) {
a = a + arr[i];
//cumulative sum = target = a - k
if (hs.contains(a - K)) {
//subarray exists
return true;
} else {
hs.add(a);
}
}
return false;
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Problem 4 Distinct elements in every window of size K
Given an array of integers and a number, K. Find the count of distinct elements in every window of size K in the array.
**Example**
```java
// Input:
Array = [1, 2, 1, 3, 4, 2, 3]
K = 4
// Output:
[3, 4, 4, 3]
```
- In the first window `[1, 2, 1, 3]`, there are 3 distinct elements: 1, 2, and 3.
- In the second window `[2, 1, 3, 4]`, there are 4 distinct elements: 2, 1, 3, and 4.
- In the third window `[1, 3, 4, 2]`, there are again 4 distinct elements: 1, 3, 4, and 2.
- In the fourth window `[3, 4, 2, 3]`, there are 3 distinct elements: 3, 4, and 2.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach - Using HashSet
- The code iterates through each possible window of size K in the given array.
- For each window, a temporary HashSet (`distinctSet`) is created to store the distinct elements within that window.
- Within the inner loop, the code adds each element of the window to the HashSet.
- After processing the entire window, the size of the HashSet is calculated using `distinctSet.size()`, which represents the count of distinct elements.
- The count is then added to the result list.
- This process is repeated for all possible windows in the array.
- The result list contains the count of distinct elements in each window
#### Pseudocode
```java
//Pseudo code for 'countDistinctElements' function
function countDistinctElements(arr, k):
result = empty list
for i = 0 to length of arr - k:
distinctSet = empty set
for j = i to i + k - 1:
add arr[j] to distinctSet
add size of distinctSet to result
return result
```
#### Complexity
**Time Complexity:** `O((N-K+1) * K)`
Considering the values of `K` as N/2, 1, and N.
**When K = N/2:**
If `K` is about half of `N`, then the expression simplifies to `O((N/2 + 1) * N/2)`, which further simplifies to `O((N^2 + N) / 4)`. In this case, the primary factor is `N^2`, leading to a time complexity of approximately `O(N^2)`.
**When K = 1:**
When `K` is set to 1, the expression becomes `O((N - 1 + 1) * 1)`, which straightforwardly simplifies to `O(N)`. It's important to note that this doesn't align with the original statement of the time complexity being `O(N^2)`.
**When K = N:**
If `K` is equal to `N`, then the expression becomes `O((N - N + 1) * N)`, which further simplifies to `O(N^2)`.
**Space Complexity:** O(K)
---
### Problem 4 Sliding Window - Map
Sliding Window suggests to insert all elements of the first window in the set. Now slide the window, throw the prev element out and insert new adjacent element in the set.
But we can't use Set here, since it is possible that the element just thrown out may be present in the current window.
We will also need to maintain the frequency of elements, hence we will use Hashmap.
- Maintain a HashMap to track the frequency of elements within the current subarray.
- Initially, the algorithm populates the HashMap with the elements of the first subarray, counting distinct elements.
- Then, as the window slides one step at a time:
- The algorithm updates the HashMap by updating frequency of the element leaving the window and increasing frequency of the new element entering the window.
- The distinct element count for each subarray is determined by the size of the HashMap.
#### Pseudocode
```java
void subfreq(int ar[], int k) {
int N = ar.length;
HashMap < int, int > hm;
// Step 1: Insert 1st subarray [0, k-1]
for (int i = 0; i < k; i++) {
//Increase frequecy by 1
if (hm.contains(ar[i])) {
int val = hm.get(ar[i]);
hm.put(ar[i], val + 1);
} else {
hm.put(ar[i], 1);
}
print(hm.size());
}
//step 2: Iterate all other subarrays
int s = 1, e = k;
while (e < N) {
//Remove ar[s-1]
int val = hm[ar[s - 1]];
hm[ar[s - 1]]--;
if (hm.get[ar[s - 1]] == 0) {
hm.remove(ar[s - 1]);
}
//add ar[e]
if (hm.contains(ar[e])) {
//Inc freq by 1
int val = hm[ar[e]];
hm[ar[e]]++;
} else {
hm.put(ar[e], 1);
}
print(hm.size());
s++
}
}
```
#### Complexity
**Time Complexity**: `O(n)`
**Space Complexity**: `O(n)`

View File

@@ -0,0 +1,459 @@
# Hashmap Implementation
---
## Check if given element exists in Q queries
Given an array of size N and Q queries. In each query, an element is given. We have to check whether that element exists or not in the given array.
**Example**
A [ ] = {`2, 4, 11, 15 , 6, 8, 14, 9`}
`4 Queries`
`K = 4` (return true)
`K = 10` (return false)
`K = 17` (return false)
`K = 14` (return true)
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force Approach
For every query, loop through the given array to check the presence.
Time Complexity - **O(N * Q)**
Space Complexity - **O(1)**
#### Observation
We can create an array to mark the presence of an element against that particular index.
A [ ] = {`2, 4, 11, 15 , 6, 8, 14, 9`}
For example we can mark presence of
2 at index 2
4 at index 4 and so on....
To execute that, we'll need to have indices till 15(max of Array).
The array size needed is 16.
Let's call that array as - DAT (Direct Access Table)
int dat[16] = {0}; //initally assuming an element is not present
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Let's mark the presence.
```cpp
for(int i = 0; i < N; i++) {
dat[A[i]] = 1;
}
```
Below is how that array looks like -
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
| 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 1 |
#### Advantage of using DAT
1. Time Complexity of Insertion - `O(1)`
2. Time Complexity of Deletion - `O(1)`
3. Time Complexity of Search - `O(1)`
#### Issues with such a representation
**1. Wastage of Space**
* Say array is `A[] = {23, 60, 37, 90}`; now just to store presence of 4 elements, we'll have to construct an array of `size 91`.
**2. Inability to create big Arrays**
* If values in array are as big as $10^{15}$, then we will not be able to create this big array. At max array size possible is 10^6^(around)
**3. Storing values other than positive Integers**
* We'll have to make some adjustments to store negative numbers or characters. (It'll be possible but needs some work-around)
---
### Overcome Issues while retaining Advantages
Let's say we have restriction of creating only array of size 10.
Given Array -
A [ ] = {`21, 42, 37, 45 , 99, 30`}
**How can we do so ?**
In array of size 10, we'll have indices from 0 to 9. How can we map all the values within this range ?
**Basically, we can take a mod with 10.**
21 % 10 = 1 (presence of 21 can be marked at index 1)
42 % 10 = 2 (presence of 42 can be marked at index 2)
37 % 10 = 7 (presence of 37 can be marked at index 7)
45 % 10 = 5 (presence of 45 can be marked at index 5)
99 % 10 = 9 (presence of 99 can be marked at index 9)
30 % 10 = 0 (presence of 30 can be marked at index 0)
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
| 30 | 21 | 42 | 0 | 0 | 45 | 0 | 37 | 0 | 99 |
#### What Have We Done ?
* We have basically done Hashing. Hashing is a process where we pass our data through the Hash Funtion which gives us the hash value(index) to map our data to.
* In this case, the hash function used is **MOD**. This is the simplest hash function. Usually, more complex hash functions are used.
* The DAT that we created is known as **Hash Table** in terms of Hashing.
#### Issue with Hashing ?
**COLLISION!**
Say given array is as follows -
A [ ] = {21, 42, 37, 45, 77, 99, 31}
Here, 21 & 31 will map to the same index => 1
37 & 77 map to same index => 7
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/854/original/Screenshot_2023-10-24_at_2.53.50_PM.png?1698139444)
**Can we completely avoid collision ?**
`Not Really!`
No matter how good a hash function is, we can't avoid collision!
**Why ?**
We are trying to map big values to a smaller range, collisions are bound to happen.
Moreover, this can be explained using `Pigeon Hole Principle!`
**Example -**
Say we have 11 pigeons and we have only 8 holes to keep them. Now, provided holes are less, atleast 2 pigeons need to fit in a single hole.
But, we can find some resolutions to collision.
---
### Collision Resolution Techniques
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/865/original/Screenshot_2023-10-24_at_7.11.17_PM.png?1698154890)
>From Interview Perspective, Open Hashing is Important hence, we'll dive into that.
---
### Chaining
Let's take the above problem where collision happened!
A [ ] = {`21, 42, 37, 45, 77, 99, 31`}
Here, 21 & 31 will map to the same index => 1
37 & 77 map to same index => 7
**How can we resolve Collision here?**
We can somehow store both 21 & 31 at the same index.
Basically we can have a linked list at every index.
i.e, Array of Linked List
Every index shall have head node of Linked List.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/867/original/IMG_A28158A44160-1.jpeg?1698155988)
**The above method is known as Chaining.**
* **Chaining** is a technique used in data structures, particularly hash tables, to resolve collisions. When multiple items hash to the same index, chaining stores them in a linked list or another data structure at that index.
**What will be the Time Complexity of Insertion ?**
* First we will pass the given element to Hash Function, which will return an index. Now, we will simply add that element to the Linked List at that index.
* If we insert at **tail** => `O(N)`
* If we insert at **head** => `O(1)`
Since order of Insertion doesn't matter to us, so we can **simply insert at head**.
**What will be the Time Complexity of Deletion and Searching ?**
* Time Complexity on average is always less than $\lambda$. $\lambda$ is known as lamda.
* Time Complexity in worst case is still O(N)
---
### What is lamda
There is a lamba($\lambda$) function which is nothing but a ratio of (number of elements inserted / size of the array).
**Example:**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/901/original/Screenshot_2023-10-25_at_2.53.39_PM.png?1698225828)
Table size(Array size) = 8
Inserted Elements = 6
$\lambda$ = $\frac{6}{8}$ = 0.75
Let's assume the predefined threshold is 0.7. The load factor is exceeding this value, so we will need to rehash the table.
**Rehashing:**
* Create a new hash table with double the size of the original hash table. In this case, the new size will be
* 8×2=16
* Redistribute the existing elements to their new positions in the larger hash table using a new hash function.
* The load factor is now recalculated for the new hash table:
*
$\lambda$ = $\frac{6}{16} = 0.375$ (within the threshold of 0.7)
---
### Code Implementation
#### Declaring the HashMap Class
Let's go through the code implementation of a hashmap:
* The HashMap class is defined with generic types `K` and `V` for keys and values.
* The inner class `HMNode` represents a node containing a key-value pair.
* `buckets` is an array of ArrayLists to store key-value pairs.
* `size` keeps track of the number of key-value pairs in the hashmap.
* The `initbuckets()` method initializes the array of buckets with a default size of 4.
```java
import java.util.ArrayList;
class HashMap < K, V > {
private class HMNode {
K key;
V value;
public HMNode(K key, V value) {
this.key = key;
this.value = value;
}
}
private ArrayList < HMNode > [] buckets;
private int size; // number of key-value pairs
public HashMap() {
initbuckets();
size = 0;
}
private void initbuckets() {
buckets = new ArrayList[4];
for (int i = 0; i < 4; i++) {
buckets[i] = new ArrayList < > ();
}
}
```
#### Put Method
* The `put` method adds a key-value pair to the hashmap.
* It calculates the bucket index (`bi`) using the `hash` method and finds the data index within the bucket using `getIndexWithinBucket`.
* If the key is found in the bucket, it updates the value. Otherwise, it inserts a new node.
* After inserting, it checks the load factor (`lambda`) and triggers rehashing if the load factor exceeds 2.0.
```java
public void put(K key, V value) {
int bi = hash(key);
int di = getIndexWithinBucket(key, bi);
if (di != -1) {
// Key found, update the value
buckets[bi].get(di).value = value;
} else {
// Key not found, insert new key-value pair
HMNode newNode = new HMNode(key, value);
buckets[bi].add(newNode);
size++;
// Check for rehashing
double lambda = size * 1.0 / buckets.length;
if (lambda > 2.0) {
rehash();
}
}
}
```
#### Hash Method
* The `hash` method calculates the bucket index using the hash code of the key and takes the modulus to ensure it stays within the array size.
```java
private int hash(K key) {
int hc = key.hashCode();
int bi = Math.abs(hc) % buckets.length;
return bi;
}
```
#### Get Index within Bucket
* The `getIndexWithinBucket` method searches for the data index (`di`) of a key within a specific bucket. It returns -1 if the key is not found
```java
private int getIndexWithinBucket(K key, int bi) {
int di = 0;
for (HMNode node: buckets[bi]) {
if (node.key.equals(key)) {
return di; // Key found
}
di++;
}
return -1; // Key not found
}
```
#### Rehash Method
* The `rehash` method is called when the load factor exceeds 2.0.
* It creates a new array of buckets, initializes the size to 0, and iterates through the old buckets, reinserting each key-value pair into the new array.
*
```java
private void rehash() {
ArrayList < HMNode > [] oldBuckets = buckets;
initbuckets();
size = 0;
for (ArrayList < HMNode > bucket: oldBuckets) {
for (HMNode node: bucket) {
put(node.key, node.value);
}
}
}
```
#### Get Method
* The `get` method retrieves the value associated with a given key. It calculates the bucket index and searches within the bucket to find the key.
```java
public V get(K key) {
int bi = hash(key);
int di = getIndexWithinBucket(key, bi);
if (di != -1) {
return buckets[bi].get(di).value;
} else {
return null;
}
}
```
#### Contains Key Method
* The `containsKey` method checks if a given key exists in the hashmap by calculating the bucket index and checking the data index within the bucket.
```java
public boolean containsKey(K key) {
int bi = hash(key);
int di = getIndexWithinBucket(key, bi);
return di != -1;
}
```
#### Remove Method
* The `remove` method removes a key-value pair from the hashmap. If the key is found, it returns the value; otherwise, it returns null
```java
public V remove(K key) {
int bi = hash(key);
int di = getIndexWithinBucket(key, bi);
if (di != -1) {
// Key found, remove and return value
size--;
return buckets[bi].remove(di).value;
} else {
return null; // Key not found
}
}
```
#### Size Method
The `size` method returns the total number of key-value pairs in the hashmap.
```java
public int size() {
return size;
}
```
#### Key Set Method
* The `keyset` method returns an ArrayList containing all the keys in the hashmap by iterating through the buckets and nodes.
```java
public ArrayList < K > keyset() {
ArrayList < K > keys = new ArrayList < > ();
for (ArrayList < HMNode > bucket: buckets) {
for (HMNode node: bucket) {
keys.add(node.key);
}
}
return keys;
}
}
```
---
### Question
What is the time complexity of the brute-force approach for checking the existence of an element in the array for Q queries?
**Choices**
- [ ] O(N)
- [ ] O(Q)
- [x] O(N * Q)
- [ ] O(1)
---
### Question
What advantage does the Direct Access Table (DAT) provide in terms of time complexity for insertion, deletion, and search operations?
**Choices**
- [x] O(1) for all operations
- [ ] O(N) for all operations
- [ ] O(1) for insertion and deletion, O(N) for search
- [ ] O(N) for insertion and deletion, O(1) for search
---
### Question
What is the purpose of the load factor (lambda) in a hashmap?
**Choices**
- [ ] It represents the number of elements in the hashmap.
- [ ] It is used to calculate the hash code of a key.
- [x] It determines when to trigger rehashing.
- [ ] It controls the size of the hashmap.
---
### Question
What does the rehashing process involve in a hashmap?
**Choices**
- [ ] Reducing the size of the hashmap
- [x] Creating a new hash table with double the size and redistributing elements
- [ ] Deleting all elements from the hashmap
- [ ] Removing collision resolution techniques

View File

@@ -0,0 +1,557 @@
# Advanced DSA: Heaps 1: Introduction
---
## Problem 1 Connecting the ropes
We are given an array that represents the size of different ropes. In a single operation, you can connect two ropes. Cost of connecting two ropes is sum of the length of ropes you are connecting. Find the minimum cost of connecting all the ropes.
**`To illustrate:`**
**Example 1**:
int A[] = {2, 5, 3, 2, 6}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/154/original/Screenshot_2024-01-09_at_11.02.13_AM.png?1704778393" width=500 />
**Example 2**:
**`Initial Ropes: [2, 5, 6, 3]`**
Connect 2 and 5 (Cost = 2 + 5 = 7)
Total Cost: 7
New Ropes: [7, 6, 3]
Next Step: [7, 6, 3]
Connect 7 and 6 (Cost = 7 + 6 = 13)
Total Cost: 7 + 13 = 20
New Ropes: [13, 3]
Final Step: [13, 3]
Connect 13 and 3 (Cost = 13 + 3 = 16)
Total Cost: 20 + 16 = 36
Final Rope: [16]
This is one of the options for finding the cost of connecting all ropes, but we need to find the minimum cost of connecting all the ropes.
#### Observation
Say, we have 3 ropes, **`x < y < z`**
Which 2 ropes should we connect first ?
| Case | 1 | 2 |3|
| --------| -------- | -------- |--|
| Step 1 | x+y | x+z |y+z|
| Step 2 | (x+y) + z | (x+z) + y |(y+z) + x|
Comparing case 1 and 2, y and z are different, now since y < z, we can say cost of 1 < cost of 2.
Comparing case 2 and 3, x and y are different, now since x < y, we can say cost of 2 < cost of 3.
**`Conclusion:`** Connecting smaller length ropes gives us lesser cost.
#### Process:
**`Initial Setup:`** Start with an array of rope lengths, e.g., [2, 2, 3, 5, 6]. First, sort the array.
**`Combining Ropes:`**
- Continuously pick the two smallest ropes.
- Combine these ropes, adding their lengths to find the cost.
- Insert the combined rope back into the array at its correct position in sorted array.
- Repeat until only one rope remains.
We are basically applying **`insertion sort`**.
**`Example Steps:`**
- Combine ropes 2 and 2 (cost = 4). New array: [3, 4, 5, 6]. Total cost: 4.
- Combine ropes 3 and 4 (cost = 7). New array: [5, 6, 7]. Total cost: 11.
- Combine ropes 5 and 6 (cost = 11). New array: [7, 11]. Total cost: 22.
- Combine ropes 7 and 11 (cost = 18). Final rope: 18. Total cost: 40.
#### Complexity
**Time Complexity:** O(N^2^)
**Space Complexity:** O(1)
---
### Question
What is the minimum cost of connecting all the ropes for the array [1, 2, 3, 4]?
**Choices**
- [x] 19
- [ ] 20
- [ ] 10
- [ ] 0
**Explanation**:
**Always pick two of the smallest ropes and combine them.**
After combining the two smallest ropes at every step, we need to sort an array again to get the two minimum-length ropes.
1, 2, 3, 4; cost = 3
3, 3, 4; sort: 3, 3, 4; cost = 6
6, 4; sort: 4, 6; cost = 10
Final Length: 10
Total Cost = (3 + 6 + 10) = 19
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Connecting the ropes optimisation
Heaps efficiently perform the necessary operations:
- Insertion of elements in **`O(log n)`** time.
- Extraction of the minimum element in **`O(log n)`** time.
**`NOTE: We'll understand how we can achive the above complexities, for now assume heap to be a black box solving the above requirements for us in lesser time.`**
Heap returns the min or max value depending upon it is a min heap or max heap.
Say, for above problem, we use a min heap. At every step, it will give us the 2 small length ropes. Please note below steps for solving above problem.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/155/original/Screenshot_2024-01-09_at_11.22.15_AM.png?1704779546" width=700 />
#### Time & Space Complexity
For every operation, we are removing 2 elements and inserting one back, hence it is 3 * log N. For N operations, **`the time complexity will be O(N * log N)`**
**`Space Complexity is O(N)`**
---
## Heap Data Structure
The heap data structure is a binary tree with two special properties.
- First property is based on structure.
- **Complete Binary Tree:** All levels are completely filled. The last level can be the exception but is should also be filled from left to right.
- Second property is based on the order of elements.
- **Heap Order Property:** In the case of max heap, the value of the parent is greater than the value of the children. And in the case of min heap, the value of the parent is less than the value of the children.
**Examples**
**`Example 1:`**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/168/original/1.png?1704790870" width=350/>
- This is the complete binary tree as all the levels are filled and the last level is filled from left to right.
- Heap Order Property is also valid at every point in the tree, as 5 is less than 12 and 20, 12 is less than 25 and 13, 20 is less than 24 and 22, 25 is less than 35 and 34.
- Hence, it is a **min-heap**
**`Example 2:`**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/169/original/2.png?1704790896" width=350/>
- This is the complete binary tree as all the levels are filled and the last level is filled from left to right.
- Heap Order Property is also valid at every point in the tree, as 58 is greater than 39 and 26, 39 is greater than 34 and 12, 26 is greater than 3 and 9, 34 is greater than 16 and 1.
- Hence, it is a **max-heap.**
---
### Array Implementation of Trees(Complete Binary Tree)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/170/original/3.png?1704790911" width=300/>
- We shall store elements in the array in level order wise.
- Such an array representation of tree is only possible if it is a complete binary tree.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/171/original/4.png?1704790924" width=500/>
- Index 0 has its children at index 1 and 2
- Index 1 has its children at index 3 and 4
- Index 2 has its children at index 5 and 6
- Index 3 has its children at index 7 and 8
**`For the particular node stored at the i index, the left child is at (i * 2 + 1 ) and the right child is at (i * 2 + 2 )`**.
**`For any node i, its parent is at (i-1)/2.`**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/172/original/5.png?1704790938" width=300/>
---
### Insertion in min heap
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/173/original/6.png?1704790952" width=400/>
|0|1|2|3|4|5|6|7|
|-|-|-|-|-|-|-|-|
|5|12|20|25|13|24|22|35|
**Example 1**: Insert 10
In an array, if we will insert 10 at index 8, then our array becomes,
|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|
|5|12|20|25|13|24|22|35|10|
And the tree becomes,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/174/original/7.png?1704790966" width=400/>
Now tree satisfies the complete binary tree property but the tree does not satisfy the min-heap property, as here 25 > 10.
In this case, we shall start with the inserted node and compare the parent with the child and keep swapping until the property is satisfied.
Let us assume the node inserted at index `i` and the index of its parent is `pi`.
```cpp
if(arr[pi] > arr[i]) swap
```
> i = 8
pi = (8-1)/2 = 3
Since, (arr[3] > arr[8]) swap
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/175/original/8.png?1704790980" width=400/>
|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|
|5|12|20|10|13|24|22|35|25|
Now again we need to confirm whether the heap order property is satisfied or not by checking with its parent again.
> i = 3
pi = (3-1)/2 = 1
Since, (arr[1] > arr[3]) swap
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/177/original/1.png?1704791315" width=350/>
|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|
|5|10|20|12|13|24|22|35|25|
Now again we need to confirm whether the heap order property is satisfied or not by checking with its parent again.
> i = 1
pi = (3-1)/2 = 0
Since, (arr[0] < arr[1]) no need to swap
STOP
Now this tree satisfies the min-heap order property.
|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|
|5|10|20|12|13|24|22|35|25|
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/178/original/2.png?1704791329" width=350/>
**Example 2**: Insert 3
First insert 3 at index 9.
|0|1|2|3|4|5|6|7|8|9|
|-|-|-|-|-|-|-|-|-|-|
|5|10|20|12|13|24|22|35|25|3|
- Compare index 9 and parent index ((9-1)/2)= 4 value, as arr[4] > arr[9], swap.
- Now again compare index 4 and , parent index((4-1)/2)=1 arr[1]>arr[4], swap again.
- Now again compare index 1 and , parent index((1-1)/2)=0 arr[0]>arr[1], swap again.
- Now zero index does not have any parent so stop.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/180/original/4.png?1704791359" width=300/>
|0|1|2|3|4|5|6|7|8|9|
|-|-|-|-|-|-|-|-|-|-|
|3|5|20|12|10|24|22|35|25|13|
**`NOTE: The maximum swap we can perform for any element to be inserted is equal to the height of the tree.`**
---
### Question
Time Complexity of inserting an element in a heap having n nodes?
**Choices**
- [ ] O(1)
- [x] O(log n)
- [ ] O(sqrt n)
- [ ] O(n)
---
### Inserting in min heap pseudocode
#### Pseudocode
```cpp
heap[];
heap.insert(val); // inserting at last
i = heap.size - 1;
while (i > 0) {
pi = (i - 1) / 2;
if (heap[pi] > heap[i]) {
swap(heap, pi, i);
i = pi;
} else {
break;
}
}
```
#### Complexity
**Time Complexity:** O(height of tree) = O(logN)
---
### Extract Min
**`Min Heap -`**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/205/original/1.png?1704813588" width=250/>
|0|1|2|3|4|5|6|7|8|
|-|-|-|-|-|-|-|-|-|
|2|4|5|11|6|7|8|20|12|
In this tree, we have a minimum element at the root. First we swap the first and last elements, then remove the last index element of an array virtually, i.e. consider your array from index 0 to N-2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/209/original/a.png?1704813720" width=300/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/210/original/b.png?1704813732" width=300/>
But the tree is not satisfying the heap-order property. To regain this heap-order property, first check 12, 4 and 5, the minimum is 4, so swap 12 with 4.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/206/original/2.png?1704813605" width=700/>
- Now check the index 1(12) value, it greater than index 3(11) and index 4(6), so we need to swap this value with the minimum of left and right child i.e. 6.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/207/original/3.png?1704813661" width=700/>
- Now index 4(12) does not have any child, so we will stop here. **`Now the heap-order property is regained.`**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/208/original/4.png?1704813681" width=300/>
**`NOTE to Instructor: Perform extract-min again for more clarity on above tree.`**
#### Pseudocode
```cpp
swap(heap, 0, heap - size() - 1)
heap.remove(heap.size() - 1)
heapify(heap[], 0);
void heapify(heap[], i) {
while (2 i + 1 < N) { //need to handle the edge case when left child is there but not the right child
x = min(heap[i], heap[2 i + 1], heap[2 i + 2])
if (x == heap[i]) {
break
} else if (x == heap[2 i + 1]) {
swap(heap, i, 2 i + 1)
i = 2 i + 1
} else {
swap(heap, i, 2 i + 2)
i = 2 i + 2
}
}
}
```
#### Complexity
**Time Complexity:** O(log N)
---
### Build a heap
We have an array of values, we want to make a heap of it.
**`[5, 13, -2, 11, 27, 31, 0, 19]`**
#### Idea 1
Sort the array.
[-2, 0, 5, 11, 13, 19, 27, 31]
Looking at the tree below, we can see this is a heap.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/212/original/upload_9f7fe8790107f82aae93749c6113414c.png?1704814783" width=300/>
**`Time Complexity: O(N * logN)`**
#### Idea 2
Call insert(arr[i]) for every element of an array.
**Explanation:**
When insert(val) is called, at every insert we shall make sure heap property is being satisfied.
It will take N * logN, as for each element, we will take O(log N) as heapify shall be called.
**`Time Complexity:O(N * logN)`**
--
### Build a heap Idea 3
#### Idea to build in linear time
We have an array
**`[7, 3, 5, 1, 6, 8, 10, 2, 13, 14, -2]`**
We can represent this array in the form of a tree.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/218/original/2.png?1704814958" width=350/>
- In the above tree, the heap-order property is automatically valid for the leaf node, hence no need to heapify them.
- Rather, we shall start with the first non-leaf node.
- The first non-leaf is nothing but the parent of the last leaf node of the tree and the index of the last node is $n-1$, so the index of the first non-leaf is $((n-1-1)/2)=((n-2)/2)=(n/2)-1$.
- We will call heapify() starting from for $(n/2)-1$ index to index 0.
```cpp
for (int i = (n / 2) - 1; i >= 0; i--) {
heapify(heap[], i);
}
```
- Firstly it will call for i = 4(6), `heapfiy(heap[], 4)`, minimum of 6, 14, -2 is -2 so 6 and -2 will be swapped.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/222/original/a.png?1704815197" width=300/>
- Now 6 does not have any children so we will stop here.
- Call heapify for i = 3(1), now we will check minimum of 1, 2, 13 is 1, so here min-heap property is already satisfied.
- Call heapify for i = 2(5), minimum of 5, 8, 10 is 5 and it is at index 2, so here min-heap property is already satisfied.
- Call heapify for i = 1, minimum of 3, 1, -2 is -2 and so swap.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/225/original/a.png?1704815386" width=300/>
- Now we will again check for 3, and 3 is less than 14 and 6, so here heap-order property is valid here.
- Call heapify for i = 0, here also heap-order property is not satisfied as -2 is less than 7, so swap.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/226/original/b.png?1704815404" width=300/>
- Now again check for 7, here minimum of 7, 1 and 3 is 1, so again swap it.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/227/original/c.png?1704815416" width=300/>
- Now again check for minimum of 7, 2 and 13 is 2, so again swap it.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/228/original/d.png?1704815426" width=300/>
- Now 7 does not have any child so stop here.
- Now all the nodes has valid heap-order property.
#### Time Complexity
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/229/original/e.png?1704815439" width=300/>
Total Number of elements in tree = N
Elements at last level = N/2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/230/original/f.png?1704815459" width=350/>
- We are not calling heapify() for the last level(leaf node), So for the leaf node, total swaps are 0.
- For the last second level, we have N/4 nodes and at maximum, there can be 1 swap for these nodes i.e. with the last level.
- And maximum swaps for N/8 level nodes 2.
- Similar, for the root node, maximum swaps can be equal to the height of the tree.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/233/original/1.png?1704815745" width=500/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/234/original/2.png?1704815756" width=500/>
Here it is an Arithmetic Geometric progression. We need to find the sum of
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/235/original/3.png?1704815767" width=500/>
Multiply both sides by 1/2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/236/original/4.png?1704815779" width=500/>
Now subtract the above two equations
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/237/original/5.png?1704815791" width=500/>
Here we are using the formula of the sum of GP.
And put the value of the sum in this equation
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/238/original/6.png?1704815804" width=500/>
Then
(N/2) * 2
Here both will cancel out with each other and so our overall time complexity for building a heap is **O(N)**
---
### Question
What is the time complexity for building a heap with N nodes?
**Choices**
- [ ] O(1)
- [ ] O(N$^2$)
- [x] O(N)
- [ ] O(logN)
---
### Merge N-sorted arrays
a - [2, 3, 11, 15, 20]
b - [1, 5, 7, 9]
c - [0, 2, 4]
d - [3, 4, 5, 6, 7, 8]
e - [-2, 5, 10, 20]
We have to merge these sorted arrays.
#### Idea
- If we want to merge two sorted arrays then we need two pointers.
- If we want to merge three sorted arrays then we need three pointers.
- If we want to merge N sorted arrays then we need N pointers, in which complexity becomes very high and we need to keep track of N pointers.
---
### Question
For merging N sorted arrays, which data structure would be the most efficient for this task ?
**Choices**
- [ ] Linked List
- [ ] Array
- [x] Min-Heap
- [ ] Hash Table
**Explanation:**
A Min-Heap is an efficient data structure choice. The Min-Heap ensures that the smallest element among all the elements in the arrays is always at the front. This allows for constant-time access to the minimum element, making it efficient to extract and merge elements in sorted order.
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
#### Optimized Solution
- First, we need to compare the 0th index element of every array.
- Now we use heap here.
- We will add an index 0 element of every array in the heap, in the form of element value, array number and Index of the element in particular.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/239/original/11.png?1704815927" width=250/>
Now take the minimum element and insert it in the resultant array,
- Now insert the next element of the list for which the minimum element is selected, like first, we have taken the fourth list element, so now insert the next element of the fourth list.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/240/original/22.png?1704815937" width=250/>
- Now again extract-min() from the heap and insert the next element of that list to which the minimum element belongs.
- And keep repeating this until we have done with all the elements.
#### Time Complexity
**Time Complexity:** (XlogN)
Here X is a total number of elements of all arrays.

View File

@@ -0,0 +1,567 @@
# Advanced DSA: Heaps 2: Problems
---
## Problem 1 Sort an Array
We want to sort an array in increasing order using a heap.
### Idea
We can use min-heap, and we need to call `extract-min()`/`remove(`) repeatedly many times, `extract-min()` will every time give the minimum element among all the available elements.
1. Build a min-heap.
2. `extract-min()` and store the returned value in the `ans` array until all the elements are not deleted.
---
### Question
What is the time Complexity to convert an array to a heap?
**Choices**
- [ ] O(1)
- [ ] O(log n)
- [x] O(n)
- [ ] O(nlog(n))
---
### Question
Root element in a heap is ?
**Choices**
- [ ] min element of the array
- [ ] max element of the array
- [x] either min or max depending upon whether it is min or max heap
- [ ] random element of the array
**Explanation**:
Either min or max depending upon whether it is min or max heap. Min-Heap has minimum element at the root node, where as Max-Heap has maximum element at the root node.
---
### Sort an Array Complexity and Solution Approach
#### Complexity of sorting an array using heap
1. Build a min-heap -> **Complexity:** `O(n)`
2. `extract-min()` and store the returned value in the `ans` array until all the elements are not deleted.
3. Complexity of `extract-min()` is `O(logn)` and we are calling `N` times, so the overall complexity is `O(NlogN)`.
#### Complexity
- **Time Complexity:** O(NlogN)
- **Space Complexity:** O(N), as we are using another array for building the heap.
#### Can we optimize the space complexity?
**`Hint: Try to solve by using `max-heap`.`**
- Let us take an example of `max-heap`
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/103/original/img1_.png?1704712182" width=300/>
- Create an array for this max-heap.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/104/original/img2.png?1704712218" width=500/>
- Say, we extract an element, which element will we get? The Maximum!
Now, the maximum element can be swapped with the last index. This way, maximum element will come at its correct position in sorted array.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/105/original/img_3.png?1704712238" width=600/>
- Now we will virtually remove the last element, which means we consider an array till the second last element of an array.
- Now, since the tree is not satisfying the heap order property, so we will call `heapify()` for index 0.
- So when we call `heapify()`, firstly 3 is swapped with 13(maximum of 13 and 10).
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/106/original/img_4.png?1704712261" width=200/>
- Now again 3 is swapped with 7.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/107/original/img_5.png?1704712279" width=200/>
- Now 3 is the maximum among 3, 2 and 1. Hence, no further swaps are needed.
Now we have an array,
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/108/original/img_6.png?1704712295" width=400/>
- As we know now a maximum of all available elements is present at root, call `extract-max()`, swap maximum element with the last index element(index 8) and then we will call heapify for the value 1.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/109/original/img_7.png?1704712312" width=600/>
- 1 is swapped with 10, then swapped with 8, after that 1 will reach to its correct position.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/110/original/img_8.png?1704712328" width=200/>
- Again extract the maximum and swap it with the last(7th) index element. Then call Heapify for it.
In this way, repeat these steps we completed with all the elements of the tree.
---
### Sort an Array PseudoCode
#### PseudoCode
```cpp
Build max - heap-- -> TC: O(N)
j = N - 1;
while (j > 0) {
swap(A[0], A[j]);
j--;
heapify(0, arr[], j)
}
```
#### Complexity
- **Time Complexity:** O(NlogN)
- **Space Complexity:** O(1), we are not taking an extra array, we are converting the max heap into sorted array.
#### Is heap sort an in-place sorting algorithm?
**Answer:** Yes it is in-place as we are sorting an array using heap sort in constant time in the above question.
#### Is heap sort a stable sorting algorithm?
**Answer:** No heap sort is not stable.
**Explanation:** Heap sort is not stable because operations in the heap can change the relative order of equivalent keys.
---
### Problem 2 kth Largest Element
Given arr[N], find the kth largest element.
**Example**
**Input:**
arr[] = [8, 5, 1, 2, 4, 9, 7]
k = 3
**Output:**
7
**Explanation:**
In the above array,
- First largest element = 9
- Second largest element = 8
- Third largest element = 7
We need to return the third largest element.
---
### Question
What is the 5th largest element of an array `[1, 2, 3, 4, 5]`?
**Choices**
- [ ] 5
- [ ] 3
- [x] 1
- [ ] 2
**Explanation**
In the above array,
- First largest element = 5
- Second largest element = 4
- Third largest element = 3
- Fourth largest element = 2
- Fifth largest element = 1
We need to return the fifth largest element.
---
### kth Largest Element solution approach
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### :bulb: Idea 1(by sorting)
Sort an array and simply return arr[N-K].
**Example:**
arr[] = [8, 5, 1, 2, 4, 9, 7]
k = 3
**Solution**
Sort an array, [1, 2, 4, 5, 7, 8, 9]
Now return arr[N-K] element i.e. arr[7-3] = arr[4] = 7
**Time Complexity:** O(NlogN), **Space Complexity:** O(1).
### :bulb: Idea 2(Using binary search)
We can find the kth largest element by applying binary search just like we have used in the kth smallest element.
**Time Complexity:** O(Nlog(max-min))
### :bulb: Idea 3(Using heap sort)
1. Build a max-heap.
2. Call extract-max() k-1 times to remove K-1 elements(for first largest we need zero removals, for second largest we need 1 removal, in this way for kth largest we need k-1 removals)
### Complexity
**Time Complexity:** O(N + KlogN)
**Space Complexity:** O(1)
---
### kth Largest Element Using min-heap
### :bulb: Idea 4(Using min-heap)
Let us take an example, we want to create a cricket team of 4 batsmen and we have 8 batsmen i.e. b1, b2, b3, b4, b5, b6, b7 and b8, and every batsman is given only 1 over and everyone tries to achieve maximum run in that over.
Firstly, 4 batsmen played and scored
|b1|b2|b3|b4|
|-|-|-|-|
|12|8|4|6|
We have recently incorporated four batsmen into our team with respective scores of **`12, 8, 4, and 6`**. When batsman **`B5 joins, scoring 7`**, we opt to replace the player with the lowest score to maintain team quality. Since we use a min heap to track scores, we **`remove the batsman with a score of 4 and include B5`**, updating our heap to **[12, 8, 7, 6]**.
Later, batsman **`B6 arrives, earning 3 runs`**. However, his score **`doesn't surpass our team's minimum`**, so he isn't added. Then, batsman **`B7 steps in, scoring a notable 10 runs`**. Outperforming our lowest score, **`B7's addition leads us to drop the current minimum`** scorer and update the heap to **[12, 8, 7, 10]**.
Following this, batsman **`B8 enters with a score of 9`**. Exceeding the lowest score in our lineup, we **`incorporate B8 by removing the now lowest scorer`**, refining our heap to **[12, 8, 9, 10]**.
Thus, in this dynamic team selection process, the minimum element in our heap represents the fourth-highest score among our players.
#### Example:
To find the 3rd largest element in an array using a min-heap of size 3:
Given array: **`arr = [8, 5, 1, 2, 4, 9, 7] and k=3`**.
- Initialize an empty min-heap.
- Add the first three elements of the array to the heap: [8, 5, 1].
- Iterate over the remaining elements. If an element is greater than the heap's minimum, remove the minimum and insert the new element.
- After processing elements 2, 4, 9, and 7, the heap evolves as follows:
- [8, 5, 2] (after adding 2)
- [8, 5, 4] (after adding 4)
- [8, 5, 9] (after adding 9)
- [8, 7, 9] (after adding 7)
- The 3rd largest element is the minimum in the heap: 7.
#### PseudoCode
```cpp
Build min-heap with first k elements. -> O(K)
Iterate on the remaining elements. -> (N-K)
for every element, check
if(curr element > min element in heap){
extractMin()
insert(current element)
}
ans = getMin()
```
#### Complexity
- **Time Complexity:** O(K+(N-K)logK)
- **Space Complexity:** O(K)
:bulb: What should we use for finding k-th smallest?
- A max-heap of size K.
---
### Problem 2 kth Largest Element for all windows
Find the kth largest element for all the windows of an array starting from 0 index.
**Example**
**Input:**
arr[] = `[10, 18, 7, 5, 16, 19, 3]`
k = 3
**Solution:**
- We need atleast 3 elements in a window, so we will consider first window from index 0 to k-1, we have elements in that `[10, 18, 7]`; third largest is 7, ans=`[7]`.
- Window 0 to 3 `[10, 18, 7, 5]`,third largest = 7, ans=`[7, 7]`.
- Window 0 to 4 `[10, 18, 7, 5, 16]`,third largest = 10, ans=`[7, 7, 10]`.
- Window 0 to 5 `[10, 18, 7, 5, 16, 19]`,third largest = 16, ans=`[7, 7, 10, 16]`.
- Window 0 to 6 `[10, 18, 7, 5, 16, 19, 3]`,third largest = 16, ans=`[7, 7, 10, 16, 16]`.
---
### Question
Find the kth largest element for all the windows of an array starting from 0 index.
arr[] = `[5, 4, 1, 6, 7]`
k = 2
**Choices**
- [x] [4, 4, 5, 6]
- [ ] [6, 6, 6, 6]
- [ ] [5, 4, 1, 6]
- [ ] [4, 1, 6, 7]
**Explanation**:
To find the second largest element in each window of a given size in an array:
- Start with the first window (from index 0 to k-1). For example, in [5, 4], the second largest is 4. Answer array starts as [4].
- Shift the window one element at a time and find the second largest in each new window.
- Window [5, 4, 1] gives second largest 4. Answer array becomes [4, 4].
- Window [5, 4, 1, 6] gives second largest 5. Answer array becomes [4, 4, 5].
- Window [5, 4, 1, 6, 7] gives second largest 6. Answer array becomes [4, 4, 5, 6].
---
### kth Largest Element for all windows Idea
To find the k-largest elements in an array using a min-heap:
- **Initialize Min-Heap**: Start with a min-heap and add the first k elements from the array to it.
- **Compare and Update**: For each remaining array element, if it's larger than the heap's minimum, replace the minimum with this element.
- **Track Minimums**: After each update, record the heap's minimum. This shows the evolving k-th largest element.
#### Pseudocode
```java
Build min-heap with first K elements. -> O(K)
ans.add(extractMin())
Iterate on the remaining elements. -> (N-K)
for every element, check {
if(curr element > min element in heap){
extractMin()
insert(current element)
ans.add(extractMin())
}
}
```
---
### Problem 3 Sort the nearly sorted array
Given a nearly sorted array. You need to sort the array.
> Nearly sorted array definition - Every element is shifted away from its correct position by at most k-steps.
**Example**
Sorted array can be `[11, 13, 20, 22, 31, 45, 48, 50, 60]`
We are given,
**Input:**
arr[] = `[13, 22, 31, 45, 11, 20, 48, 60, 50]`
k = 4
Every element is not more than 4 distance away from its position.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### :bulb: Idea 1(Sorting)
Sort an Array
**Time Complexity:** O(NlogN)
#### :bulb: Idea 2
An element can be shifted by at most k steps, so the **`element at index 0 can only be shifted till index (k)`**, so the **`minimum element lies from index 0 to k`**.
- So we need to choose a minimum of first k+1 elements.
- We will take a min-heap of size k+1.
- Add first k+1 elements into a heap, heap = `[13, 22, 31, 45, 11]`.
- extractMin()(heap = `[13, 22, 31, 45]`) will give a first element of a sorted array, ans = `[11]`, now add the next element from an input array, into a heap, heap = `[13, 22, 31, 45, 20]`.
- Again extractMin(), it will give a second of a sorted array, ans = `[11, 13]`, again add the next element of the input array, again extractMin(), in this way do until we reach the last index, and then remove minimum element from array one-by-one and add it to ans array.
#### PseudoCode
```cpp
1. build min-heap with the first (k + 1) elements.
2. for(i = k + 1 ; i < N ; i ++){
extractMin(); -> put it into ans[] array
insert( arr[i] )
}
while(minHeap is not empty){
extractMin() -> put it into ans[] array
}
3. return ans;
```
#### Compexity
**Time Complexity:** O(K + N.logK)
**Space Complexity:** O(K)
---
### Flipkart's Delivery Time Estimation Challenge
*Flipkart is currently dealing with the difficulty of precisely estimating and displaying the expected delivery time for orders to a specific pin code.*
*The existing method relies on historical delivery time data for that pin code, using the median value as the expected delivery time.*
*As the order history expands with new entries, Flipkart aims to enhance this process by dynamically updating the expected delivery time whenever a new delivery time is added. The objective is to find the expected delivery time after each new element is incorporated into the list of delivery times.*
**End Goal:** With every addition of new delivery time, requirement is to find the median value.
**Why Median ?**
The median is calculated because it provides a more robust measure of the expected delivery time
The median is less sensitive to outliers or extreme values than the mean. In the context of delivery times, this is crucial because occasional delays or unusually fast deliveries (outliers) can skew the mean significantly, leading to inaccurate estimations.
---
### Problem 4 Find the median
Given an infinite stream of integers. Find the median of the current set of elements
>### Median
>Median is the Middle element in a sorted array.
>The median of [1, 2, 5, 4, 3, 6]
First, we need to sort an array [1, 2, 3, 4, 5, 6]
We have two middle values as the size of the array is even i.e. 3, 4.
So to find the median, we need to take the average of both middle values, median = (3+4)/2 = 3.5
---
### Question
The median of [1, 2, 4, 3]
**Choices**
- [ ] 2
- [ ] 4
- [ ] 3
- [x] 2.5
**Explanation**:
The median of [1, 2, 4, 3]
First, we need to sort an array [1, 2, 3, 4]
We have two middle values as the size of the array is even i.e. 2, 3.
So to find the median, we need to take the average of both middle values,
Median = (2+3)/2 = 2.5
---
### Find the median Brute Force Approach
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Understanding the question
We have an infinite stream of elements.
1. First we have one element.
6, then median = 6.
2. Next element if 3
6, 3, then median = 4.5
3. 6, 3, 8, then median = 6
4. 6, 3, 8, 11, then median = 7
5. 6, 3, 8, 11, 10 then median = 8
#### Brute Force Idea
For every incoming value, include the value and sort an array. Find the middle point/average of 2 middle points.
**Time Complexity:** O(N^2^logN)
---
### Find the median solution approach
#### Idea(Using Insertion Sort)
Every time find the correct position of the upcoming element i.e. Insertion Sort
**Time Complexity:** O(N^2^)
#### Idea(Using heap)
To find the median in an array by dividing it into two parts - one with smaller elements and the other with larger elements:
Consider an array, **`for example, [6, 3, 8, 11]`**. We divide it such that **`6, 3 are on the smaller side`** and **`8, 11 on the larger side`**, as shown in the image:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/111/original/1.png?1704712501" width=500/>
To find the median:
- If both sides have an equal number of elements, take the average of the largest element on the smaller side and the smallest element on the larger side.
- If the sizes are unequal, choose the largest element from the smaller side if it's larger, or the smallest from the larger side otherwise.
**The key is to use two heaps:** a min-heap for the larger elements and a max-heap for the smaller elements. This approach maintains a balanced partition of the array for efficient median calculation.
**Example**
arr = [6, 3, 8, 11, 20, 2, 10, 8, 13, 50, _ _ _ ]
Take two heaps, min-heap and max-heap
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/112/original/2.png?1704712513" width=400/>
Smaller side elements are stored in max-heap and Greater side elements are stored in min-heap
1. First element is 6, simply add it in max-heap
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/114/original/3.png?1704712533" width=400/>
**The median is 6.**
2. Second element is 3; compare with h1.getMax(), if 3<6 then it must be included in h1.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/115/original/4.png?1704712540" width=400/>
but now both the heaps do not have half-half elements. Remove the maximum element from max-heap and insert it into h2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/116/original/5.png?1704712551" width=400/>
Now we have an equal number of elements in both heaps, so the median is the average of the largest value of h1 and the smallest value of h2.
**Median is 4.5**
3. Next element is 8.
Compare it with h1.getMax(), 8>3 so 8 will go to h2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/117/original/6.png?1704712630" width=400/>
size(h2) is greater by 1
**Median is 6**
4. Next element is 11.
Compare it with h1.getMax(), 11>3 so 11 will go to h2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/118/original/7.png?1704712646" width=400/>
But now both heap does not have nearly half elements.
So remove the minimum element and add it to h1.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/119/original/8.png?1704712663" width=400/>
**Median is average of 6,8 = (6+8)/2 = 7**
5. Next element is 20.
Compare it with h1.getMax(), 20>6 so 20 will go to h2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/061/120/original/9.png?1704712677" width=400/>
size(h2) is greater by 1
**The median is 8.**
In this way we will do for all the elements of an array, and find the median at every step, we need to take care that the |h1.size()-h2.size()|<=1.
After adding all the medians in an array, we will get an answer: [6, 4.5, 6, 7, 8, 7, 8, 8, 8, _ _ _ ]
---
#### PseudoCode
```cpp
h1, h2
h1.insert(arr[0])
print(arr[0])
for (int i = 1; i < N; i++) {
if (arr[i] > h1.getMax()) {
h2.insert(arr[i]);
} else {
h1.insert(arr[i]);
}
diff = | h1.size() - h2.size() |
if (diff > 1) {
if (h1.size() > h2.size()) {
h2.insert(h1.getMax());
} else {
h1.insert(h2.getMin());
}
}
if (h1.size() > h2.size()) {
print(h1.getMax());
} else if (h2.size() > h1.size()) {
print(h2.getMin())
} else {
print((h1.getMax() + h2.getMin()) / 2.0);
}
}
```
#### Complexity
**Time Complexity:** O(NlogN)
**Space Complexity:** O(N)

View File

@@ -0,0 +1,351 @@
# DSA 4 - Interview Problems
---
### Problem 1 Target Sum
You are given a set of non-negative integers and a target sum. The task is to determine whether there exists a subset of the given set whose sum is equal to the target sum.
**Examples**
**Input**: set = {3, 34, 4, 12, 5, 2}, sum = 9
**Output**: True
**Explanation**: There is a subset (4, 5) with a sum of 9.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
#### Approach: Brute Force
The brute force approach involves exploring all possible subsets of the given set. This is achieved through a recursive function named isSubsetSum(set, n, sum). The function explores two possibilities for each element: including it in the subset or excluding it. The base cases check if the sum is zero or if there are no more elements to consider.
#### Code
```java
boolean isSubsetSum(int[] set, int n, int sum) {
if (sum == 0) return true;
if (n == 0 && sum != 0) return false;
// Explore two possibilities: include the current element or exclude it
return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);
}
```
#### Complexity Analysis
* **Time complexity**: O(2^n) - Exponential
* **Space complexity**: O(1)
---
### Target Sum Dynamic Programming Approach
#### Approach:
To optimize the solution, dynamic programming is employed. A 2D array `dp` is used to store results of subproblems. The value `dp[i][j]` represents whether it's possible to obtain a sum of `j` using the first `i` elements of the set.
#### Code
```java
boolean isSubsetSum(int[] set, int n, int sum) {
boolean[][] dp = new boolean[n + 1][sum + 1];
// Initialize the first column as true, as sum 0 is always possible
for (int i = 0; i <= n; i++) dp[i][0] = true;
// Fill the dp array using a bottom-up approach
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
dp[i][j] = dp[i - 1][j];
if (j >= set[i - 1]) dp[i][j] = dp[i][j] || dp[i - 1][j - set[i - 1]];
}
}
return dp[n][sum];
}
```
#### Complexity Analysis
* **Time complexity**: O(n * sum)
* **Space complexity**: O(n * sum)
---
### Problem 2 Minimum Jumps to Reach End
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
* 0 <= j <= nums[i]
* i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
#### Example 1
**Input**: nums = [2,3,1,1,4]
**Output**: 2
**Explanation**: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
#### Example 2
**Input**: nums = [2,3,0,1,4]
**Output**: 2
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Intuition
The code utilizes a greedy approach, aiming to minimize the number of jumps by selecting the jump that maximizes the range of reachable positions at each step.
#### Approach
* Initialize a counter to keep track of the number of jumps (counter).
* Use a while loop to iterate through the array until the end is reached.
* In each iteration:
* Calculate the range of positions that can be reached from the current position (range).
* If the calculated range includes the last position or exceeds it, exit the loop.
* Find the position within the current range that maximizes the next reachable position (temp).
* Update the current position to the selected position (temp).
* Increment the jump counter (counter).
* Repeat the process until the end is reached.
#### Code
```java
class Solution {
public int jump(int[] nums) {
int i = 0;
int counter = 0;
// If the array has only one element, no jumps are needed
if (nums.length == 1)
return 0;
while (i < nums.length) {
counter++;
int range = i + nums[i];
// If the range includes the last position or exceeds it, exit the loop
if (range >= nums.length - 1)
break;
int max = 0;
int temp = 0;
// Find the position within the current range that maximizes the next reachable position
for (int k = i + 1; k <= range; k++) {
if (nums[k] + k >= max) {
max = nums[k] + k;
temp = k;
}
}
i = temp;
}
return counter;
}
}
```
#### Complexity Analysis
**Time complexity**: O(n)
* The algorithm iterates through each element of the array once.
* The inner loop within each iteration also traverses a limited number of positions.
**Space complexity**: O(1)
* The algorithm uses a constant amount of extra space.
* The space requirements do not depend on the size of the input array.
---
### Problem 3 N digit numbers
Find out the number of A digit positive numbers, whose digits on being added equals to a given number B.
Note that a valid number starts from digits 1-9 except the number 0 itself. i.e. leading zeroes are not allowed.
Since the answer can be large, output answer modulo 1000000007
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
### Brute Force Approach
#### Objective
Count the number of A-digit positive numbers whose digit sum equals a given number B.
#### Idea
* Generate all possible A-digit numbers
* For each number, check if the sum of its digits equals B.
* Keep track of the count of valid numbers.
#### Code
```cpp
int bruteForceCount(int A, int B) {
int count = 0;
for (int num = pow(10, A - 1); num < pow(10, A); ++num) {
int digitSum = 0;
int temp = num;
while (temp > 0) {
digitSum += temp % 10;
temp /= 10;
}
if (digitSum == B) {
count++;
}
}
return count;
}
```
---
### N digit numbers optimization using Recursion
#### Observation
The brute force approach involves iterating through all A digit numbers and checking the count of numbers whose digit sum equals B.
#### Optimized Recursive Approach
**Recursive Function Definition**
* The recursive function `countWays(id, sum)` is defined to represent the count of A-digit numbers with a digit sum equal to sum.
* The base cases are as follows:
* If sum becomes negative, it implies that the digit sum has exceeded the target, so the count is 0.
* If id becomes 0, meaning all digits have been considered, the count is 1 if sum is 0 (indicating the target sum has been achieved), and 0 otherwise.
* Memoization is used to store and retrieve previously calculated values, preventing redundant computations.
**Memoization Table**
* The memo vector is a 2D table of size (A + 1) x (B + 1) initialized with -1 to represent uncalculated states.
* The value `memo[id][sum]` stores the count of A-digit numbers with a digit sum of sum that has already been calculated.
**Recursive Part**
* The function explores all possible digits from 0 to 9 in a loop.
* For each digit, it recursively calls `countWays(id - 1, sum - digit, memo)` to calculate the count of (A-1)-digit numbers with the updated digit sum.
* The results are summed up, and the modulus operation is applied to avoid integer overflow.
#### Optimized Recursive Code
```cpp
int memoizationCount(int A, int B) {
vector<vector<int>> memo(A + 1, vector<int>(B + 1, -1));
return countWays(A, B, memo);
}
int countWays(int id, int sum, vector<vector<int>>& memo) {
if (sum < 0) return 0;
if (id == 0) return (sum == 0) ? 1 : 0;
if (memo[id][sum] != -1) return memo[id][sum];
int ways = 0;
for (int digit = 0; digit <= 9; ++digit) {
ways += countWays(id - 1, sum - digit, memo);
ways %= 1000000007;
}
return memo[id][sum] = ways;
}
```
#### Optimized Iterative Code
```cpp
int iterativeCount(int A, int B) {
vector<vector<int>> dp(A + 1, vector<int>(B + 1, 0));
// Base case
for (int digit = 1; digit <= 9; ++digit) {
if (digit <= B) dp[1][digit] = 1;
}
// Build DP table
for (int id = 2; id <= A; ++id) {
for (int sum = 1; sum <= B; ++sum) {
for (int digit = 1; digit <= 9; ++digit) {
if (sum - digit >= 0) {
dp[id][sum] += dp[id - 1][sum - digit];
dp[id][sum] %= 1000000007;
}
}
}
}
return dp[A][B];
}
```
**Time Complexity** : O(A * B)
**Space Complexity** : O(A * B)
---
### Problem 4 Maximum Profit from Stock Prices
Given an array A where the i-th element represents the price of a stock on day i, the objective is to find the maximum profit. We're allowed to complete as many transactions as desired, but engaging in multiple transactions simultaneously is not allowed.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
Let's start with some key observations:
**Note 1**: It's never beneficial to buy a stock and sell it at a loss. This intuitive insight guides our decision-making process.
**Note 2**: If the stock price on day i is less than the price on day i+1, it's always advantageous to buy on day i and sell on day i+1.
Now, let's delve into the rationale behind Note 2:
**Proof**: If the price on day i+1 is higher than the price on day i, buying on day i and selling on day i+1 ensures a profit. If we didn't sell on day i+1 and waited for day i+2 to sell, the profit would still be the same. Thus, it's optimal to sell whenever there's a price increase.
#### DP-Based Solution
Now, let's transition to a dynamic programming solution based on the following recurrence relation:
Let Dp[i] represent the maximum profit you can gain in the region (i, i+1, ..., n).
**Recurrence Relation**: `Dp[i] = max(Dp[i+1], -A[i] + max(A[j] + Dp[j] for j > i))`
Here, Dp[i] considers either continuing with the profit from the next day (Dp[i+1]) or selling on day i and adding the profit from subsequent days.
#### Base Cases
When i is the last day (i == n-1), Dp[i] = 0 since there are no more future days.
When i is not the last day, Dp[i] needs to be computed using the recurrence relation.
#### Direction of Computation
We start computing Dp[i] from the last day and move towards the first day.
#### Code
```cpp
int max_profit(vector<int>& A) {
int n = A.size();
vector<int> dp(n, 0);
for (int i = n - 2; i >= 0; --i) {
dp[i] = dp[i + 1];
for (int j = i + 1; j < n; ++j) {
if (j + 1 < n) {
dp[i] = max(dp[i], -A[i] + A[j] + dp[j + 1]);
} else {
dp[i] = max(dp[i], -A[i] + A[j]);
}
}
}
return dp[0];
}
```
#### Optimized Code
The provided code snippet in C++ contains this observation-based solution. It iterates through the array, checks for price increases, and accumulates the profits accordingly.
```cpp
int Solution::maxProfit(const vector<int> &A) {
int total = 0, sz = A.size();
for (int i = 0; i < sz - 1; i++) {
if (A[i + 1] > A[i])
total += A[i + 1] - A[i];
}
return total;
}
```
**Time Complexity** : O(|A|)
**Space Complexity** : O(1)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,600 @@
# Linked List 1: Introduction
---
## Linked List
### Issues with Array
We need continuous space in memory to store Array elements. Now, it may happen that we have required space in chunks but not continuous, then we will not be able to create an Array.
### Linked List
* A linear data structure that can utilize all the free memory
* We need not have continuous space to store nodes of a Linked List.
### Representation of Linked List
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/211/original/upload_7e7b22bf1e51fd9e12b9c9a524701df4.png?1696392677" width=300/>
* it has a data section where the data is present
* a next pointer which points to next element of the linked list
### Structure of Linked List
```java
class Node{
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
```
**Example of Linked List**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/212/original/upload_ea3fcb891dd06906043a69f5ebabec0d.png?1696392700" width=500/>
<br/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/213/original/upload_cb6b9e12558bfca662aa0c8d7502a807.png?1696392732" width=500/>
* the first node of the linked list is called head
* any linked list is represented by its first node
---
### Question
Where will the "next" pointer of the last node point to?
**Choices**
- [ ] First Node
- [ ] Any Node
- [ ] Middle Node
- [x] Null
---
### Question
From which node can we travel the entire linked list ?
**Choices**
- [ ] Middle
- [x] First
- [ ] Last
- [ ] Any Node
---
### Operation on Linked List
### 1. Access kth element(k = 0; k is the first element)
```java
Node temp = Head // temp is a compy
for i -> 1 to k {
temp = temp.next
}
return temp.data // never update head otherwise the first node is lost
```
> Time complexity to access the kth element is O(K). Here we can see that linked list takes more time compared to array as it would take constant time to access the kth element.
### 2. Check for value X (searching)
We can simply iterate and check if value X exists of not.
```java
temp = Head
while (temp != null){
if(temp.data == X)
return true
temp = temp.next
}
return false
```
> Here if the Linked List is empty i.e if `Head = NULL`, if we try to access head.next it will give null pointer expection error.
Time Complexity for searching in Linked list is O(N).
> In linked list we cannot perform binary search because we have to travel to the middle element. We cannot jump to the middle element unlike array.
---
### Question
What is the time complexity to search any node in the linked list?
**Choices**
- [ ] O(1)
- [ ] O(log(N))
- [x] O(N)
- [ ] O(N ^2)
---
### Question
What is the time complexity to access the Kth element of the linked list? [index K is valid]
**Choices**
- [ ] O(1)
- [ ] O(log(N))
- [ ] O(N)
- [x] O(K)
---
### Problem 1 Insert a New Node with Data
### Insert a New Node with Data
Insert a new node with data **v** at index **p** in the linked list
>Though indexing doesn't exist is LL, but for our understanding, let's say Node 1 is at index 0, Node 2 at index 1, etc.
**Testcase 1**
v = 60 and p = 3
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/738/original/p2t1.png?1681756504" width=600 />
**Solution to Testcase 1**
* Iterate to the node having index p-1 where p-1>=0 from start of linked list. Here p is 3 so we iterate till 2
* On reaching index 2 we create a new node riz with data v i.e. 60
* Set **riz.next = t.next** and set **t.next = riz**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/746/original/s2dr3.png?1681759945" width=600/>
**Testcase 2**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/748/original/s2rt1.png?1681760633" width=700/>
**Solution to Testcase 2**
**We can do the dry run similar to testcase 1 here is the final result**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/749/original/s2rt.png?1681760713" width=700/>
---
### Question
Insert a new node with data **10** at index **2** in the Given linked list.
Head -> 1 -> 6 -> 7 -> 9 -> Null
Choose the correct LinkedList after insertion.
**Choices**
- [ ] Head -> 1 -> 6 -> 7 -> 9 -> **10** -> Null
- [x] Head -> 1 -> 6 -> **10** -> 7 -> 9 -> Null
- [ ] Head -> 1 -> **10** -> 6 -> 7 -> 9 -> Null
- [ ] Head -> 10 -> 1 -> 6 -> 7 -> 9 -> Null
---
### Insert a New Node with Data Approach
#### Approach
* Traverse till **(p - 1)th** node. Let's call it **t**.
* Create a new node **newNode**, with data **v**.
* Set **newNode.next** equals to **t.next**.
* Set **t.next** to reference of **newNode**.
#### Pseudocode 1
```cpp
Function insertAtIndex(p, v, Node head) {
Node t = head
for (i = 1; i < p; i++) // iterating updating t, p-1 times
{
t = t.next
}
// create a new node
Node newNode = Node(v)
// Inserting the Node
newNode.next = t.next
t.next = newNode
}
```
>Again there is an edge case to above solution can anyone figure it out ?
#### Edge Case
If p = 0 then where to insert the node ?
=> At head of the list.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/753/original/sdrt3.png?1681762396" width=700/>
#### Pseudocode 2
```cpp
Function insertAtIndex(p, v, Node head) {
// create a new node
Node newNode = Node(v)
Node t = head
if (p == 0) { // edge case
newNode.next = head
head = newNode
}
for (i = 1; i < p; i++) { // iterating updating t p-1 times
t = t.next
}
// Inserting the Node
newNode.next = t.next
t.next = newNode
}
```
### Time Complexity for Insertion
O(K)
---
### Deletion in Linked List
*Delete the first occurrence of value X in the given linked list. If element is not present, leave as is.*
**Example 1:**
```java
List: 1 -> 8 -> 4 -> -2 -> 12
X = -2
Ans:
List: 1 -> 8 -> 4 -> 12
-2 has been deleted from the list.
```
**Example 2:**
```java
List: 1 -> 8 -> 4 -> -2 -> 4 -> 12
X = 4
Ans:
List: 1 -> 8 -> -2 -> 4 -> 12
The first occurrence of 4 has been deleted from the list.
```
#### Cases:
1. **Empty list i.e., head = null**
```java
List: null
X = 4
Ans:
List: null
```
2. **head.data = X i.e., delete head**
```java
List: 4
X = 4
Ans:
List: null
```
3. **X is somewhere in between the list, find and delete node with value X**
```java
List: 1 -> 8 -> 4 -> -2 -> 4 -> 12
X = 4
Ans:
List: 1 -> 8 -> -2 -> 4 -> 12 (removed first occurrence)
```
4. **X is not in the list, simply return**
```java
List: 1 -> 8 -> -2 -> 7 -> 12
X = 4
Ans:
List: 1 -> 8 -> -2 -> 7 -> 12
```
---
### Question
Delete the first occurrence of value **X** in the given linked list. If element is not present, leave as is.
Linked List : ```5 -> 4 -> 7 -> 1 -> NULL```
X (to Delete) : 1
**Choices**
- [ ] 5 -> 4 -> 7 -> 1 -> NULL
- [x] 5 -> 4 -> 7 -> NULL
- [ ] 4 -> 7 -> 1 -> NULL
- [ ] 5 -> 7 -> NULL
**Explanation:**
The Value 1 is not present in the Linked List. So leave as it is.
Thus, the final Linked List is 5 -> 4 -> 7 -> -1 -> NULL
---
### Deletion in Linked List Approach and Pseudocode
#### Approach
- Check if the list is empty; if so, return it as is.
- If the target value X is at the head, update the head to the next node.
- Otherwise, iterate through the list while looking for X.
- When X is found, skip the node containing it by updating the next reference of the previous node.
- Return the modified head (which may or may not have changed during the operation).
#### Pseudocode
```java
if (head == null) return head
if (head.data == X) {
tmp = head
free(tmp) //automatically done in java, whereas have to do manually for c++ and other languages.
head = Head.next
return head
}
temp = head
while (temp.next != null) {
if (temp.next.data == X) {
tmp = temp.next
temp.next = temp.next.next
free(tmp)
return head
}
temp = temp.next
}
return head
```
#### Time complexity for Deletion
**O(N)**
> It can be seen that every operation in linked list takes linear time complexity unlike arrays.
---
### Problem 3 Reverse the linked list
**Note:** We can't use extra space. Manipulate the pointers only.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/214/original/upload_b1b57d6a7f3fa84de5c43c4e52abacbb.png?1696393145" width=600/>
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach:
- Check for Empty List:
- If head is null, return it as is.
- Handle Single Node List:
- If head.next is null, return head. (This line is optional and can be omitted without affecting the core functionality.)
- Reverse the Linked List:
- Initialize cur as head, pre as null, and a temporary variable nxt.
- While cur is not null, do the following:
- Store the next node in nxt.
- Reverse the next pointer of cur to point to pre.
- Update pre to cur.
- Move cur to the next node (nxt).
- Update head:
- After the loop, set head to pre, making the reversed list the new head.
#### Dry Run
**Initialize the pointers**
prev = null
curr = 2 -> 5 -> 8 -> 7 -> 3 -> null
nxt = null
#### Iteration 1:
**Store the next node in nxt**
```java
nxt = curr.next; nxt = 5 -> 8 -> 7 -> 3 -> null
```
**Reverse the next pointer of the current node**
```java
curr.next = prev
```
**Update the previous and current pointers**
```java
prev = curr
curr = nxt
prev = 2 -> null
curr = 5 -> 8 -> 7 -> 3 -> null
```
#### Iteration 2:
**Store the next node in nxt**
```java
nxt = curr.next; nxt = 8 -> 7 -> 3 -> null
```
**Reverse the next pointer of the current node**
```java
curr.next = prev
```
**Update the previous and current pointers**
```java
prev = curr
curr = nxt
prev = 5 -> 2 -> null
curr = 8 -> 7 -> 3 -> null
```
#### Iteration 3:
**Store the next node in nxt**
```java
nxt = curr.next; nxt = 7 -> 3 -> null
```
**Reverse the next pointer of the current node**
```java
curr.next = prev
```
**Update the previous and current pointers**
```javascript
prev = curr
curr = nxt
prev = 8 -> 5 -> 2 -> null
curr = 7 -> 3 -> null
```
#### Iteration 4:
**Store the next node in nxt**
```java
nxt = curr.next; nxt = 3->null
```
**Reverse the next pointer of the current node**
```java
curr.next = prev
```
**Update the previous and current pointers**
```java
prev = curr
curr = nxt
prev = 7 -> 8 -> 5 -> 2 -> null
curr = 3 -> null
```
**Iteration 5**:
**Store the next node in nxt**
```java
nxt = curr.next; nxt = null
```
**Reverse the next pointer of the current node**
```java
curr.next = prev
```
**Update the previous and current pointers**
```java
prev = curr
curr = nxt
prev = 3 -> 7 -> 8 -> 5 -> 2 -> null
curr = null
```
The **loop terminates** because **curr is now null**
Final state of the linked list:
```java
prev = 3 -> 7 -> 8 -> 5 -> 2 -> null
curr = null
The head of the linked list is now prev, which is the reversed linked list:
3 7 8 5 2
```
---
### Question
Reverse the given Linked List.
Linked List : 5 -> 6 -> 7 -> 8 -> 9
**Choices**
- [ ] 5 -> 6 -> 7 -> 8 -> 9
- [x] 5 <- 6 <- 7 <- 8 <- 9
- [ ] 9 -> 6 -> 7 -> 8 -> 5
- [ ] 5 <- 6 -> 7 <- 8 <- 9
---
### Reverse the LinkedList Psuedo code and Time Complexity
#### Psuedocode
```java
if (head == null)
return head;
if (head.next == null)
return head;
cur = head;
pre = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
head = pre;
```
#### TC & SC
**Time complexity -** O(N)
**Space complexity -** O(1)
--
### Problem 2 Check Palindrome
Given a Linked List, check if it is a palindrome.
**Example:**
maam, racecar, never, 121, 12321
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/215/original/upload_cda9b4e733dcc81c3804f1a2d12d9021.png?1696393390" width=500/>
---
### Question
Check the Given linked list is Palindrome or not.
Linked List : ```Head -> 1 -> Null```
**Choices**
- [x] YES
- [ ] NO
**Explanation:**
Yes, The Given Linked List is an Palindrome, Because it reads the same in reverse order as well.
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Check Palindrome Solution
**Solution 1 :**
Create a copy of linked list. Reverse it and Compare
**Complexity**
**Time Complexity -** O(N)
**Space Complexity -** O(N).
**Solution 2 :**
1. Find middle element of linked list
2. Reverse second half of linked list
3. Compare first half and compare second half
**Step wise solution:**
1. **Find length of linked list**
```java
n = 0
temp = Head
while(temp != null){
n++
temp = temp.next
}
```
2. **Go to the middle element**
// If n = 10(even), we'll reverse from 6th node.
// If n = 9(odd), then also we'll reverse from 6th node.(**5th node will be middle one that need not be compared with any node**)
So, regardless of even/odd, we can skip (n + 1) / 2 nodes.
```java
temp Head
(for i --> 1 to (n + 1) / 2){
temp =temp.next
}
//temp middle
```
3. Now reverse the linked list from $((n+1)/2 + 1)th$ node.
4. Compare both the linked list
#### T.C & S.C
Total time complexity for checking palindrome is O(N) and space complexity is O(N).

View File

@@ -0,0 +1,503 @@
# Linked List 2: Sorting and Detecting Loop
---
### Question
What is the time complexity needed to delete a node from a linked list?
**Choices**
- [ ] O(1)
- [ ] O(log(N))
- [x] O(N)
- [ ] O(N^2)
#### Explanation
To delete a node from the linked list we need to traverse till that node. In the worst case, the time-complexity would be O(N).
---
### Question
What is the time complexity needed to insert a node as the head of a linked list?
**Choices**
- [x] O(1)
- [ ] O(log(N))
- [ ] O(N)
- [ ] O(N$^2$)
**Explanation**
No traversal is needed to reach the head node. Therefore the time complexity needed is constant i.e. O(1).
---
### Question
What is the time complexity needed to delete the last node from a linked list?
**Choices**
- [ ] O(1)
- [ ] O(log(N))
- [x] O(N)
- [ ] O(N$^2$)
**Explanation:**
To delete the last node from the linked list we need to traverse till that node. In that case, the time-complexity would be O(N).
---
### Question
Can we do Binary Search in a sorted Linked List?
**Choices**
- [ ] Yes
- [x] No
**Explanation:**
Binary search relies on random access to elements, which is not possible in a linked list.
---
### Problem 1 Find the middle element.
Given a Linked List, Find the middle element.
**Examples**
Following 0 based indexing: The middle node is the node having the index (n / 2), where n is the number of nodes.
```cpp
Input: [1 -> 2 -> 3 -> 4 -> 5]
Output: [3]
Here 3 is the middle element
```
```cpp
Input: [1 -> 2 -> 3 -> 4]
Output: [2]
There are two middle elements here: 2 and 3 respectively.
```
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Find the middle element Solution
#### Solution
* First, We will find the length of the linked-list.
* Now we will traverse half the length to find the middle node
#### Pseudocode
```cpp
function findMiddle(head)
if head is null
return null
count = 0
current = head
while current is not null
count = count + 1
current = current.next
middleIndex = count / 2
current = head
for i = 0 to middleIndex - 1
current = current.next
return current
}
```
#### Complexity
**Time Complexity:** O(n * 2) = O(n)
**Space Complexity:** O(1)
#### Optimized Solution
We can optimize the solution using the **Two Pointers** technique.
* Take two pointers initially pointing at the head of the Linked List and name them slowPointer and fastPointer respectively.
* The fastPointer will travel two nodes at a time, whereas the slowPointer will traverse a single node at a time
* When the fastPointer reaches the end node, the slowPointer must necessarily be pointing at the middle node
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/464/original/upload_11f71a7c2d1ec9ad9294aa1d8cb91211.png?1697176856" width=700/>
#### Pseudocode
```java
function findMiddleTwoPointers(head)
if head is null
return null
slowPointer = head
fastPointer = head
while fastPointer is not null and fastPointer.next is not null
slowPointer = slowPointer.next
fastPointer = fastPointer.next.next
return slowPointer
```
#### Complexity
**Time Complexity:** O(n / 2) = O(n)
**Space Complexity:** O(1)
---
### Problem 2 Merge two sorted Linked Lists
Given two sorted Linked Lists, Merge them into a single sorted linked list.
**Example 1 :**
```cpp
Input: [1 -> 2 -> 8 -> 10], [3 -> 5 -> 9 -> 11]
Output: [1 -> 2 -> 3 -> 8 -> 9 -> 10 -> 11]
```
**Example 2 :**
```cpp
Input: [1 -> 7 -> 8 -> 9], [2 -> 5 -> 10 -> 11]
Output: [1 -> 2 -> 5 -> 7 -> 8 -> 9 -> 11]
```
---
### Question
Given two sorted Linked Lists, Merge them into a single sorted linked list.
`Input: [2 -> 10 -> 11] [1 -> 5 -> 12 -> 15]`
**Choices**
- [x] [1 -> 2 -> 5 -> 10 -> 11 -> 12 -> 15]
- [ ] [2 -> 10 -> 11 -> 1 -> 5 -> 12 -> 15]
- [ ] [1 -> 5 -> 12 -> 15 -> 2 -> 10 -> 11]
- [ ] [1 -> 2 -> 10 -> 5 -> 12 -> 11 -> 15]
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Merge two sorted Linked Lists Solution
#### Solution
* Base Cases Handling: First of all, we need to take care of the Base cases: if either list is empty,we return the other list
* Determine Merged List's Head: The algorithm compares the first nodes of the two lists. The smaller node becomes the head of the merged list.
* Merge the Remaining Nodes:Merge the remaining nodes in such a way that whichever linked lists node is the smallest, we add it to the current list
* We continue doing this till the end of one of the linked lists is reached
* Finally we attach any remaining nodes from list1 or list2
* Returning the Result: We return the linked list
#### Pseudocode
```cpp
function mergeSortedLists(list1, list2)
if list1 is null
return list2
if list2 is null
return list1
mergedList = null
if list1.data <= list2.data
mergedList = list1
list1 = list1.next
else
mergedList = list2
list2 = list2.next
current = mergedList
while list1 is not null and list2 is not null
if list1.data <= list2.data
current.next = list1
list1 = list1.next
else
current.next = list2
list2 = list2.next
current = current.next
if list1 is not null
current.next = list1
if list2 is not null
current.next = list2
return mergedList
}
```
#### Complexity
**Time Complexity:** O(n + m)
**Space Complexity:** O(1)
---
### Problem 3 Sort a Linked List
A Linked List is given, Sort the Linked list using merge sort.
**Example**
```cpp
Input: [1 -> 2 -> 5 -> 4 -> 3]
Output: [1 -> 2 -> 3 -> 4 -> 5]
```
```cpp
Input: [1 -> 4 -> 3 -> 2]
Output: [1 -> 2 -> 3 -> 4]
```
#### Solution
**Base Case:**<br> The function starts by checking if the head of the linked list is null or if it has only one element (i.e., head.next is null). These are the base cases for the recursion. If either of these conditions is met, it means that the list is already sorted (either empty or has only one element), so the function simply returns the head itself.
**Find the Middle Node:**<br> If the base case is not met, the function proceeds to sort the list. First, it calls the findMiddle function to find the middle node of the current list. This step is essential for dividing the list into two halves for sorting.
**Split the List:**<br> After finding the middle node (middle), the function creates a new pointer nextToMiddle to store the next node after the middle node. Then, it severs the connection between the middle node and the next node by setting middle.next to null. This effectively splits the list into two separate sublists: left, which starts from head and ends at middle, and right, which starts from nextToMiddle.
**Recursively Sort Both Halves:**<br> The function now recursively calls itself on both left and right sublists. This recursive step continues until each sublist reaches the base case (empty or one element). Each recursive call sorts its respective sublist.
**Merge the Sorted Halves:**<br> Once the recursive calls return and both left and right sublists are sorted, the function uses the mergeSortedLists function to merge these two sorted sublists into a single sorted list. This merging process combines the elements from left and right in ascending order.
**Return the Sorted List:**<br> Finally, the function returns the sortedList, which is the fully sorted linked list obtained by merging the sorted left and right sublists
#### Pseudocode
```cpp
// Function to merge two sorted linked lists
function mergeSortedLists(list1, list2)
if list1 is null
return list2
if list2 is null
return list1
mergedList = null
if list1.data <= list2.data
mergedList = list1
mergedList.next = mergeSortedLists(list1.next, list2)
else
mergedList = list2
mergedList.next = mergeSortedLists(list1, list2.next)
return mergedList
function findMiddle(head)
if head is null or head.next is null
return head
slow = head
fast = head.next
while fast is not null and fast.next is not null
slow = slow.next
fast = fast.next.next
return slow
function mergeSort(head)
if head is null or head.next is null
return head
// Find the middle node
middle = findMiddle(head)
nextToMiddle = middle.next
middle.next = null
// Recursively sort both halves
left = mergeSort(head)
right = mergeSort(nextToMiddle)
// Merge the sorted halves
sortedList = mergeSortedLists(left, right)
return sortedList
```
#### Complexity
**Time Complexity:** O(Nlog(N))
**Space Complexity:** O(log(N))
---
### Problem 4 Detect Cycle in a Linked List.
Given a Linked List, Find whether it contains a cycle.
**Example 1**
**Input:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/470/original/upload_fd21b14f9b526a9dee6af96d7c9f5f3d.gif?1697177234" width=800/>
**Output:**
```plaintext
Yes
```
**Example 2**
**Input:**
Input: [1 -> 4 -> 3 -> 2 -> 11 -> 45 -> 99]
**Output:**
```plaintext
No
```
---
### Detect Cycle in a Linked List Solution
#### Solution
* **Initialization:**<br> Start with two pointers, slow and fast, both pointing to the head of the linked list.
* **Traversal:**<br> In each iteration, the slow pointer advances by one step, while the fast pointer advances by two steps. This mimics the tortoise and hare analogy. If there is a cycle, these two pointers will eventually meet at some point within the cycle.
* **Cycle Detection:**<br> While traversing, if the slow pointer becomes equal to the fast pointer, this indicates that the linked list contains a cycle. This is because the fast pointer "catches up" to the slow pointer within the cycle.
* **No Cycle Check:**<br> If the fast pointer reaches the end of the linked list and becomes null or if the fast pointer's next becomes nullp, this means there is no cycle in the linked list.
* **Cycle Detected:**<br> If the slow and fast pointers meet, it implies that the linked list contains a cycle. The function returns true.
#### Pseudo Code
```cpp
function hasCycle(head)
if head is null or head.next is null
return false // No cycle in an empty or single-node list
slow = head
fast = head.next
while fast is not null and fast.next is not null
if slow is the same as fast
return true // Cycle detected
slow = slow.next
fast = fast.next.next
return false // No cycle detected
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 5 Find the starting point
Given a Linked List which contains a cycle , Find the start point of the cycle.
**Example**
**Input:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/471/original/upload_627b814b08d3cc13417de9d895cf1446.gif?1697177500" width=500/>
**Output:**
```plaintext
5
```
---
### Find the starting point Solution
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Solution
* **Initialization:**<br> Similar to cycle detection, start with two pointers, slow and fast, both pointing to the head of the linked list.
* **Cycle Detection:**<br> In each iteration, move the slow pointer by one step and the fast pointer by two steps. If a cycle exists, they will eventually meet within the cycle.
* **Meeting Point:**<br> If a cycle is detected (slow meets fast), set a flag hasCycle to true.
* **Start Point Identification:**<br> Reset the slow pointer to the head of the list while keeping the fast pointer at the meeting point. Advance both pointers by one step in each iteration. They will eventually meet at the start point of the cycle.
* **Returning the Result:**<br> Once the slow and fast pointers meet again, it implies that the linked list has a cycle, and the meeting point is the start of the cycle. Return this pointer.
Assume that the length from the head to the first node of cycle is x and the distance from the first node of cycle to the meeting point is y. Also the length from the meeting point to the first node is z.
Now, speed of the fast pointer is twice the slow pointer
```cpp
2(x + y) = x + y + z + y
x = z
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/481/original/upload_53a9113ef4baf57965effd9d80628c34.png?1697178095" width=700/>
* **No Cycle Check:** If the fast pointer reaches the end of the linked list (i.e., becomes nullptr) or if the fast pointer's next becomes nullptr, there is no cycle. In such cases, return nullptr.
This approach ensures that you can find the start point of the cycle using the Floyd's Tortoise and Hare algorithm with a slightly modified process.
#### Pseudo Code
```cpp
function detectCycleStart(head)
if head is null or head.next is null
return null // No cycle in an empty or single-node list
slow = head
fast = head
hasCycle = false
while fast is not null and fast.next is not null
slow = slow.next
fast = fast.next.next
if slow is the same as fast
hasCycle = true
break
if not hasCycle
return null // No cycle detected
slow = head
while slow is not the same as fast
slow = slow.next
fast = fast.next
return slow // Return the start point of the cycle
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)

View File

@@ -0,0 +1,340 @@
# Linked List 3: Problems & Doubly Linked List
---
## What is doubly linked list
A doubly linked list is a type of data structure used in computer science and programming to store and organize a collection of elements, such as nodes. It is similar to a singly linked list but with an additional feature: each node in a doubly linked list contains pointers or references to both the next and the previous nodes in the list.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/483/original/upload_213ccfab994121707413abee35188ad7.png?1697178938" width=500 />
### Correlation with Singly Linked List
The main difference between singly linked lists and doubly linked lists lies in the bidirectional traversal capability of the latter, which comes at the cost of increased memory usage. The choice between them depends on the specific requirements of the problem we're solving and the operations we need to perform on the list
> **Note-1**: Sometimes the `previous` pointer is called the `left` pointer and the `next` pointer is called the `right` pointer.
> **Note-2**: The `previous` pointer of the first node always points to `null` and the `next` pointer of the last node also points to `null` in the doubly linked list.
---
### Question
`prev` Pointer of Head of Doubly LinkedLIst points to:
**Choices**
- [ ] Next to Head Node
- [x] Null pointer
- [ ] Tail
- [ ] Depends
---
### Problem 1 Insert node in a doubly linked list
A doubly linked list is given. A node is to be inserted with data ``X`` at position ``K``. The range of ``K`` is between 0 and ``N`` where ``N`` is the length of the doubly Linked list.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/485/original/upload_22adfd80f32ce29dd08a28d3da723c06.png?1697179076" width=700 />
---
### Question
In a doubly linked list, the number of pointers affected for an insertion operation between two nodes will be?
**Choices**
- [ ] 1
- [ ] 2
- [ ] 3
- [x] 4
- [ ] Depends
For insertions in the middle of the list **four** pointer assignments take place.
---
### Insert node in a doubly linked list Solution
#### Solution
A naive approach to insert a node with data `X` at position `K` in a doubly linked list of length `N` would involve traversing the list from the beginning until position `K` is reached, and then updating the pointers of the adjacent nodes to include the new node. This approach takes `O(K)` time complexity in the worst case.
#### Our Approach
Let us now move on to the below approach:
Suppose given data are `X = 8` and `K = 3` and the provided linked list contains the nodes 1, 2, 3, 4, 5. Now, describe the overall approach in a step-wise manner.
1. The very first thing that can be done is to create a node with data `X` whose previous and next pointers are pointing toward `null` currently.
2. Next, we need to check if our linked list is empty or not. In the case of an empty linked list head pointer points towards `null`. So, if the head pointer is pointing towards `null`, we can simply return a new node with data `X`.
3. The next thing that we need to take care of is if the value of `K` is zero. In this case, we need to add a new node with data `X` pointed by the head pointer. we also need to update the head pointer and the next pointer of the newly created node.
4. Now that we have covered the two base cases, we can simply add the node by making `K - 1` jumps from the head pointer. For this, we can create a temporary node that is currently pointing toward the head, and we will traverse the `K - 1` nodes to reach the position where we want to add the new node.
5. The last and most important thing that we need to do here is to update the next and previous pointers of `K - 1` and `K + 1` nodes.
Let us now see the pseudo code of our approach.
#### Pseudocode
```cpp
xn = new Node(x) // xn.next = xn.pre = null
// Empty List
if (head == null)
return xn
// Update head
if (k == 0) {
xn.next = head
head.pre = xn
head = xn
return head
}
temp = head
for i = 1 to(k - 1)
temp = temp.next
xn.next = temp.next
xn.pre = temp
if (temp.next != null)
temp.next.pre = xn
temp.next = xn
return head
```
>**Note**: we should also check if our current position of insertion is the last node or not. In the case of the last node, the next pointer is pointing toward the `null`. So, we have to make it point to the current node.
#### Time and Space Complexity
- **Time Complexity**: **O(N)**, since we traverse the linked list only once.
- **Space Complexity**: **O(1)** as we are not using any extra list.
---
### Problem 2 Delete the first occurrence of a node from the doubly linked list
We have been given a doubly linked list of length `N`, we have to delete the first occurrence of data `X` from the given doubly linked list. If element `X` is not present, don't do anything.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/486/original/upload_551369ab85fade6023d1ca5aab112f91.png?1697179461" width=600 />
---
### Delete the first occurrence Solution
#### Solution
A naive approach to solving this problem would be to start from the beginning of the doubly linked list and traverse it node by node. If the data of a node matches the given element, X, then remove that node by updating the next and previous pointers of the adjacent nodes to bypass the node to be deleted.
#### Our Approach
Suppose we have a DLL having nodes 9, 7, 3, 7, and 3, and we have to delete node 7. Let's break it into smaller steps:
1. The simple thing that we need to do in this problem is to grab the previous node and the next node of node `X`.
2. Then make the next pointer of the previous node point to the next node and make the previous pointer of the next node point to the previous node.
3. Now, move on to corner cases. The first corner case is when the head pointer is pointing to `null`. In this case, we simply need to return null as we cannot delete anything.
4. Now let's move on to the normal case and search for our next node. For searching we just need to create a temporary nod that is pointing to the head.
5. Now, we will traverse the entire list using temporary nodes and check if the current node's value is the same as the `X`'s value.
6. If the value is found, we just need to stop searching and delete the node.
After traversal, we can have three situations:
1. If the temp pointer is pointing to null, this means that we have not found our node. So, we can simply return the head pointer.
2. If the previous pointer of the temporary node is pointing to null, then this means that our desired node is the first node. So, we need to delete the head pointer and simply return null. This will work the same if the next pointer of temp is null.
3. If both the above corner cases are not encountered, then we can simply delete the current node that is pointed by temp.
Let us now see the pseudo code of our approach.
#### Pseudocode
```cpp
temp = head
// Searching
while (temp != null) {
if (temp.data == X)
break
temp = temp.next
}
// No update
if (temp == null) {
return head
}
// Single node
if (temp.pre == null and temp.next == null) {
return null
} else if (temp.pre == null) // delete head
{
temp.next.pre = null
head = temp.next
} else if (temp.next == null) {
temp.pre.next = null
} else {
temp.pre.next = temp.next
temp.next.pre = temp.pre
}
return head
```
#### Time and Space Complexity
- **Time Complexity**: **O(N)**, since we traverse the linked list only once.
- **Space Complexity**: **O(1)** as we are not using any extra list.
---
### Problem 3 LRU
We have been given a running stream of integers and the fixed memory size of `M`, we have to maintain the most recent `M` elements. In case the current memory is full, we have to delete the least recent element and insert the current data into the memory (as the most recent item).
**Example**
This question is closely related to the concept of an LRU (Least Recently Used) cache memory. An LRU cache is a data structure that maintains a fixed-size memory and stores the most recently accessed items. When the cache is full and a new item needs to be inserted, the least recently used item is evicted to make space for the new item.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/488/original/upload_e9764c3d0a621e599b59bbd40017650a.png?1697179670" width=700 />
---
### Question
What is the behavior of an LRU cache memory when a new item is inserted and the cache is already full?
**Choices**
- [x] The new item is added to the cache, and the least recently used item is removed from the cache.
- [ ] The new item is not added to the cache, and the least recently used item is not removed from the cache.
- [ ] The new item is added to the cache, and the least recently used item is updated to be the most recently used item.
- [ ] The new item is not added to the cache, and the most recently used item is removed from the cache.
In an LRU cache, the least recently used item is always the one that is removed when the cache is full and a new item needs to be inserted. This ensures that the most recently accessed items are always prioritized and kept in the cache.
---
### LRU Solution
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Solution
Suppose we have several data to be inserted and the memory size is `M = 5`. So, we will take data one by one and insert it into the memory. As soon as the memory gets full, we have to delete the oldest data. In case a number comes and the same number is present in the memory pool, it will not be deleted but it will be considered as the most recent element.
A decision tree or flow chart can also be created for the problem.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/489/original/upload_d6013eb06c37f8089ff8560707ef330b.png?1697179781" width=700 />
There can be two cases when a new number is to be inserted.
1. If the current number is not present in the memory pool. In this case, we can simply delete the oldest number (i.e. deleting the head node).
2. If the current number is present in the memory pool. In this case, we have to maintain the number `X`, as well as its position. So we can use a data structure called HashMap.
Let us now see the pseudo code of our approach.
#### Our Approach
So, the conclusion is that we have to use a Doubly Linked List or a hashmap for the solution to this problem. Let now move on to the Coding / Solution part:
1. Create a HashMap. Storing the value `X`, and the node of `X`.
2. Check if the HashMap contains `X` and the size of memory is not full, then we can simply put a new number at the last position. In this case, we also need to tackle the corner cases of the problem - Deletion of a new node from the doubly linked list.
3. The last case is when the number `X` is not present in the memory pool. Here, if the memory is full, we have to delete the oldest number i.e. the head node of the DLL( that we covered in the previous question). If the memory is not full we need to insert a new node into DLL at last.
#### Important Concept
There is an important concept in the Doubly linked list that is shallow copying and deep copying.
In a doubly linked list, the concept related to shallow copying and deep copying is about how references (pointers) to nodes are managed during copying: "Shallow copying" involves copying the structure of the list, including the references, while "deep copying" involves creating new nodes and copying their content to have an independent copy of the original list.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/490/original/upload_51b509a42a7f7730de730f294350aa25.png?1697179902" width=600 />
#### Pseudocode
```cpp
// Take a hashmap (hm)
HashMap < x, node of x > hm;
if (h.containsKey(X)) {
// Delete x from its position
xn = hm.get(x)
head = deleteNode(xn, head)
// insert as as node
tail.next = xn
xn.pre = tail
tail = xn
} else // Not present
{
// full memory
if (hm.size() == M) {
hm.remove(head.data)
deleteNode(head)
}
xn = new Node(x)
hm.put(x, xn)
if (hm.size() > 1) {
// Insert as last node
tail.next = xn
xn.pre = tail
tail = xn
} else {
head = tail = xn
}
}
```
#### Time and Space Complexity
- **Time Complexity**: **O(N)**, since we traverse the linked list only once.
- **Space Complexity**: **O(1)** since we are not using any additional list.
---
### Problem 4 Deep copy of a doubly linked list
we have to create a deep copy of the Doubly Linked list with random pointers. Here there is no certain next and previous pointer, a node can point to some other node.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/491/original/upload_417b733a9e235dfef1a60636c5c40857.png?1697180048" width=500/>
---
### Deep Copy Solution
#### Solution
A naive approach to creating a deep copy of a doubly linked list with random pointers could involve iteratively traversing the original list, creating new nodes with the same data and random pointers, and then using additional passes to update the random pointers to point to the corresponding new nodes in the copied list.
#### Our Approach
1. In a node, we have two pointers. The first one is the next pointer and the second one is a random pointer.
2. Our goal is to populate the Doubly Linked list using the next and random pointer. For this, we will be using the concept of deep copying in this.
3. Now, since we don't have the previous and next pointer as of the Doubly Linked list, we can use a HashMap to map the original nodes.
4. So, we will be creating the HashMap containing two things one is an old node and another is a new node but there is a small problem in this approach, we are using extra space here. As we only want the original mapping, we can solve this with constant space.
A systematic approach can be:
1. we will create a copy of each node calling it ``node_1`` and making it pointed by the first node.
2. After this, we will make it point to the second node. So we are pushing a node between two nodes.
>**Note**: Here, we can teach that this problem can be summarized as pushing a copy of a node between two nodes and then changing the random pointer.
3. Now, the problem becomes sorted as we only must copy a node and insert it in the middle of its previous and next node.
4. Finally, we will be shuffling the random pointer. For this, we will be using an extra node ``X``, and ``X`` will be traversing until the last node of the list.
#### Pseudocode
```cpp
// Populate random pointers
x = head
while (x != null) {
y = x.next
y.random = x.random.next
x = x.next.next
}
// Separate two
h = head.next
x = head
while (x != null) {
y = x.next
x.next = x.next.next
if (y.next != null) {
y.next = y.next.next
}
x = x.next
}
return h
```
#### Time and Space Complexity
- **Time Complexity**: **O(N)**, as we are creating a deep copy of the doubly linked list with random pointers.
- **Space Complexity**:**O(N)**. In the case of deleting the first node, the time complexity remains **O(1)** as long as the deletion operation itself is **O(1)**.
---
### Question
What is the time complexity of creating a deep copy of a Doubly Linked List consists of N nodes with random pointers using extra space?
**Choices**
- [x] O(N)
- [ ] O(N * N)
- [ ] O(1)
- [ ] O(log(N))

View File

@@ -0,0 +1,438 @@
# Maths 1: Modular Arithmetic & GCD
---
## Modular Arithmetic Introduction
A % B = Remainder when A is divided by B
Range of A % B will be within **[0, B - 1]**
### Why do we need Modular Arithmetic(%) ?
The most useful need of `%` is to limit the range of data. We don't have unlimited range in **Integer** OR **Long**, hence after a certain limit, we cannot store data. In such cases, we can apply mod to limit the range.
### Rules for applying mod on Arithmetic Operations
**1.** `(a + b) % m = (a % m + b % m) % m`
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/401/original/Screenshot_2023-10-19_at_11.25.07_AM.png?1697694922" />
---
**2.** `(a * b) % m = (a % m * b % m) % m`
**3.** `(a + m) % m = (a % m + m % m) % m = (a % m) % m = a % m`
---
**4.** `(a - b) % m = (a % m - b % m + m) % m`
This extra **m** term is added to ensure that the result remains within the range of **0 to m-1** even if the intermediate result of **(a % m - b % m) is negative**. This guarantees that the final remainder is a non-negative value.
Example:
Let's take **a = 7**, **b = 10**, and **m = 5**.
$(a - b)~ \%~ m ~=~ (7 - 10) ~\%~ 5 ~=~ -3 ~\%~ 5 = -3$ (which is not in the range 0 to 4)
Now we can simly do
(-3 + 5) % 5 = 2 (now value is in the range 0 to 4)
---
**5.** `(a ^ b) % m = ( (a % m) ^ b ) % m`
(a raise to power b)
---
### Question
Evaluate :
$(37^{103} - 1) \% 12$
**Choices**
- [ ] 1
- [x] 0
- [ ] No Idea
- [ ] 10
**Explanation**:
$(37^{103}-1)\%12$
$=>~ ((37^{103}~\%12)-(1\%12)+12)\%12$
$=>~ (((37\%12){103}~\%12)-1+12)~\%12$
$=>~ (1-1+12)\%12 = 12\%12 =0$
---
### Question
What is the result of the following modular arithmetic operation?
(25+13)%7
**Choices**
- [ ] 1
- [ ] 2
- [x] 6
- [ ] 4
**Explanation**
(25+13)%7=38%7=3⋅7+3=3
Therefore, the correct choice is 6.
---
### Question 1 Count pairs whose sum is a multiple of m
Given N array elements, find count of pairs (i, j) such that $(arr[i] + arr[j]) ~\%~ m = 0$
**Note:** $i~!=~j$ and pair(i, j) is same as pair(j, i)
**Example**
`A[ ] = {4, 3, 6, 3, 8, 12}`
`m = 6`
Pairs that satisfy **$(arr[i] + arr[j]) ~\%~ 6 = 0$** are:
`(4 + 8) % 6 = 0`
`(3 + 3) % 6 = 0`
`(6 + 12) % 6 = 0`
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force Approach
* For each pair of distinct indices `i` and `j` (where `i != j`), the sum $arr[i] ~+~ arr[j]$ is calculated, and then the remainder of this sum when divided by `m` is checked.
* If the remainder is 0, then the pair `(i, j)` satisfies the condition, and the count is incremented. This approach has a time complexity of $O(N^2)$, where N is the number of elements in the array, as it involves checking all possible pairs.
#### Optimal Approach
**Hint:**
We can utilise the property: $(a + b) \% m = (a \% m + b \% m) \% m$
Instead of directly checking for $(a+b)\%m$, we can check for $(a ~\%~ m ~+~ b \% m) \% m$
**Idea:**
* Iterate through the array and calculate `A[i] % m` for all values.
* Now, the sum of `A[i] % m` for two values should be divisible by m.
**Example**:
```java
A[ ] = {2, 3, 4, 8, 6, 15, 5, 12, 17, 7, 18}
m = 6
```
After doing mod with 6, we'll get
```java
{2, 3, 4, 2, 0, 3, 5, 0, 5, 1, 0}
Note: The range of A[i] % 6 is from 0 to 5
```
* Summing 1 with 5 will give sum divisible by 6.
* Likewise, 2 with 4, 3 with 3, and lastly 0 with 0.
#### Algorithm
* Iterate given array and calculate $A[i]\%m$.
* Create a frequency array of size **m** to store the frequency of remainders obtained from the elements.
* For each element, find the complement remainder needed for the sum to be divisible by `m`. Count frequency of complement remainder. Add these counts to get the total count of pairs satisfying the condition.
* **Note:** Mod 0 will form a pair with 0, i.e if m = 6, and say 12 & 18 are present in given array, doing 12 % 6 and 18 % 6 will result in 0.
#### Dry Run
```java
A[ ] = {2, 3, 4, 8, 6, 15, 5, 12, 17, 7, 18}
m = 6
```
After doing mod with 6, we'll get
```java
{2, 3, 4, 2, 0, 3, 5, 0, 5, 1, 0}
```
* We'll keep inserting frequency of elements in frequency array while iterating over remainder values -
| Remainder | Pair for it | Frequency | Count | Freq array |
|:---------:|:-------------------:|:----------------------------------------------------------------------:|:-----:| --- |
| 2 | $6-2 = 4$ | 4 is not yet present, but insert 2 for future use. | 0 | 2:1 |
| 3 | $6-3 = 3$ | 3 is not yet present, but insert 3 for future use. | 0 | 2:1 3:1 |
| 4 | $6-4 = 2$ | 2 is present with freq 1, count += 1 i.e, **1**; insert 4 for future use | 1 | 2:1 3:1 4:1 |
| 2 | $6-2 = 4$ | 4 is present with freq 1, count += 1 i.e, **2**; update frequency of 2. | 2 | 2:2 3:1 4:1 |
| 0 | 0 forms pair with 0 | 0 is not yet present, but insert 0 for future use. | 2 | 2:2 3:1 4:1 0:1 |
| 3 | $6-3 = 3$ | 3 is present with freq 1, count += 1 i.e, **3**; update frequency of 3. | 3 | 2:2 3:2 4:1 0:1 |
| 5 | $6-5 = 1$ | 1 is not yet present, but insert 5 for future use. | 3 | 2:2 3:2 4:1 0:1 5:1 |
| 0 | 0 forms pair with 0 | 0 is present with freq 1, count += 1 i.e, **4**; update frequency of 0. | 4 | 2:2 3:2 4:1 0:2 5:1 |
| 5 | $6-5 = 1$ | 1 is not yet present, but update frequency of 5 | 4 | 2:2 3:2 4:1 0:2 5:2 |
| 1 | $6-1 = 5$ | 5 is present with freq 2, count += 2 i.e, **6**; update frequency of 1. | 6 | 2:2 3:2 4:1 0:2 5:2 1:1 |
| 0 | 0 forms pair with 0 | 0 is present with freq 2, count += 2 i.e, **8**; update frequency of 0. | 8 | 2:2 3:2 4:1 0:3 5:2 1:1 |
#### Pseudocode
```cpp
int pairSumDivisibleByM(A, m) {
N = A.length;
freq[N] = {
0
};
count = 0;
for (int i = 0; i < N; i++) {
val = A[i] % m;
if (val == 0) {
pair = 0;
} else {
pair = m - val;
}
ans += freq[pair];
freq[val]++;
}
return count;
}
```
**Time Complexity** - `O(N)`
---
### Question
**Space Complexity**: Pair Sum Divisible by M
**Choices**
- [ ] O(N)
- [x] O(M)
- [ ] O(N+M)
**Explanation**
Space Complexity (SC) is `O(M)`, where M is the modulus value. This is because the frequency array of size M is required to store frequency of elements from 0 to M-1.
---
## GCD Basics
### Explanation
* GCD - Greatest Common Division
* HCF - Highest Common Factor
* GCD(A, B) - Greatest factor that divides both a and b
If we have `GCD(A, B) = x`
This implies:-
* A % x = 0
* B % x = 0
and hence `x` is the highest factor of both A and B
**Example - 1**
GCD(15, 25) = 5
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/487/original/Screenshot_2023-10-19_at_8.14.14_PM.png?1697726838" width="300"/>
**Example - 2**
GCD(12, 30) = 6
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/490/original/Screenshot_2023-10-19_at_8.14.22_PM.png?1697726994" width="250" />
**Example - 3**
GCD(0, 4) = 4
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/488/original/Screenshot_2023-10-19_at_8.14.32_PM.png?1697726867" width="250" />
**Example - 4**
GCD(0, 0) = Infinity
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/489/original/Screenshot_2023-10-19_at_8.14.39_PM.png?1697726934" width="250"/>
---
## Properties of GCD
### Property - 1
GCD(A, B) = GCD(B, A)
### Property - 2
GCD(0, A) = A
### Property - 3
GCD(A, B, C) = GCD(A, GCD(B, C)) = GCD(B, GCD(C, A)) = GCD(C, GCD(A, B))
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/491/original/Screenshot_2023-10-19_at_8.14.46_PM.png?1697727034" width="500"/>
### Property - 4
Given `A >= B > 0`,
**GCD(A, B) = GCD(A - B, B)**
**Example:**
<img src="https://hackmd.io/_uploads/S1yPWyBh3.png" width="500"/>
### Property - 5
GCD(A, B) = GCD(A % B, B)
---
### Question
gcd(0,8) = ?
Chose the correct answer
**Choices**
- [ ] 1
- [x] 8
- [ ] 0
- [ ] not defined
---
### Question
TC of gcd(a1,a2,a3,....,an) is:
Chose the correct answer
**Choices**
- [ ] O(log(max number))
- [ ] O(N)
- [x] O(N*log(max number)
- [ ] O(N^2)
---
### Question
Given an array A = [15, 21, 33, 45], find the GCD of all elements in the array.
**Choices**
- [ ] 4
- [x] 3
- [ ] 6
- [ ] 9
---
## Function of GCD
### Write a function to find GCD(A, B)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/492/original/Screenshot_2023-10-19_at_8.15.12_PM.png?1697727112" width="600" />
Suppose we have two positive numbers a, b then:
```java
int gcd(a, b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
```
**Time Complexity(TC):** O(log(max(a, b)))
### Given an array, calculate GCD of the entire array
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/493/original/Screenshot_2023-10-19_at_8.15.19_PM.png?1697727148" width="500" />
```java
int gcdArr(int[] arr) {
int ans = arr[0];
int n = arr.length();
for (int i = 0; i < n; i++) {
ans = gcd(ans, arr[i])
}
return ans;
}
```
---
### Problem 2 Delete One
**Question**
Given arr[N] elements , we have to delete one element such that GCD of the remaining elements becomes maximum.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/494/original/Screenshot_2023-10-19_at_8.15.30_PM.png?1697727189" width="600"/>
#### Brute Force Approach
The brute approach for this problem will be to delete arr[i], and then calculate the GCD for all the remaining elements. This will be repeated for all the elements.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/495/original/Screenshot_2023-10-19_at_8.15.39_PM.png?1697727231" width="300" />
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
#### Optimal Approach: Prefix Array
**Approach:**
* Idea is to find the GCD value of all the sub-sequences of length (N 1) and removing the element which is not present in the sub-sequence with that GCD. The maximum GCD found would be the answer.
* To find the GCD of the sub-sequences optimally, maintain a `prefixGCD[]` and a `suffixGCD[]` array using single state dynamic programming.
* The maximum value of GCD(`prefixGCD[i 1]`, `suffixGCD[i + 1]`) is the required answer.
The implementation is given below:
```java
// Recursive function to return gcd of a and b
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int MaxGCD(int a[], int n) {
// Prefix and Suffix arrays
int Prefix[] = new int[n + 2];
int Suffix[] = new int[n + 2] ;
Prefix[1] = a[0];
for (int i = 2; i <= n; i += 1) {
Prefix[i] = gcd(Prefix[i - 1], a[i - 1]);
}
Suffix[n] = a[n - 1];
for (int i = n - 1; i >= 1; i -= 1) {
Suffix[i] = gcd(Suffix[i + 1], a[i - 1]);
}
// If first or last element of the array has to be removed
int ans = Math.max(Suffix[2], Prefix[n - 1]);
// If any other element is replaced
for (int i = 2; i < n; i += 1) {
ans = Math.max(ans, gcd(Prefix[i - 1], Suffix[i + 1]));
}
return ans;
}
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/496/original/Screenshot_2023-10-19_at_8.15.46_PM.png?1697727278" width="300" />
---
### Proof of gcd(a, b) = gcd(a-b, b)
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/437/original/Screenshot_2023-10-19_at_12.16.30_PM.png?1697698017" />

View File

@@ -0,0 +1,339 @@
# Maths 2: Combinatorics Basic
---
## Addition and Multiplication Rule Example 1
### Example - 1
Given 10 girls and 7 boys, How many different pairs can be formed?
**Note: pair = 1 boy + 1 girl**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/402/original/upload_16c7dda2cfb92de07aa0da616c14e6fa.png?1697695941" width="500"/>
Since each pair consists of one boy and one girl, you can pair each of the 7 boys with any of the 10 girls. This results in a total of 7 boys × 10 girls = 70 different pairs that can be formed.
---
### Addition and Multiplication Rule Example 2
### Example - 2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/403/original/upload_df4cecb847475f527b0b065f450e1ee4.png?1697695989" width="500"/>
**Approach:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/404/original/upload_3288e1ad8ab8bf9dfbab49e8176bcf58.png?1697696013" width="500"/>
To reach Agra via Delhi from Pune, you can combine the ways to get from Pune to Delhi (3 ways) with the ways to get from Delhi to Agra (2 ways).
So, the total number of ways to reach Agra via Delhi from Pune is:
3 ways (Pune to Delhi) * 2 ways (Delhi to Agra) = 6 ways.
---
# Question
No. of ways of reaching Agra from Pune ?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/640/original/Screenshot_2023-10-21_at_12.15.51_PM.png?1697870821" width="400" />
# Choices
- [ ] 72
- [ ] 12
- [x] 18
- [ ] 20
To go to Pune to delhi , there are 3 ways. And do go from delhi to agra there are 4 ways. From pune to Mumbai there are 2 ways, from Mumbai to agra there are 3 ways.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/406/original/upload_083f6fd771433dbecded9b1766c41221.png?1697696156" width="500"/>
To calculate the number of ways to reach Agra from Pune through different routes, you need to consider the combination of routes from Pune to Delhi and from Delhi to Agra, as well as the routes from Pune to Mumbai and from Mumbai to Agra. Then, you can add these possibilities together.
From Pune to Delhi, there are 3 ways.
From Delhi to Agra, there are 4 ways.
From Pune to Mumbai, there are 2 ways.
From Mumbai to Agra, there are 3 ways.
So, to find the total number of ways to reach Agra from Pune via these routes, you add the possibilities:
(3 ways from Pune to Delhi * 4 ways from Delhi to Agra) + (2 ways from Pune to Mumbai * 3 ways from Mumbai to Agra) = $(3 * 4) + (2 * 3) = 12 + 6 = 18$ ways.
There are 18 different ways to reach Agra from Pune through these routes.
* (Multiplication) = AND: Used when counting possibilities that occur together in sequence.
* (Addition) = OR: Used when counting possibilities that occur in separate ways.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/411/original/upload_f652c91e49444d681f084737296d046d.png?1697696353" width="500"/>
---
## Permutation
### Explanation
Permutation is defined as the arrangements of objects. In permutation, **order matters**. To simplify `(i, j) != (j, i)`
### Example - 1
Given 3 distinct characters, in how many ways can we arrange them?
**Approach:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/413/original/upload_7568dff00780afa54e072374f327036d.png?1697696426" width="500"/>
---
### Question
In how many ways n distinct characters can be arranged?
**Choices**
- [ ] N * (N + 1) / 2
- [x] N! (N Factorial)
- [ ] N ^ 2
- [ ] N
### Explanation:
N distinct characters can be arranged in n! (n factorial) ways. This means that for each distinct character you have, you can multiply the total number of arrangements by the count of characters. Here's the formula:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/449/original/N!.png?1697704088" width="500"/>
---
## nPr Formulae
### Example - 2
Given N distinct characters, in how many ways you can arrange R out of N distinct chracters?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/450/original/nPr.png?1697704431" width="500"/>
**Approach:**
When arranging 2 distinct characters from a set of 4, and order matters (e.g., AB and BA are considered different arrangements), the number of ways is indeed $4 * 3 = 12$ ways.
When arranging **R** characters out of **N** distinct characters:
* For the first position, you have **N** choices
* For the second position, since you've used one character, you have **N-1** choices.
* For the third position, you have **N-2** choices, and so on.
This continues until the **R-th** position, for which you have $N-(R-1)$ choices.
Thus, the total number of ways to arrange **R** characters out of **N** distinct characters is `N (N 1) (N 2) ... (N (R 1))`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/415/original/upload_63876d8d7294076b99a93712b6c490f4.png?1697696591" width="500"/>
Here:
* **n** is the total number of distinct characters.
* **r** is the number of characters you want to arrange.
* **nPr** represents the permutations of **n** items taken **r** at a time.
---
## Combination
### Explanation
Combination is defined as the number of ways to select something.
**Note:** In combination, **order of selection does not matter**. To simplify `(i, j) = (j, i)`
### Example - 1
Given 4 players, count the number of ways of selecting 3 players.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/416/original/upload_2220fb8671ac7d6ddf6020bad13d7a26.png?1697696630" width="500"/>
### Example - 2
Given 4 players, write the number of ways to arrange players in 3 slots
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/417/original/upload_437149b5f107414c3e9c7de3abaab121.png?1697696655" width="500"/>
* **Number of Selections (x):** You are selecting 3 players out of 4, which is represented as **4C3**, and it equals 4.
* **Number of Arrangements in Each Selection (6):** There are 3! (3 factorial) ways to arrange 3 players within 3 slots, which is 6.
* **Total Number of Arrangements:** Multiply the number of selections by the number of arrangements in each selection:
Number of Selections * Number of Arrangements in Each Selection = $4 * 6 = 24$
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/418/original/upload_640820c7d18e2637883e9bf2cf19f1ad.png?1697696708" width="500"/>
---
## nCr Formulae
### Example - 3
Given **n** distinct elements, in how many ways we can select **r** elements s.t `0 <= r <= n`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/419/original/upload_8d51bb5d67f2e1164fb4455f0514a47a.png?1697696754" width="500"/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/420/original/upload_39ee568b2cb0325e3e13071203ebeaa6.png?1697696789" width="500"/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/421/original/upload_45755c9cfa7b404d5cfe1a348e9b800d.png?1697696823" width="500"/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/422/original/upload_e304bd1176a20d8529433879998f60c9.png?1697696867" width="500"/>
---
## Properties of Combination
### Property - 1
The number of ways of selecting **0** items from **N** items, i.e. number of ways to **not select anything**, will always be **1**.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/423/original/upload_593decf3cd709e2904f9238a8641f134.png?1697696921" width="500"/>
### Property - 2
The number of ways of selecting **n** items from **n**, i.e. number of ways to **select everything** will also be **1**.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/424/original/upload_329467ded9b7afdc7a63d51f5e237fa2.png?1697696949" width="500"/>
### Property - 3
Number of ways of selecting **(n-r)** items from **n**:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/426/original/upload_0d1e20a0920a46798d66c9421f0d58dd.png?1697697011" width="500"/>
---
## Special Property
### Property - 4
Given **n** distinct elements, select **r** items:
For each elements, we have 2 options, either to select or not select:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/428/original/upload_872a1a64f356a30283360e845c6aef3a.png?1697697049" width="500"/>
**Select Case:**
When you choose to "select" an element from the available n distinct elements, it means that you are including that specific element as one of the r items you want to pick. In this case:
* You decrease the number of items you need to select by 1, so it becomes r - 1.
* You decrease the total number of available elements by 1, as you've already chosen one element, so it becomes n - 1.
* You continue the selection process, considering the reduced values of r and n.
**Reject Case:**
When you choose to "reject" an element, it means that you are not including that particular element as part of your selection. In this case:
* You keep the number of items you need to select the same, which remains as r.
* You decrease the total number of available elements by 1, as you've decided not to choose one element, so it becomes n - 1.
* You continue the selection process with the same value of r and the reduced value of n.
---
## Problem 1 Pascal Triangle
Generate Pascal's triangle for given value of `n`.
**Example**
Pascal Triangle for `n = 4` is given below
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/430/original/upload_b7eeb6693170725bdea0966e6ffc36d7.png?1697697147" width="500"/>
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Brute Force:** For each and every value, calculate the factorial and print it.
`c[i][j]` represents the element in the i-th and j-th column. Each element is the sum of the two numbers directly above it from the previous row. In combinatorial terms, `c[i][j]` indicates the number of ways to choose j items from a set of i items without repetition and without order.
But as we know that, factorial grows very fast as the number increases, hence this approach won't work properly.
### Optimized Approach
* Pascal's Triangle elements are calculated using `c[i][j] = c[i - 1][j] + c[i - 1][j - 1]`, summing elements from the row above.
* Start with `c[0][0] = 1`, forming the foundation of the triangle.
* Calculate rows iteratively using the relation, reusing previous row values to minimize redundant calculations.
* Utilize only two rows (previous and current) to calculate and update elements, saving memory.
* Print each row's elements to see Pascal's Triangle emerge from the calculated values.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/431/original/upload_7497467fe55b22426bb897d29269c1c5.png?1697697410" width="500"/>
### Pseudo Code
```java
void pascalsTriangle(int n) {
nCr[n][n] = {0};
for (int i = 0; i < n; i++) {
nCr[i][0] = 1;
nCr[i][i] = 1;
for (int j = 1; j < i; j++) {
nCr[i][j] = nCr[i-1][j] + nCr[i-1][j-1];
// If mentioned in the question to take % M then:
// nCr[i][j] = (nCr[i-1][j] + nCr[i-1][j-1]) % M;
}
return nCr;
}
}
```
### Complexity
**Time Complexity:** $O(N^2)$
**Space Complexity:** $O(N^2)$
---
### Problem 2 Finding N-th column title
Find the n-th column title, the columns are titled as A, B, C... and after Z, it is AA, AB, AC... and so on. Given the column number, find the title of the column.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/435/original/upload_a4a321d8e25bd825591baf4bb16ceb8b.png?1697697568" width="500"/>
Base for mapping A-Z will be 26
#### Example
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/436/original/upload_ac79c11bd69ab4ca16e15931c263e9e7.png?1697697604" width="500"/>
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* Start with the given number **n**.
* For each digit of the column title (from right to left):
* Find the remainder when **n** is divided by 26.
* Map the remainder to the corresponding letter ('A' to 'Y' for 1-25, 'Z' for 0).
* Append the letter to the Excel column title.
* Divide **n** by **26** (integer division) to process the next digit.
* Repeat step 2 until n becomes zero.
* The resulting string is the Excel column title for the original number n.
#### Code
```java
void columnTitle(int n) {
ans = "";
while(n > 0) {
ans = (char) ((n - 1) % 26 + 'A') + ans; // char + string
n = (n - 1) / 26
}
return ans
}
```
#### Complexity
**Time Complexity:** O(log(N)) [base 26]
**Space Complexity:** O(1)

View File

@@ -0,0 +1,300 @@
# Maths 3: Prime Numbers
---
## Introduction to Prime Numbers
### What are Prime Numbers?
Numbers having only 2 factors i.e, 1 and the number itself are known as Prime Numbers
**Example:** 2, 5, 7, 11
---
### Problem 1 Check if a number is prime or not
Given a number, we need to check wheather its a prime number or not
**Example**
**Input:**
```
n = 3
n = 4
```
**Output:**
```
true
false
```
---
### Question
Check whether 11 is a prime number or not!
**Choices**
- [x] true, 11 is a prime number
- [ ] false, 11 is not a prime number
### Approach
* We need to count the number of factors:
* if factors = 2, then it is prime
* otherwise if factors >2, then it is non prime
### Code snippet
```java
boolean checkPrime(int n) {
count = 0;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
if (i == n / i) {
count++;
} else {
count += 2;
}
}
}
if (count == 2) {
print("prime");
} else {
print("Not Prime");
}
}
```
---
## Problem 2 Print all prime numbers from 1 to N
Given a number N, we need to print all the prime no. from 1 to N
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/372/original/upload_ca624d99d0511b1d5e5bfea2d1f07826.png?1697652469" width="500"/>
### Question
Find all the prime numbers from 1 to N
**Choices**
- [ ] 1, 2, 3, 5, 7
- [ ] 2, 3, 5, 7, 8
- [x] 2, 3, 5, 7
- [ ] 2, 5 ,7
### Solution
**Brute Force:** Iterate from 1 to N, and check if a number is prime or not.
```java
void printAllPrime(int n) {
for (int i = 2; i <= n; ++i) {
boolean isPrime = true;
for (int j = 2; j * j <= i; ++j) {
if (i % j == 0) {
isPrime = false;
break;
}
}
}
```
* **Time Complexity (TC):** The time complexity of the given function is $O(n√n)$, as it iterates through numbers from 2 to N and for each number, it checks divisibility up to the square root of that number.
* **Space Complexity (SC):** The space complexity is O(1), as the function uses a constant amount of extra space regardless of the input size.
---
## Sieve of Eratosthenes
### Optimized approach for counting number of primes between 1 to N
**Approach**
* **Assumption:** Begin by assuming that all numbers from 2 to N are prime numbers.
* **Marking Non-Primes:** Start with the first prime number, which is 2. Since 2 is a prime number, mark all its multiples as non-prime. These multiples are 4, 6, 8, and so on.
* **Move to Next Unmarked Number:** Move to the next unmarked number, which is 3. Since 3 is a prime number, mark all its multiples as non-prime. These multiples are 6, 9, 12, and so on. Notice that we skip numbers that have already been marked as non-prime in previous steps. Unmarked numbers are prime as they do not have any number less then themselves a factor of the number except 1. Which means they are prime
* **Repeat for Remaining Unmarked Numbers:** Continue this process for the remaining unmarked numbers, each time marking all their multiples as non-prime.
* **Completion:** After going through all numbers up to the square root of N, the remaining unmarked numbers are prime numbers. This is because their multiples have been marked as non-prime in previous steps.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/373/original/upload_b442db3bcc3a4185648ef1d3ecca0ea5.png?1697652539" width="500"/>
### Code Snippet
```java
void printAllPrime(int n) {
boolean[] isPrime = new boolean[n + 1]; // Initialize a boolean array to track prime numbers
Arrays.fill(isPrime, 2, n + 1, true); // Assume all numbers from 2 to n are prime
for (int i = 2; i * i <= n; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false; // Mark multiples of the current prime as non-prime
}
}
}
}
```
### Optimization in Sieve of Eratosthenes
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/374/original/upload_b73738ff854848f11bb17d23ea42e4f3.png?1697652577)" width="500"/>
Starting from the square of each prime number, mark all its multiples as non-prime in the sieve. This is efficient because smaller multiples of the prime would have already been marked by smaller primes. By avoiding redundant marking, we optimize the Sieve of Eratosthenes algorithm.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/375/original/upload_a4554ab46a486e271d5e7e6415c6c634.png?1697653082" width="500"/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/376/original/upload_7360b60910237c0941d76a96b6bd05d4.png?1697653111" width="500"/>
* **Time Complexity (TC):** The optimized Sieve of Eratosthenes has a time complexity of O(n log log n), which means it grows very slowly. This is because the algorithm only visits and marks numbers up to the square root of N, and the number of non-prime numbers marked is logarithmic with respect to N.
* **Space Complexity (SC):** The space complexity is O(n), which is used to store the boolean array indicating whether each number is prime or not. The space used is directly proportional to the input size N.
---
### Problem 3 Smallest Prime Factor
Given N, return the smallest prime factors for all numbers from 2 to N
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/377/original/upload_1a33cf4015f2f1af58337fda6c441b81.png?1697654454" width="500"/>
### Question
What is the smallest prime factor of 25
**Choices**
- [ ] 1
- [x] 5
- [ ] 10
- [ ] 25
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Smallest Prime Factor Approach
* **Initialization:** Create an integer array to store the smallest prime factors for each number from 2 to N. Initialize each element of the array to its own value, indicating that it's not yet known if the number is prime or not.
* **Smallest Prime Factor Determination:** Starting from the first prime number (2), for each prime number:
* If the smallest prime factor for a number is still its own value (indicating it's not determined yet), mark it as the smallest prime factor for all its multiples.
* **Iterate Over All Numbers:** Go through each number from 2 to N, and for each number, if its smallest prime factor is still itself, mark it as prime and set its smallest prime factor to itself.
* **Smallest Prime Factors:** The array will now hold the smallest prime factors for all numbers from 2 to N.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/378/original/upload_e7db37ef3571b9313e25249114adbc52.png?1697654480" width="500"/>
```java
public int[] smallestPrimeFactors(int n) {
int[] spf = new int[n + 1];
for (int i = 2; i <= n; ++i) {
spf[i] = i; // Initialize smallest prime factor with its own value
if (spf[i] == i) { // i is prime
for (int j = i * i; j <= n; j += i) {
if (spf[j] == j) {
spf[j] = i; // Mark smallest prime factor for multiples
}
}
}
}
return spf;
}
```
---
## Prime Factorization
Prime factorization is the process of finding the prime numbers, which are multiplied together to get the original number. For example, the prime factors of 16 are $2 × 2 × 2 × 2$.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/379/original/upload_2fd9d2307767e0e70c77bf0a029bb7b1.png?1697654511" width="500"/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/380/original/upload_f05609851563d97d890bdf800919116b.png?1697654544" width="500"/>
---
### Problem 4 Total Number of Factors
Given a number n, assume its prime factorization
$n=i^{a1}*j^{a2}*k^{a3}...z^{ax}$
the number of choices we have for the power of every prime is [0, a1], [0,a2], [0, a3].............[0, ax]
the number of divisor/factors will be given by the formula:
(a1 + 1)*(a2 + 1)*(a3 + 1)*.....(ax + 1)
Example
**Example 1**
$25 = 5^2$
Number of divisors = $(2+1) = 3$
**Example 2**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/382/original/upload_8268cdcd52dde872eff270cd07fe0723_%281%29.png?1697655012" width="500"/>
### Question
Find the total number of factors of 20
**Choices**
- [x] 5
- [ ] 1
- [ ] 3
- [ ] 4
**Explanation:**
20 = 2^2^ * 5^1^
= (2 + 1) * (1 + 1)
= 5
The factors are 1, 2, 5, 10, 20.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
---
### Total Number of Factors Approach
#### Approach
* **Prime Factorization:** For each number from 1 to N, find its prime factorization. Determine the prime factors of the number and their respective powers.
* **Counting Factors:** The number of factors for a given number is calculated by adding 1 to each power of its prime factors and then multiplying those incremented powers together.
* **Iterate through Numbers:** Iterate through the numbers from 1 to N. For each number:
* Calculate its prime factorization.
* Count the factors using the prime factors' powers.
* **Store or Output Results:** Store or output the number of factors/divisors for each number.
The number of factors for a given number is calculated by adding 1 to each power of its prime factors and then multiplying those incremented powers together.
* **For 1:** $(1+1) = 2$ factors (1 and itself).
* **For 2:** $(1+1) = 2$ factors (1 and 2).
* **For 3:** $(1+1) = 2$ factors (1 and 3).
* **For 4:** $(2+1) = 3$ factors (1, 2, and 4).
* **For 5:** $(1+1) = 2$ factors (1 and 5).
* **For 6:** $(1+1) * (1+1) = 4$ factors (1, 2, 3, and 6).
* **For 7:** $(1+1) = 2$ factors (1 and 7).
* **For 8:** $(3+1) = 4$ factors (1, 2, 4, and 8).
* **For 9:** $(2+1) = 3$ factors (1, 3, and 9).
* **For 10:** $(1+1) * (1+1) = 4$ factors (1, 2, 5, and 10).
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/383/original/upload_822d2bbd4f4aac99df10def9ff33c6f1.png?1697655221" width="500"/>
#### Code
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/285/original/Screenshot_2024-01-24_at_7.25.23_PM.png?1706104531" width="400"/>
* **Time Complexity (TC):** The time complexity of this code is O(N * log N), mainly due to the prime factorization process for each number from 1 to N.
* **Space Complexity (SC):** The space complexity is O(N), where the primary space usage comes from the arrays for storing the smallest prime factors and the hashmap for storing the factors count for each number.

View File

@@ -0,0 +1,488 @@
# OOPS 1
### Programming Paradigms
Types:
* **Imperative Programming** - It tells the computer how to do the task by giving a set of instructions in a particular order i.e. line by line.
```cpp
// For eg:
int a = 10;
int b = 20;
int sum = a + b;
print(sum);
int dif = a - b;
print(dif);
```
* **Procedural Programming** - It splits the entire program into small procedures or functions (section of code that perform a specific task) which are reusable code blocks.
```cpp
// For eg:
int a = 10;
int b = 20;
addTwoNumbers(a, b);
subtractTwoNumbers(a, b);
void addTwoNumbers(a, b) {
int sum = a + b;
print(sum);
}
void subtractTwoNumbers(a, b) {
int dif = a - b;
print(dif);
}
```
* **Object Oriented Programming** - It builds the entire program using classes and objects. [will discuss this in detail today!]
* **Declarative Programming** - In this paradigm, you specify "what" you want the program to do without specifying "how" it should be done.
```SQL
-- For eg: (SQL Queries)
select * from Customer;
```
* **Functional Programming**, **Logic Programming**, etc.
Most of the people start their coding journey with procedural programming and hence let's start with the first type of paradigm i.e. procedural programming.
---
## Procedural Programming
It splits the entire program into small procedures or functions (section of code that perform a specific task) which are reusable code blocks. Eg - C, C++, etc.
Procedure is an oldage name of function/method.
```cpp
// For eg:
void addTwoNumbers(a, b) {
int sum = a + b;
print(sum);
}
void addThreeNumbers(a, b, c) {
int sum = a + b;
addTwoNumbers(sum, c);
}
void main() {
addThreeNumbers(10, 20, 30);
}
```
---
### Problems with Procedural Programming
**Cons of Procedural programming:**
* Difficult to make sense
* Difficult to debug and understand
* Spaghetti code i.e. unstructured and needs to be tracked form multiple locations.
So this is all about procedural programming, now lets move to OOPs as we are preparing for the base of OOPs.
---
## Object Oriented Programming Introduction
### OOPS
OOPs came from the need of thinking of software systems in terms of how we humans think about real world.
* Entities are core in OOPs
* Every entity has some attribute and behaviour
In object oriented programming we build the entire program using classes and objects (entity).
**Class:** Blueprint of an idea.
Example - Floor plan of an apartment.
So, while designing new house, we make something called blue print.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/687/original/upload_fd21eec1163e374c6941c99414aa7abf.png?1692719460" width="500"/>
Now this will have exact dimensions as per need. Is the house built? No not yet, but whenever it will get built, the design will be look like this.
**Class represent the strucutre of the idea.**
Class has attributes to define data and methods to define functionalities/behaviour.
Lets build a `Student` class with some attributes and methods.
Its the basic structure, its not a real thing, it just show what data every student holds upto. Also, You can create multiple instances of this class.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/688/original/upload_6d32af9ec0c67eb9779264de5f92beba_%281%29.png?1692719509" width="500"/>
**Object:** They are real instances of the class.
### Question
Will the object of a class occupy memory?
**Choices**
- [ ] No
- [ ] In some cases only
- [x] Yes
Yes they will occupy memory because they are real instance of the class / blueprint.
---
### Classes & Objects Example
Now lets create a class and object and see how this thing works on machine.
1. We will create a class named Student
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/689/original/Screenshot_2023-08-07_145127.png?1692719555" width="500"/>
```java
}
```
2. Then, we will create the main class
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/690/original/Screenshot_2023-08-07_145303.png?1692719596" width="500"/>
3. And we can see that both naman and dinesh have their own identity
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/692/original/Screenshot_2023-08-07_145356.png?1692719666" width="500"/>
---
### Pillars of Object Oriented Programming
Now what is principle and pillar?
* **Principle** - Fundamental foundation / concept.
* **Pillar** - Support to hold things together
**So what does the principle of OOP says?**
Idea of OOP is based on **abstraction** and the whole software system is build around abstraction.
But how would we implement the abstraction? ---> Using the 3 pillars of OOPs i.e.
* **Inheritance**
* **Polymorphism**
* **Encapsulation**
**For example:**
Your **principal** can be:
- I will be a good person.
But how you would be a good person? Here comes your **pillars**:
- I will be truthfull,
- I will do hardwork,
- I respect everyone, etc.
So we got to know that abstraction is not the pillar of OOPs, it is the main principle on which whole concept of OOP is based.
---
### OOPs Abstraction
Abstraction means ---> **Representing in terms of ideas**.
Now what does ideas mean? ---> Anything in software system that has attrubute and associated behaviour.
So if you are building scaler, you don't have to think about storing individuals like, Naman, Anshuman, Indarjeet. You can use Students, Mentors, TAs, Classes, etc. with their attributes.
**Do they have a behaviour?**
Yes they all have some behaviour. Student can send messages, pause courses these are all behaviours.
So abstraction is an idea of representing complex software system interms of ideas, because ideas are easy to understand.
So, its an concept of making something abstract.
### What is the purpose of abstraction?
The main purpose is that others dont need to know the details of the idea.
Suppose you are driving a car, and you want it to turn left and speed up, and you steer the steering to left and press the acceleration pedal. It works right? Do you need to know how does this happen? What combustion is happening, how much fuel is used, How steering wheel turned the car?
No right? This is what we call as abstraction.
Abstraction is way to represent complex software system, in terms of ideas.
What needed to be represented in terms of ideas?
* Data
* Anything that has behaviours
No one else need to know the details about the ideas.
Now let's move to encapsulation.
---
## OOPs Encapsulation
So what are the purpose for making capsules, and not normal medicine?
If the capsule breaks away, what will happen?
- It will flow away. So first purpose is to hold the medicine powder together.
- Then there are multiple powders are present in the capsule, it helps them to avoid mixing with each other.
- Third purpose is it protects the medicine from the outside environment.
This is exactly the purpose of Encapsulation in OOP.
Encapsulation allows us to store attribute and Behaviours together.
### Question
Where do we store attribute and behavious together? What is the technical term for that?
**Choices**
- [x] Class
- [ ] Object
- [ ] Project
Yes, a **class**, and it protects attributes & methods from outer environment i.e. other classes can't have access to it if we restrict.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/686/original/upload_ec5c0fae6db181970a0f3f3e96074b60.png?1692719428" width="500"/>
Here no one can access the age of student other than the class student.
---
## Access Modifiers
We got to know that Encapsulation has two advantages,
* ONE is it holds data and attributes together and
* SECOND is it protect members from illegitimate access. You can't access the data from class unless the class allows you to.
Now, The first thing gets sorted by class, i.e. we create a class, and it holds the behaviors and attributes together.
But, **How the SECOND one is implemented?**
i.e., How in code illegitimate access is prevented?
How the encapsulation prevents access to class data?
That is something called **access modifiers**.
---
### Question
Which one of these is **not** an access modifier?
**Choices**
- [ ] Public
- [x] Open
- [ ] Private
- [ ] Protected
---
### Types of Access Modifiers
There are four access modifiers in most of the programming languages, they are:
* **Public**
* **Private**
* **Protected**
* **Default** (if we don't use any of the above three, then its the default one)
So what are these access modifiers? Let's quickly look at them.
**Public access modifier** - A public attribute or method can be accessed by everyone.
**Private access modifiers** - A private attribute or method can be accessed by no one, not even the child class.
**Explanation** - It can be accessed by the **same** class. No one outside the class has access to private methods.
**Protected access modifier** - A protected attribute or method can be accessed only from the classes of the same package.
Let me show you a diagram that will be helpful in understanding and will clear most of your doubts.
where:<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/697/original/Screenshot_2023-08-06_161609.png?1692721785" width="500"/>
---
### Question
Which is the **most restricted** access modifier?
**Choices**
- [ ] Public
- [ ] Default
- [x] Private
- [ ] Protected
---
### Question
Which is the **most open** access modifier?
**Choices**
- [x] Public
- [ ] Default
- [ ] Private
- [ ] Protected
---
### `this` Keyword
Before we see the example of access modifier, let's understand **"this" keyword**:
* In programming, "this" is a keyword used to refer to the **current instance of a class or object**.
* It's typically used to distinguish between instance variables and local variables or method parameters with the same names, and to access or modify instance members within methods.
* This enhances code clarity and prevents naming conflicts in object-oriented languages like Java and C++.
Here is an example:
```Java
public class Person {
private String name;
public Person(String name) {
this.name = name; // "this" refers to the current instance of the class
}
public void introduceYourself() {
System.out.println("Hello, I am " + this.name); // Using "this" to access the instance variable
}
public static void main(String[] args) {
Person person1 = new Person("Alice");
Person person2 = new Person("Bob");
person1.introduceYourself(); // Output: Hello, I am Alice
person2.introduceYourself(); // Output: Hello, I am Bob
}
}
```
In this example, the "this" keyword is used to differentiate between the instance variable name and the constructor parameter name, ensuring that the correct value is assigned and accessed within the class methods.
---
### Example of Access Modifiers
```Java
package mypackage;
public class AccessModifierExample {
public int publicVariable = 10; // Public access
private int privateVariable = 20; // Private access
protected int protectedVariable = 30; // Protected access
int defaultVariable = 40; // Default (package-private) access
public void publicMethod() {
System.out.println("This is a public method.");
}
private void privateMethod() {
System.out.println("This is a private method.");
}
public static void main(String[] args) {
AccessModifierExample example = new AccessModifierExample();
System.out.println("Public variable: " + example.publicVariable);
System.out.println("Private variable: " + example.privateVariable);
System.out.println("Protected variable: " + example.protectedVariable);
System.out.println("Default variable: " + example.defaultVariable);
}
}
```
```Java
package otherpackage;
import mypackage.AccessModifierExample; // Import the class from a different package
public class AnotherClass {
public static void main(String[] args) {
AccessModifierExample example = new AccessModifierExample();
System.out.println(example.publicVariable); // Accessing publicVariable is valid
System.out.println(example.defaultVariable); // Error: Cannot access defaultVariable from a different package
example.publicMethod();
example.privateMethod(); // Error: Private method is not accessible outside the class
}
}
```
In this example:
The class **AccessModifierExample** has variables and methods with different access modifiers: public, private, protected, and default.
Access modifiers control the visibility and accessibility of members (variables and methods) outside the class.
Public members are accessible from anywhere, private members are only accessible within the class, protected members are accessible within the class and its subclasses, and default members are accessible within the same package.
Now, you can try all these on your machine just by creating classes and accessing them.
---
### `static` Keyword
The **static** keyword in programming languages like Java and C++ is used to declare **class-level members or methods**, which are associated with the class itself rather than with instances (objects) of the class.
1. **Static Variables (Class Variables):** When you declare a variable as "static" within a class, it becomes a class variable. These variables are shared among all instances of the class. They are initialized only once when the class is loaded, and their values are common to all objects of the class.
2. **Static Methods (Class Methods):** When you declare a method as "static," it becomes a class method. These methods are invoked on the class itself, not on instances of the class. They can access static variables and perform operations that don't require access to instance-specific data.
The **static** keyword is often used for utility methods and constants that are relevant at the class level rather than the instance level. It allows you to access these members without creating an object of the class.
Static variable is created when we load a class.
Here is an example:
```Java
public class MyClass {
// Static variable
static int staticVar = 0;
// Instance variable
int instanceVar;
public MyClass(int value) {
this.instanceVar = value;
staticVar++;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(20);
System.out.println("Static Variable: " + staticVar); // Output: Static Variable: 2
System.out.println("Instance Variable (obj1): " + obj1.instanceVar); // Output: Instance Variable (obj1): 10
System.out.println("Instance Variable (obj2): " + obj2.instanceVar); // Output: Instance Variable (obj2): 20
}
}
```
In this example, we have a static variable **staticVar** and an instance variable **instanceVar**. The staticVar is incremented every time an object is created, and we access both static and instance variables directly within the main method.
---
### Scope of a variable
Now let's talk about scope of a variable within a program!
In Java, scope refers to the region or context within your code where a specific variable or identifier is accessible and can be used. The scope of a variable is determined by where it is declared, and it influences its visibility and lifetime within the program.
**There are primarily four types of variable scope in Java:**
1. **Class/Static Scope:** Variables declared as `static` within a class have class-level scope. These variables are associated with the class itself rather than with instances (objects) of the class. They can be accessed using the class name and are shared among all instances of the class.
2. **Instance Scope:** Variables declared within a class but outside any method or constructor have instance scope. These are often referred to as instance variables, and they are associated with specific instances (objects) of the class. Each object has its own copy of these variables.
3. **Method/Local Scope:** Variables declared within a method or a block of code have method or local scope. These variables are only accessible within the specific method or block where they are defined. They go out of scope when the method or block's execution is complete.
4. **Block Scope:** Variables declared within a pair of curly braces `{}` have scope limited to that block. These variables are only accessible within the block in which they are defined.
The scope of a variable is essential for ensuring that the right variables are accessed at the right time and for avoiding naming conflicts. Properly managing variable scope contributes to the clarity and reliability of your code.
Here's a brief example to illustrate variable scope in Java:
```java
public class ScopeExample {
// Class-level variable (static scope)
static int classVar = 10;
// Instance variable (instance scope)
int instanceVar = 20;
public void exampleMethod() {
// Method-level variable (method scope)
int methodVar = 30;
if (true) {
// Block-level variable (block scope)
int blockVar = 40;
System.out.println(classVar + instanceVar + methodVar + blockVar);
}
// The 'blockVar' is out of scope here.
}
public static void main(String[] args) {
ScopeExample obj = new ScopeExample();
obj.exampleMethod();
// The 'methodVar' and 'blockVar' are out of scope here.
}
}
```
In this example, you can see how variables with different scopes are defined and accessed within a Java class.

View File

@@ -0,0 +1,660 @@
# OOPs 2
### Constructors
If you remember, we have studied **classes and objects** in the previous lecture, so what is a class and object? Let's have a quick recap of it.
**Class:** Blueprint of an entity.
**Object:** Instance of class
Now let's look at how a class comes into reality.
Let's define a class named Student.
```java
Student {
String name;
int age;
doubly psp;
}
```
Now, let's make an object of the Student class.
```java
Student st = new Student();
```
Now, from the basics of programming, we all know that to declare a variable, we write:
```java
int a = 12;
```
Let's compare this with object creation:
```java
int a = 12;
Student st = new Student();
```
We can see that **Student** is the Data type here and **st** is a variable name, but
This thing => **Student();** is called a **constructor**, which creates the object of the class.
This thing, when you don't create a constructor, is called a **default constructor**. Let's discuss it in detail.
---
### Default Constructor
If we don't create our own constructor in a class, a **default constructor** is created.
**Default constructor** creates a new object of the class and sets the value of each attribute as the default value of that type.
Examples of default values of datatype:
* **0** for integer,
* **null** for String,
* **0.0** for float, etc.
> **Note:** A default constructor will assign default values only if we haven't assigned values to class attributes while declaring the variable.
So if we are not creating any constructor, then our class is going to make its own constructor.
A default constructor can be assumed to be present like this:
```java
class Student {
String name;
int age;
double psp;
String univName;
Student() {
name = null;
age = 0;
psp = 0.0;
univName = null;
}
}
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/713/original/Screenshot_2023-08-07_091328.png?1692723204" width="400"/>
But,
* By the definition of the default constructor, we know that, **if we create our own constructor** then a default constructor is not created.
So, by looking at Student(), we can say that no parameters are passed here, right?
So, **the default constructors take no parameters**.
**Summarising** the default constructor:
1. Takes no parameter.
2. Sets every attribute of class to it's default value (unless defined).
3. Created only if we don't write our own constructor.
4. It's public i.e. can be access from anywhere.
---
### Manual Constructor
Now, let's create our own constructor using the same `Student` class
```java
public class Student {
String name;
private int age = 21;
String univName;
double psp;
public Student (String studentName, String universityName) {
name = studentName;
univName = universityName;
}
}
```
Let's create a client class.
```java
public class Client {
public static void main(String[] args) {
Student st = new Student(); //ERROR
}
```
But here, why its throwing error?
* Because now there is no default constructor, since we have our own constructor, and it has parameters. So we have to pass the parameters here.
So, let's do like this,
```java
public class Client {
public static void main(String[] args) {
Student st = new Student("Utkarsh", "JIIT");
}
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/715/original/Screenshot_2023-08-07_103207.png?1692723759" width="500"/>
Now, let's move to the copy constructor and learn more about it.
---
### Copy Constructor
Now, **What is a copy constructor?**
Let's say we already have an object of student class, and then we want to create a new object of student that has the exact same values of attributes as older objects.
**For example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/718/original/Screenshot_2023-08-07_113204.png?1692723906" width="500"/>
If `st1` as an object and we need to create one more object `st2`, with the same attribute values, we can do it with the copy constructor.
```java
class Student {
String name;
int age;
Student() {
name = null;
age = 0;
}
Student(Student st) {
name = st.name;
age = st.age;
}
}
```
So basically, to make a copy, we need to pass it as a parameter to the copy constructor, as the data type is Student.
```java
Student st1 = new Student();
st1.name = "Utkarsh";
st1.age = 27;
Student st2 = new Student(st1); // Copy Constructor
```
So now we understand how to write a copy constructor, but what is the use case of the copy constructor?
* The copy constructor comes in use when we have an object, and a newly created object needs the same values, so we don't assign it ourselves. We use the copy constructor the get the work done.
* Some of the attributes may be private and cannot be accessed by the user, but a copy constructor can access it and make the copy itself.
### Question
Is copy constructor same as doing `Student st2 = st1;`?
**Choices**
- [ ] Yes
- [ ] In some cases only
- [x] No
Let's see how do things work internally?
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/728/original/Screenshot_2023-08-07_115214.png?1692725483" width="500"/>
* So we have a memory, and st1 is present in the memory with all the data, as shown in the above diagram.
* When we write student `st2 = st1`, we just make st2 to point as s1, i.e., **a new object is not created**.
* Now the problem here is if we do changes in st2, i.e. `st2.name = 'xyz'`, it will change the value of st1.
Now if we create the object using copy constructor then it has a different address. So it's not pointing in the memory, as we have seen in the example above.
---
### Deep and Shallow copy
### Shallow copy
* When we have created a new object, but behind the scenes, the new object still refer to attributes of the old object. i.e., the new object still refers to the same data as the old copy.
```python
original_books = ["Book A", "Book B"]
shallow_copy_books = original_books
shallow_copy_books.append("Book C")
print(original_books) # Output: ["Book A", "Book B", "Book C"]
```
### Deep copy
* When we have created a new object behind the scenes, the new object do not refer to attributes of the old object. i.e., the new object has no shared data.
```python
import copy
original_books = ["Book A", "Book B"]
deep_copy_books = copy.deepcopy(original_books)
deep_copy_books.append("Book C")
print(original_books) # Output: ["Book A", "Book B"]
```
---
### Inheritance
**How is inheritance represented?**
**Ans** - Inheritance is represented as parent-child relations between different classes.
Now, let's talk about the scaler's hierarchy of representation.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/747/original/Screenshot_2023-08-08_112052.png?1692729330" width="500"/>
Now, Let's say User has the following attributes:
* Username
* Login
So, We can say that:
* Instructor
* Mentor
* TA
* Student
They all are **specific types** of users i.e. they will share all the members / attributes / methods of **User** and may have some more of their own.
A **child class / subclass** can have specific attributes / behaviors which may not be present in the **parent class / superclass**.
>Consider the below diagram for explaining child / subclass & parent / superclass terms more clearly.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/748/original/Screenshot_2023-08-08_113025.png?1692729357" width="500"/>
So we can **conclude**: A child class inherits all the members of the parent class and may or may not add their own members.
---
### Parent-Child Relationship in Code
How can we represent a parent-child relationship in code? Let's say we need to make a relationship between the User and the Instructor.
To build this, Let's say we have a **Parent class called User**, as shown below:
```java
class User {
String userName;
void login() {
...
}
}
```
**Instructor** is a child/subclass of User, so how can we do that?
```java
Class Instructor extends User.
```
So here `extends` is the **keyword in Java** that is used to create a child class.
The `extend` keyword is specific to Java and is used to create a subclass that inherits properties and behaviors from a superclass.
While the keyword itself may vary in other programming languages, the concept is similar. Here are a few examples from different languages:
- **In Python:** The inheritance is indicated using **parentheses**.
For example: `class Subclass(SuperClass):`
- **In C++:** The inheritance is specified using a **colon**.
For example: `class Subclass : public SuperClass { };`
- **In C#:** The inheritance is specified using a **colon**.
For example: `class Subclass : BaseClass { }`
So, while the specific syntax and keywords may differ, the concept of class extension or inheritance is present in various object-oriented programming languages.
The instructor class has the following methods:
```java
class Instructor extends User {
String batchName;
double avgRating;
void scheduleClass() {
...
}
}
```
* Does the Instructor class needs a username property?
* Yes
* Do we need to code it?
* No
* So, how can we use it?
* We are extending it from the User class.
Extends means, **keeping the original things and adding more things to it**.
---
### Constructor Chaining
How do we create an object of any class?
```java
Instructor i = new Instructor();
```
* Did we ever created `Instructor()` constructor?
* No, Right?
* So, how it came into the picture?
* Yes, It is a Default Constructor.
This constructor initializes to default values of all the attributes, so can we do like:
```java
i.username = "Utkarsh";
i.login();
```
Yes, because it's coming from the `User` class.
Can we also do:
```java
i.avgRating = 4
```
Yes, because it's part of the Instructor's class.
**Note:** In Inheritance, a parent class is nothing but generalization, and every child is a specification.
Now, assume we are given this relation:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/752/original/Screenshot_2023-08-08_124458.png?1692729547" width="300"/>
---
### Question
Which of these classes has the highest level of abstraction?
**Choices**
- [x] A
- [ ] B
- [ ] C
- [ ] D
First of all, what is abstraction?
- It's an idea.
So, what does the highest level of abstraction mean?
- A bigger idea that means a more general idea.
So out of them, **A** is the most generic class, right?
That's why **A has the highest level of abstraction.**
---
### Question
Do the child class contains all the attributes of parent class?
**Choices**
- [x] Yes
- [ ] No
- [ ] Can't say
Definitely, **Yes**.
Example is Animal :arrow_right: Dog
So now the question is, how are they initialized? Who initializes them?
Let's see what happens behind the scenes:
* Let's say we have a User class as shown below:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/753/original/Screenshot_2023-08-08_130539.png?1692729576" width="150"/>
And we create a `User` object:
**`User user = new User();`**
So,
How will the attributes get initialized?
**Ans** - Since we haven't created our constructor, our attributes get assigned to null values by default constructor, as shown below.
* <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/754/original/Screenshot_2023-08-08_130908.png?1692729607" width="200"/>
* Or we may create our own constructor:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/755/original/Screenshot_2023-08-08_131123.png?1692729739" width="200"/>
Now, If we create a child class / sub-class named instructor:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/756/original/Screenshot_2023-08-08_131915.png?1692729766" width=250/>
**Now the question is:** When we create an instructor, someone has to initialize the attribute that came from the parent.
There are scenarios now:
1. We know how to initialize, and we understand how to change, so **we will initialize** the values to those attributes, like this:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/757/original/Screenshot_2023-08-08_132224.png?1692729800" width="300"/>
But DO YOU THINK we will always Know how to initialize the attributes?
Ans - **No!** But there is someone who'll always know how and what to initialize.
2. A **constructor of the parent** definitely knows how and what to initialize the attributes. Let's understand How it's done!
---
### Steps to Create an Object of Child
**(Assuiming no constructor is created, its only default constructors are present)**
Suppose we have a class named **A**.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/758/original/Screenshot_2023-08-08_172426.png?1692729822" width="100"/>
Now `B` is a child of `A`,
`C` is a child of `B`, and
`D` is a child of `C.`
Suppose we create an object of **D**:
```java
D d = new D();
```
So, **What really happens when we call `D()`?**
1. Constructor of D will be called.
2. Since D is also a child of someone, so before its execution, it will call the constructor of C.
3. Similarly, C will call the constructor of B first.
4. And B will call the constructor of A before it's execution.
So, **Who's constructor will be finished first?**
- **A**'s constructor will be finished first, then **B** will be finished, then **C** will be finished, then **D** will be finished.
Because,
* **Can a child be born before its parents are born?**
**No**, right?
* That's why the parent class constructor will be called first. We haven't specifically called the parents constructor but by default, the parent constructor is called.
**Note:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/759/original/Screenshot_2023-08-08_180123.png?1692729914" width="500"/>
What will happen if we add a parameterized constructor in class **C** as shown below:
```java
public class C extends B {
C() {
System.out.println("Constructor of C");
}
C(String a) {
System.out.println("Constructor of C with params");
}
}
```
What will be the output if we run the code now?
The output will still be the same right, i.e., `Default Constructor of C` will be printed with all other constructors from A, B & D.
But, What if we want to **print the manual constructor** of class C?
To make this happen, we need to make changes in our **D** class.
We have to add the **super** function in the first line of our constructor.
```java
public class D extends C {
D() {
super ("Hello"); // This must be the first line
System.out.println("Constructor of D");
}
}
```
The **super("Hello");** will make the parametrized constructor from Class C become active.
**Note:** This super() line in the code must be written in the **first line inside a constructor**. Otherwise, it throws an error.
---
## Polymorphism
What really is polymorphism?
There's a very famous explanation of Polymorphism i.e. **Poly means Many** and **Morphism means Form**.
Which means, someone who has multiple forms.
So, till now, in today's class, have you learned about something which had multiple forms?
**Ans** - Yes, a user could have multiple forms. Because a user can be a student, instructor, TA, etc.
So this can be an example of multiple forms.
**Another example** - Suppose we have a list of Animals. Animals have Mammals, Reptiles, Aquatic, etc. classifications.
**Can we write:**
`Animal a = new Dog();`
Yes, because this is an **object of type Dog**, which is a Mammal and which is an Animal. So we can write it!
**But, Can we write:**
`Dog d = new Animal();`
No, this is **not allowed** since every Dog is an Animal, but every Animal must not be a Dog.
**That means: We can put an object of the child class in a variable that takes parent data type.**
**Suppose we have three classes, A, B, and C.** as shown below:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/761/original/Screenshot_2023-08-08_200212.png?1692730048" width="500"/>
Now if we write:
```java
A a = new C();
a.company = "ABC";
```
This will **throw an error** because **a** has a datatype of **A**, but A doesn't have any variable named company.
* Compiler only allows you access to members of the data type of the variable.
Now, suppose you have a method called:
**changePassword()**
* Is this change password method need a Student / TA / Instructor, OR just a user?
* Just a User, right?
Because it doesn't matter which type of user is asking for a changepassword.
=> **The more generic your code is, the better the reusability will be.**
This is one of the use cases of Polymorphism.
There are **two types of polymorphism**:
1. Compile Time Polyphormism
2. RunTime Polymorphism
Now we have seen that one way of having many forms is **Inheritance**. The other is called **Method overloading**.
---
### Method Overloading
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/762/original/Screenshot_2023-08-09_094412.png?1692730077" width="500"/>
Suppose we have a class **A**, and it has a method named `hello()`.
* Can a class have another method with the same name but having different parameters?
* Yes, this second method `hello(String Name)` is having same name.
Now, this is called **Method overloading**.
Here also, can you identify **Polymorphism**?
**Ans** - The same method name has many forms.
So, If we write:
```java
hello();
hello(name);
```
Does the compiler knows which method to call? In each of the statements?
* Yes, It knows. So it will be the respective parameters which matches the method definition.
:arrow_right: As here, the final form that will execute is known to the *Compiler*. That's why it is known as **Compile time Polymorphism**.
Which of the following is a method overloading, and which of them is not?
* <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/763/original/Screenshot_2023-08-09_100541.png?1692730381" width="500"/>
Yes, the first 2 are method overloading, but the last one is not method overloading.
:arrow_right: So there is something called a **Method Signature**.
A method signature is: **`Name of method (Data type of Params)`**
Example: If we have a method:
`void printHello(String Name, int age)`
* Method signature for this method will be:
`printHello(String, int)`
**Methods are known to be overloaded when they have the same name but different signatures.**
---
### Question
Is this allowed in the same class?
```
void printHello(String s) {...}
String printHello(String s) {...}
```
**Choices**
- [ ] Yes
- [x] No
- [ ] Can't say
Since the method signature of both the functions is same, the compiler will not be able to distinguish between the functions and hence will give **compile time error**.
---
### Method overriding
Suppose we have a class **A**,
```java
Class A {
void doSomething(String a) {
...
}
}
```
And we have another class **B** which inherits from **A**, and this class also had a method named `doSometihng`,
```java
Class B extends A {
String doSomething(String c) {
...
}
}
```
So, Is this allowed?
**Ans** - No,
Since all the methods of the parent class are present in the child class, like:
```java
Class B extends A {
String doSomething(String c) {
...
}
// Parent method inherited
void doSomething(String a) {
...
}
}
```
And, in the child class, we are having 2 methods with the same signature which it's not allowed. It's going to give us a **Compile time error**.
Now let's see another scenario of the same classes. But here, the **return type of both methods is going to be the same**.
Suppose we have a class **A**,
```java
Class A {
void doSomething(String a) {
...
}
}
```
And we have another class **B** which inherits from **A**, and this class also had a method named `doSometihng`, like:
```java
Class B extends A {
void doSomething(String c) {
...
}
}
```
If parent and child classes have the same method with the same name and same return type, and the same signature, this is called **Method overriding.**
In Method overriding, the Parent class methods get hidden.
Let's say we have two classes, as shown below:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/767/original/Screenshot_2023-08-09_112752.png?1692731362" width="500"/>
And in the **Main()** method we run the following:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/768/original/Screenshot_2023-08-09_113052.png?1692731390" width="500"/>
So we can see that at first, we have `Hello` as output, and in the last statement, we get `Bye` as output.
Now there are some points that you have to understand:
* The method that is executed is of the data type that is **actually** present at the time of code and **not the type of variable**.
* Do we know the exact code that is about to run in compile time?
* No, and that's why it's called **RunTime polymorphism**
=> ***Compiler relies on the data type of variable, whereas runtime relies on the actual object.***

View File

@@ -0,0 +1,500 @@
# Queues: Implementation & Problems
---
## Queue
A queue represents a linear data structure where items are added at one end and removed from the other end. It follows the "First-In-First-Out" (FIFO) principle, meaning that the item that has been inserted first in queue will be the first one to be removed. To illustrate this concept, let's use a ticket counter as an example.
**Example: Ticket Counter Queue**
Imagine you're at a ticket counter for a popular event, and there are several people waiting in line to purchase tickets. This line of people forms a queue, and the first person who has come in this line will get the ticket first.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/893/original/upload_0dabcb159a39d120faf30f6112ccc7fe.png?1697475336" width=700/>
Common operations in a queue include:
1. **Enqueue**:<br> This operation adds an element to the back (or rear) of the queue. It is also called "push" in some contexts.
2. **Dequeue**:<br> This operation removes and returns the element from the front of the queue. It is also called "pop" in some contexts.
3. **Peek or Front**:<br> This operation allows you to look at the element at the front of the queue without removing it. It is useful for inspecting the next item to be processed.
4. **IsEmpty**:<br> This operation checks if the queue is empty. If it's empty, it means there are no elements in the queue.
5. **Size or Length**:<br> This operation returns the number of elements currently in the queue. It provides the count of items in the queue.
**Q. Can a stack or queue have a limit of elements it can have, and then we can use isFull()?**
**Sol.** Yes, both stacks and queues can have a limit on the number of elements they can hold, and you can use an "isFull()" method to check if they have reached their capacity. This concept is commonly referred to as a "bounded" stack or queue.
---
Implementaion of queue
description: Discussion about the various concepts related to implementaion of queue in detail.
duration: 2100
card_type: cue_card
---
### Implementaion of Queue
Here's how you can implement a queue using a dynamic array along with pseudocode for the `enqueue`, `dequeue`, and `isEmpty` operations:
```sql
Queue using Dynamic Array:
- Initialize an empty dynamic array (e.g., ArrayList or Python list) to store the elements.
- Initialize two pointers: 'front' and 'rear'. Initially, both are set to -1.
Pseudocode for Enqueue (Add an element to the rear of the queue):
enqueue(element):
if rear is -1:
# Empty queue, set both front and rear to 0
set front and rear to 0
else if rear is at the end of the array:
# Check if there is space for expansion
if front > 0:
# Move elements to the beginning of the array
for i from front to rear:
array[i - front] = array[i]
set rear to (rear - front)
set front to 0
else:
# If no space, resize the array by creating a new larger array
new_size = current_array_size * 2 # You can choose your resizing strategy
create a new array of size new_size
copy elements from the current array to the new array
set array to new_array
set rear to (rear - front)
set front to 0
array[rear] = element
increment rear by 1
Pseudocode for Dequeue (Remove an element from the front of the queue):
dequeue():
if front is -1:
# Empty queue, nothing to dequeue
return "Queue is empty"
else:
element = array[front]
increment front by 1
if front > rear:
# Reset front and rear to -1 if the queue is empty
set front and rear to -1
return element
Pseudocode for isEmpty (Check if the queue is empty):
isEmpty():
if front is -1:
return true
else:
return false
```
This pseudocode provides a basic implementation of a queue using a dynamic array. It handles the enqueue and dequeue operations efficiently by resizing the array when necessary to accommodate more elements. The `isEmpty` function checks if the queue is empty by examining the state of the `front` pointer.
### Implementation of Queues using linkedlist
1. **Insert at Head (prepend):**
- **Time Complexity:** O(1)
- **Explanation:** Inserting a node at the head of a singly linked list involves creating a new node, setting its `next` pointer to the current head, and updating the head pointer to the new node. This operation takes constant time because it doesn't depend on the size of the list.
2. **Insert at Tail (append):**
- **Time Complexity:** O(n)
- **Explanation:** To insert a node at the tail of a singly linked list, you typically need to traverse the entire list to find the current tail node. This operation takes linear time since you have to visit each node in the list to reach the end.
3. **Delete at Head:**
- **Time Complexity:** O(1)
- **Explanation:** Deleting a node at the head of a singly linked list is a constant-time operation. You simply update the head pointer to point to the next node in the list.
4. **Delete at Tail:**
- **Time Complexity:** O(n)
- **Explanation:** Deleting a node at the tail of a singly linked list also requires traversing the entire list to find the current tail node. This operation takes linear time since you have to reach the end of the list to perform the deletion.
Queue functionality can be achieved by using two of the methods mentioned:
1. **Insertion at Head and Deletion at tail:**<br> This approach can be used to provide the functionality of queue.Elements are inserted at the head (enqueue operation)with TC O(1) and removed from the tail with TC O(n)(dequeue operation). This ensures that the first element added to the queue is the first one to be removed.
2. **Insertion at Tail and Deletion at Head:**<br> This approach can also be used to create a queue using LinkedList.Elements are inserted at tail with TC O(n) and removed from the head with TC O(1). We can optimise the TC of insertion at tail to O(1) by maintaining a tail pointer and this is why we generally used this approach for queue creation through LinkedList.
---
### Question
What will be the state of the queue after these operations
enqueue(3), enqueue(7), enqueue(12), dqueue(), dqueue(), enqueue(8), enqueue(3)
**Choices**
- [x] 12, 8, 3
- [ ] 3, 7, 12, 8
- [ ] 3, 8, 3
- [ ] 7, 12, 3
**Explanation**
Let's break down the sequence of queue operations:
enqueue(3) : Queue becomes [3]
enqueue(7) : Queue becomes [3, 7]
enqueue(12) : Queue becomes [3, 7, 12]
dequeue() : Removes the element from the front, and the queue becomes [7, 12]
dequeue() : Removes the element from the front, and the queue becomes [12]
enqueue(8) : Queue becomes [12, 8]
enqueue(3) : Queue becomes [12, 8, 3]
So, after these operations, the final state of the queue is [12, 8, 3]
---
### Question
What will be the state of the queue after these operations
enqueue(4), dqueue(), enqueue(9), enqueue(3), enqueue(7), enqueue(11), enqueue(20), dqueue()
**Choices**
- [ ] 4, 9, 3, 7
- [x] 3, 7, 11, 20
- [ ] 9, 3, 7, 11
- [ ] 3, 7, 20
**Explanation**
Let's go through the sequence of queue operations:
enqueue(4): Queue becomes [4]
dequeue(): Removes the element from the front, and the queue becomes empty.
enqueue(9): Queue becomes [9]
enqueue(3): Queue becomes [9, 3]
enqueue(7): Queue becomes [9, 3, 7]
enqueue(11): Queue becomes [9, 3, 7, 11]
enqueue(20): Queue becomes [9, 3, 7, 11, 20]
dequeue(): Removes the element from the front, and the queue becomes [3, 7, 11, 20]
So, after these operations, the final state of the queue is [3, 7, 11, 20]
---
### Implementaion of queue using Stack
The explaination for implementing a queue using two stacks step by step:
```cpp
class QueueUsingTwoStacks {
private:
std::stack<int> stack1; // For enqueue operations
std::stack<int> stack2; // For dequeue operations
```
We define a C++ class called `QueueUsingTwoStacks`. This class has two private member variables: `stack1` and `stack2`. `stack1` is used for enqueue operations, and `stack2` is used for dequeue operations.
```cpp
public:
void enqueue(int value) {
// Simply push the value onto stack1
stack1.push(value);
}
```
The `enqueue` method allows you to add an element to the queue. In this implementation, we simply push the given `value` onto `stack1`, which represents the back of the queue.
```cpp
int dequeue() {
if (stack2.empty()) {
// If stack2 is empty, transfer elements from stack1 to stack2
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
// Pop the front element from stack2 (which was originally at the front of stack1)
if (!stack2.empty()) {
int front = stack2.top();
stack2.pop();
return front;
}
// If both stacks are empty, the queue is empty
std::cerr << "Queue is empty" << std::endl;
return -1; // You can choose a different sentinel value or error handling strategy
}
```
The `dequeue` method allows you to remove and return the front element from the queue. Here's how it works:
- If `stack2` is empty (meaning we haven't yet transferred elements from `stack1` to `stack2`), we perform the transfer. We pop elements from `stack1` and push them onto `stack2`, effectively reversing the order of elements. This is done to ensure that the front element is at the top of `stack2`.
- We then pop the top element from `stack2` (which was originally at the front of the queue) and return it.
- If both `stack1` and `stack2` are empty, we print an error message and return a sentinel value (-1 in this case) to indicate that the queue is empty. You can customize the error handling strategy as needed.
```cpp
bool isEmpty() {
return stack1.empty() && stack2.empty();
}
};
```
The `isEmpty` method checks whether the queue is empty. It returns `true` if both `stack1` and `stack2` are empty, indicating that there are no elements in the queue.
In the `main` function, we create an instance of `QueueUsingTwoStacks`, perform enqueue and dequeue operations, and check if the queue is empty. The example code demonstrates the usage of this queue implementation.
---
### Problem 1 Nth perfect number
Write a function `findNthPerfectNumber(N)` that takes an integer N as input and returns the Nth perfect number formed by the only digits 1 and 2.
**Input:**
- An integer $N (1 <= N <= 1000)$, representing the position of the desired perfect number.
**Output:**
- Return the Nth perfect number formed using only digits 1 and 2.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/898/original/upload_a08c17fcc75c1c2dc3ecf411779a8c36.png?1697475642" width=700/>
**Question Explanation**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/899/original/upload_dbe8b86e3c42650e30c2b95519cd70c2.png?1697475707" width=700/>
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/900/original/upload_fdc14c469a179a938cd303e2a5a159dc.png?1697475746" width=600/>
* As we can see in above example, we have to insert 1 and 2 in the queue.
* The next numbers can be made using the previous digits by appending the combination of 1 and 2.
* Like to get 11 we append 1 after 1, to get 12 we append 2 after 1.
* Similarly, we can generate numbers 21 by appending 1 after 2, and to get the 22, we can append 2 to 2 and so on.
* As we have to append and remove digits frequently so queue can help us here.
---
### Question
What is the **5th** perfect number formed by the only digits 1 and 2.
**Choices**
- [ ] 11111
- [ ] 22222
- [x] 21
- [ ] 12
**Explanation:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/898/original/upload_a08c17fcc75c1c2dc3ecf411779a8c36.png?1697475642" width=700/>
From the image, the 5th Perfect Number is **21**.
---
### Nth perfect number Solution
#### Solution
```javascript
int solve(N) {
if (N <= 2) return N
// Queue ->q
q.enqueue(1) q.enqueue(2)
i = 3
while (i <= N) {
x = q.dequeue()
a = x * 10 + 1
b = x * 10 + 2 //a + 1
if (i == N) return a
if (i + 1 == N) return b
q.enqueue(a)
q.enqueue(b)
i = i + 2
}
}
```
#### Dry Run
To dry run the provided code for N = 10, we'll create a table to keep track of the values of `q` (the queue) and `i` at each step.
```plaintext
| N | q | i | |
|:---:|:----:| --- |:-----------------:|
| 10 | 1, 2 | 3 | // Initial values |
// Loop starts
| N | q | i |
|-------|----------------|-----|
| 10 | 2, 11, 12 | 3 |// Dequeue 1, enqueue 11 and 12
| 10 | 11, 12,21,22 | 5 |// Dequeue 2, enqueue 21 and 22
| 10 |12,21,22,111,112| 7 |// Dequeue 11, enqueue 111 and 112
| 10 |21,22,111,112,121,122| 9 |// Dequeue 12, enqueue 121 and 122
// Now Loop ends at N == 10 , and ans = 122
```
The function dequeues and enqueues values in the queue until `i` reaches `N`. When `i` equals `N`, it returns the current value of `a`. In this case, for `N = 10`, the function returns 112.
#### Complexity
**Time Complexity:** O(n)
**Space Complexity:** O(n)
---
### Doubly Ended Queue
A double-ended queue (deque) is a data structure that allows elements to be added or removed from both ends, making it versatile for various operations. A double-linked list is a common choice for implementing a deque because it provides efficient operations for adding and removing elements from both ends.
Here are some basic operations that are possible with a doubly-ended queue implemented using a double-linked list:
1. **Insertion at Front (push_front)**: Add an element to the front (head) of the deque.
2. **Insertion at Back (push_back)**: Add an element to the back (tail) of the deque.
3. **Removal from Front (pop_front)**: Remove and return the element from the front of the deque.
4. **Removal from Back (pop_back)**: Remove and return the element from the back of the deque.
5. **Front Element Access (front)**: Get the element at the front of the deque without removing it.
6. **Back Element Access (back)**: Get the element at the back of the deque without removing it.
A **double-linked list** is well-suited for implementing a **deque** because it allows for efficient insertions and removals at both ends. Each node in the linked list has pointers to the next and previous nodes, making it easy to manipulate the list in both directions.
---
### Problem 2 Sliding Window Maximum
#### Problem Statement
Given an integer array `A` and an window of size k find the max element.
**Input**
- An integer array `A` and integer `k` .
**Output**
- An integer representing the maximum length of a subarray of `A` in which the average of all elements is greater than or equal to `k`. If no such subarray exists, return 0.
**Example**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/902/original/upload_4c4499c78441c8180afcf468db0c57f4.png?1697475913" width=600/>
#### Question Explanation
Find max elements in 4-element sliding windows of array A:
- `[1, 8, 5, 6]` -> max: 8
- `[8, 5, 6, 7]` -> max: 8
- `[5, 6, 7, 4]` -> max: 7
- `[6, 7, 4, 2]` -> max: 7
- `[7, 4, 2, 0]` -> max: 7
- `[4, 2, 0, 3]` -> max: 4
Result: `[8, 8, 7, 7, 7, 4]`.
1. Initialize an empty list `max_elements`.
2. Iterate from index 0 to 3 (inclusive) to create windows of size 4.
3. Find the maximum element in each window and append it to `max_elements`.
4. Result: `[8, 8, 7, 7, 7, 4]`, representing max elements in each 4-element window in `A`.
---
### Question
Given an integer array `A` and an window of size k find the max element.
A = [1, 4, 3, 2, 5]
k = 3
**Choices**
- [x] [4, 4, 5]
- [ ] [5, 5, 5]
- [ ] [1, 4, 3]
- [ ] [5, 4, 3]
**Explanation:**
Maximum of [1, 4, 3] is 4
Maximum of [4, 3, 2] is 4
Maximum of [3, 2, 5] is 5
So, `[4, 4, 5]` is the answer.
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Sliding Window Maximum Approaches
#### Brute Force Approach
Brute-force approach to find max element in a window of size `k` in array `A` involves iterating through windows, finding max within each, and storing results. Time complexity: **O(n * k)** and space complexity: **O(1)**.
#### Dry Run using the Sliding Window Approach
Array `A = [1, 8, 5, 6, 7, 4, 2, 0, 3]` and `k = 4`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/903/original/upload_c51f03fd7ab32785b5087c21a5d907e3.png?1697475979" width=700/>
Let's dry run the code with the given example:
Array `A = [1, 8, 5, 6, 7, 4, 2, 0, 3]` and `k = 4`.
1. Initialize an empty queue `q`.
2. Start iterating through the array elements.
- **For i = 0, A[i] = 1:**
- Queue `q` is empty, so nothing happens.
- Enqueue `i` at the rear of the queue. `q = [0]`.
- **For i = 1, A[i] = 8:**
- The front element of the queue is at index `0`, which is smaller than the current element and thus can't be the maximum for any window.
- Deque the element and Enqueue `i` at the rear of the queue. `q = [1]`.
- **For i = 2, A[i] = 5:**
- `q` is not empty, and `A[r]` (element at index `1`) is greater than `A[i]`, so we don't do anything.
- Enqueue `i` at the rear of the queue. `q = [2]`.
- **For i = 3, A[i] = 6:**
- `q` is not empty, and `A[r]` (element at index `2`) is smaller than `A[i]`, so we deque it, now 8 is greater than 6 so don't do anything.
- Enqueue `i` at the rear of the queue. `q = [3]`.
**After the first K insertions, the q = [8,6];
Now the maximum of this window is present in the front so print it and slide the window.
To slide the window, check if A[i - k] is present in front, if yes then dequeue it. Add the next element to slide the window**
- Continue this process for the remaining elements.
3. The final output will be the maximum elements in each group of size `k`:
- For `k = 4`, the maximum elements are `[8, 8, 7, 7, 4, 2, 3]`.
So, the dry run demonstrates how the code finds and prints the maximum elements in groups of size `k` as it iterates through the array.
#### Pseudocode (Using Dequeue)
```javascript
function findMaximumInGroups(A, k):
Initialize an empty queue q
n = length(A) // Total number of elements in the array A
for i from 0 to k - 1:
while (!q.isEmpty() and A[i] >= A[q.rear()]):
q.dequeueRear() // Remove elements that are smaller than A[i]
q.enqueueRear(i) // Add the current element to the queue
print A[q.front()] // Print the maximum element in the current group
// Slide for next windows
for i from k to n - 1:
if (!q.isEmpty() and q.front() == i - k):
q.dequeueFront() // Remove elements that are outside the current window
while (!q.isEmpty() and A[i] >= A[q.rear()]):
q.dequeueRear() // Remove elements that are smaller than A[i]
q.enqueueRear(i) // Add the current element to the queue
print A[q.front()] // Print the maximum element in the last group
# Example usage:
A = [1, 8, 5, 6, 7, 4, 2, 0, 3]
k = 4
findMaximumInGroups(A, k)
```
#### Complexity
**Time Complexity:** O(n)
**Space Complexity:** O(n)

View File

@@ -0,0 +1,374 @@
# Recursion 1
---
## Introduction to Recursion
### Definition
1. See this video - [LINK](https://www.youtube.com/watch?v=-xMYvVr9fd4)
2. Function calling itself.
3. A problem is broke into smaller problem(subproblem) and the solution is generated using the subproblems.
**Example**
Here's an example of how recursion can be used to calculate the sum of the first **N** natural numbers:
```cpp
sum(N) = 1 + 2 + 3 + 4 + ..... + N-1 + N
sum(N) = sum(N-1) + N
```
Here, **sum(N-1)** is smaller instance of same problem that is **sum(N)**.
sum(N-1) is known as a subproblem.
### How to write a recursive code?
We can solve any recursive problem using below magic steps:
1. **Assumptions:** Decide what the function does for the given problem.
2. **Main logic:** Break the problem down into smaller subproblems to solve the assumption.
3. **Base case:** Identify the inputs for which we need to stop the recursion.
---
## Function Call Tracing
* Function call tracing involves tracing the sequence of function calls that are made when a program is executed.
* It involves keeping track of the function calls, their arguments, and the return values in order to understand the flow of the program and how the functions are interacting with each other.
### Example:
We have the following code:
```cpp
int add(int x, int y) {
return x + y;
}
int mul(int x, int y, int z) {
return x * y * z;
}
int sub(int x, int y) {
return x - y;
}
void(int x) {
cout << x << endl;
}
int main() {
int x = 10;
int y = 20;
print(sub(mul(add(x, y), 30), 75));
return 0;
}
```
Here are the steps involved in function call tracing of the above code:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/896/original/Screenshot_2023-05-22_at_9.21.01_PM.png?1684771032" alt= “” width="350" height="400">
* We start with the call to **sub(mul(add(10, 20), 30), 75)**.
* That called: **mul(add(10, 20), 30)**.
* That called: **add(10, 20)**.
* add will return **10+20 = 30** to **mul** function.
* mul will return **30*30 = 900** to **sub** function.
* sub will return **900-75 = 825** to print function.
### Data structure involved in function calls
* We need to store calling function so that we can come back to it once answer of the called function has been evaluated.
* **Stack Data Structure** is used to store function calls, their arguments, and return values.
* In recursion, stack is called "call stack" and is used by the program to keep track of function calls in progress.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/383/original/Screenshot_2023-05-02_at_3.13.05_PM.png?1683043955" alt= “” width="600" >
---
### Problem 1 : Factorial of N
Given a positive integer N, find the factorial of N.
### Question
If N = 5, find the factorial of N.
**Choices**
- [ ] 100
- [x] 120
- [ ] 150
- [ ] 125
**Solution**
**Assumptions:** Create a function which -
* takes an integer value `N` as parameter.
* calculates and returns N!.
* return type should be integer.
**Main logic:**
* The factorial of N is equal to N times the factorial of (N-1)
* We made assumption that sum(N) calculates and return factorial of N natural number. Similarly, sum(N-1) shall calculate and return the factorial of N-1 natural number.
`factorial(N) = N * factorial(N-1)`
**Base case:** The base case is when N equals 0, i.e., `0! = 1`
For example,
When we perform, `factorial(N) = N * factorial(N-1)`, value of N keeps on decreasing by 1.
`N -> (N-1) -> (N-2) ........ 2 -> 1`
for N = 1 as well as 0, the factorial is 1.
So, we can write base case for N = 0 which will also cover for N = 1.
#### Pseudocode
```cpp
int factorial(int N) {
// base case
if (N == 0) {
return 1;
}
// recursive case
return N * factorial(N - 1);
}
```
### Dry Run
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/805/original/Screenshot_2023-10-08_at_6.50.26_PM.png?1696771237" width="350" />
---
### Problem 2 : Nth number in the Fibonacci Series
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers.
The sequence goes like this:
| N | 0 | 1 | 2 | 3 | 4 | 5 |....|
|---|---|---|---|---|---|---|---|
| Fibonacci(N) | 0 | 1 | 1 | 2 | 3 | 5 |....|
Given a positive integer N, write a function to compute the Nth number in the Fibonacci sequence using recursion.
**Example**
```cpp
Input = 6
Output = 8
```
**Explanation:**
| N | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Fibonacci(N) | 0 | 1 | 1 | 2 | 3 | 5 | 8 |
Fibonacci(6) = Fibonacci(5) + Fibonacci(4) = 3 + 5 = 8.
---
### Question
If N = 7, find the Nth number in the fibonacci sequence.
**Choices**
- [ ] 8
- [ ] 5
- [x] 13
- [ ] 10
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Nth number in the Fibonacci sequence Solution
#### Solution
**Assumptions:** Create a function which -
* takes an integer value `N` as parameter.
* calculates and returns Nth number in the fibonacci sequence.
* return type should be integer.
**Main logic:** Recursively compute the (N-1)th and (N-2)th numbers in the sequence and add them together to get the nth number.
`fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2)`
**Base case:** If N is 0 or 1, return the corresponding value in the Fibonacci sequence.
* Since, according to the definition of fibonacci sequence, the smallest two possible values of N are `N = 1` & `N = 2`, therefore, stop recursion as soon as N becomes 0 or 1.
#### Pseudocode
```cpp
int fibonacci(int N) {
// base case
if (N == 0 || N == 1) {
return N;
}
// recursive case
return fibonacci(N - 1) + fibonacci(N - 2);
}
```
#### Function Call Tracing
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/890/original/Screenshot_2023-05-22_at_8.05.10_PM_%281%29.png?1684766319" alt= “” width="500" height="500">
---
### Time Complexity of Recursion - using Recurrence Relation
**Factorial(N)**
#### Pseudocode
```cpp
int factorial(int N) {
// base case
if (N == 0) {
return 1;
}
// recursive case
return N * factorial(N - 1);
}
```
* Let's assume that time taken to calculate **factorial(n)** = **T(n)**.
* **factorial(n)** depends on the time taken by **factorial(n-1)** and other than that, constant work is being performed.
* Time taken by **factorial(n-1) = T(n-1) + O(1)**.
* Therefore, for the sum of digits, the recursive relation will be defined as follows:
#### Equation 1
```
T(n) = T(n-1) + 1
```
**1** is added because other than function calls, a constant amount of work is being done.
Substituting the value of ```T(n-1) = T(n-2) + 1```
#### Equation 2
```
T(n) = T(n-2) + 2
```
Substituting the value of ```T(n-2) = T(n-3) + 1```
#### Equation 3
```
T(n) = T(n-3) + 3
```
Substituting the value of ```T(n-3) = T(n-4) + 1```
#### Equation 4
```
T(n) = T(n-4) + 4
```
After say **k** iterations, we shall reach to the base step.
The equation will be:
#### Equation 5
```
T(n) = T(n-k) + k
```
The base case shall take constant time:
```
T(0) = O(1)
```
We shall substitute the value of **n - k = 0**
```
=> n - k = 0
=> n = k
```
Put the above value in a generalized equation, we get
```
T(n) = T(0) + n
T(n) = 1 + n
T(n) = O(n)
```
Hence we can say that.
```
T(n) = O(n)
```
---
### Time Complexity of Fibonacci
#### Pseudocode
```cpp
Function fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
```
Recurrence Relation is:
```
T(n) = T(n-1) + T(n-2)
```
For easy calculation, we can write the recurrence relation as follows:
```
T(n) = 2 * T(n-1)
```
It will evaluate to **O(2<sup>N</sup>)**
>Note to Instructor: Please evaluate above recurrence relation in class.
### Another definition of Time Complexity
Time Complexity can also be defined as
**Time taken in a single function call * Number of function calls**
---
### Question
How many recursive calls in the factorial(6)?
Choose the correct answer
**Choices**
- [ ] 0
- [ ] 2
- [x] 6
- [ ] 10
---
### Space Complexity of Recursive Code
The space complexity of recursion refers to the amount of memory required by a recursive algorithm as it executes. It is determined by the maximum amount of memory needed on the call stack at any given point during the recursion.
### Space Complexity of factorial(N)
Total N call will be stored in the stack.
```
factorial(1)
factorial(2)
---------------
---------------
---------------
factorial(N-1)
factorial(N)
```
Maximum stack space used is N, hence space is O(N)
Hence, total O(N) space is required to execute all the recursive calls.
### Space complexity of fibonacci(n)
If the time complexity of our recursive Fibonacci is O(2^n), whats the space complexity?
***Tempted to say the same?***
> NOTE to Instructor: Show it using a stack
**SPACE COMPLEXITY** can also be calculated using **RECURSIVE TREE**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/163/original/fibonacci.png?1706036608" width=500/>
>Please Note: This tree is known as Recursive Tree.
Space complexity is the amount of memory used by the algorithm.
When a function is called, it is added to the stack.
When a function returns, it is popped off the stack.
Were not adding all of the function calls to the stack at once.
We only make n calls at any given time as we move up and down branches.
We proceed branch by branch, making our function calls until our base case is met, then we return and make our calls down to the next branch.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/164/original/fibnocci_compexity.png?1706036686" width=500/>
We can also define **Space Complexity** as **height of the Recursive Tree**.
---
### Question
What is the height of tree for fibonacci(6) ?
Choose the correct answer
**Choices**
- [ ] 0
- [ ] 7
- [x] 6
- [ ] 8

View File

@@ -0,0 +1,547 @@
# Recursion 2
## Question
What is the output of the following code for N = 3?
```cpp
void solve(int N){
if(N == 0)
return;
solve(N-1);
print(N);
}
```
**Choices**
- [x] 1 2 3
- [ ] 0 1 2
- [ ] 2 1 0
- [ ] 3 2 1
```cpp
void solve(int N) {
if (N == 0)
return;
solve(N - 1);
print(N);
}
```
N=3
1. So first of all, solve(3) is called,
1. Then solve(3) will first call for solve(2) as n!=0,
1. Similarly, solve(2) calls for solve(1), and then solve(1) calls for solve(0).
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/184/original/Screenshot_2023-10-10_at_5.32.03_PM.png?1696939587" width="150" />
Now n==0 so return.
Then solve(1) will print 1, then it will return, and after that solve(2) will print 2, in this way 1, 2, 3 will be printed as an output.
---
### Question
What is the output of the following code for N = 3?
```cpp
void solve(int N){
if(N == 0)
return;
print(N);
solve(N-1);
}
```
**Choices**
- [ ] 1 2 3
- [ ] 0 1 2
- [ ] 2 1 0
- [x] 3 2 1
```cpp
void solve(int N){
if(N == 0)
return;
print(N);
solve(N-1);
}
```
N=3
1. So first of all, solve(3) is called,
1. Then solve(3) will first **print 3**, then call for solve(2) as n!=0,
1. In this way solve(2) first **print 2**, then call for solve(1), and then solve(1) will **print 1**, then call for solve(0).
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/184/original/Screenshot_2023-10-10_at_5.32.03_PM.png?1696939587" width="150" />
Now n==0 so return.
Then solve(1) will return, after that solve(2) will return.
In this way 3, 2, 1 will be printed as an output.
---
### Question
What is the output of the following code for N = -3?
```cpp
void solve(int N){
if(N == 0)
return;
print(N);
solve(N-1);
}
```
**Choices**
- [ ] -3 -2 -1
- [ ] 3 2 1
- [x] Error; Stack Overflow
- [ ] 1 2 3
```cpp
void solve(int N){
if(N == 0)
return;
print(N);
solve(N-1);
}
```
`N = -3`
In this question we will never reach 0, that's why we are getting stack overflow.
At first solve(-3) is called, then it will print -3
call for solve(-4), then it will print -4
call for solve(-5), in this way, it will keep making calls infinitely, as we will not reach zero, hence stack overflow error occurs.
---
## Problem 1 Power Function
**Problem Statement**
Given two integers **a** and **n**, find **a<sup>n</sup>** using recursion.
**Input**
```
a = 2
n = 3
```
**Output**
```
8
```
**Explanation**
2<sup>3</sup> i.e, 2 * 2 * 2 = 8.
:::warning
Please take some time to think about the recursive approach on your own before reading further.....
:::
#### Brute Force Approach
The above problem can be redefined as:
```
a ^ n = a * a * a......* a (n times).
```
The problem can be broken into subproblem as:
```
a ^ n = a ^ (n-1) * a
```
So we can say that pow(a,n) is equivalent to
```
pow(a,n) = pow(a,n-1) * a
```
Here, pow(a,n) is the defined as `a^n`.
We have seen how the problem is broken into subproblems. Hence, it can be solved using recursion.
Below is the algorithm:
* Assumption step:
* Define a recursive function pow(a,n).
* Main Logic:
* Define a recursive case: if **n** > 0, then calculate the pow(a,n-1).
* Return a * pow(a,n-1).
* Base Case:
* Base condition: if **n** = 0, then return 1.
#### Pseudocode
```cpp
function pow(int a, int n) {
if (n == 0) return 1;
return a * pow(a, n - 1);
}
```
#### Complexity
We shall calculate Time Complexity at the end.
---
### Power Function Optimized Approach 1
We can also divide pow(a, n) as follows:
if **n** is even:
```
pow(a,n) = pow(a,n/2) * pow(a,n/2)
```
if **n** is odd:
```
pow(a,n) = pow(a,n/2) * pow(a,n/2) * a
```
#### Recursion Steps:
* Assumption Step:
* Define a recursive function pow(a,n).
* Main Logic:
* if n is odd, then return pow(a,n/2) * pow(a,n/2) * a.
* else return pow(a,n/2) * p(a,n/2).
* Base Condition:
* if **n** is equal to 0, then return 1.
#### Pseudocode
```cpp
Function pow(int a, int n) {
if (n == 0) return 1;
if (n % 2 == 0) {
return pow(a, n / 2) * pow(a, n / 2);
} else {
return pow(a, n / 2) * pow(a, n / 2) * a;
}
}
```
The above function will have more time complexity due to calling the same function twice. We will see it while calculating Time Compleixity.
---
### Time Complexity of Power Function
#### Pseudocode
```cpp
Function pow(int a, int n) {
if (n == 0) return 1;
if (n % 2 == 0) {
return pow(a, n / 2) * pow(a, n / 2);
} else {
return pow(a, n / 2) * pow(a, n / 2) * a;
}
}
```
Let Time taken to calculate pow(a,n) = f(n).
```
T(n) = 2 * T(n/2) + 1
```
Substituting the value of T(n/2) = 2 * T(n/4) + 1
```
T(n) = 2 * [2 * T(n/4) + 1] + 1
= 4 * T(n/4) + 3
= 2^2 * T(n/2^2) + (2^2 - 1)
```
Substituting the value of T(n/4) = 2 * T(n/8) + 1
```
T(n) = 4 * [2 * T(n/8) + 1] + 3
= 8 * T(n/8) + 7
= 2^3 * T(n/2^3) + (2^3 - 1)
```
Substituting the value of T(n/8) = 2 * T(n/16) + 1
```
T(n) = 8 * [ 2 * T(n/16) + 1] + 7
= 16 * T(n/16) + 15
= 2^4 * T(n/2^4) + (2^4 - 1)
```
After, say, **k** iterations, we shall reach the base step.
The equation will be:
```
T(n) = 2^k * T(n/2^k) + (2^k - 1)
```
The base case shall take contant time:
```
T(0) = O(1) or T(1) will also be constant
```
```
n/(2 ^ k) = 1
n = 2^k
k = log2(n)
```
Hence we can say that
```
T(n) = n * T(1) + (n - 1)
= O(n)
```
Let's see time complexity of the optimised pow function.
---
### Power Function Optimized Approach - Fast Power
In above approach, we are calling function **pow(a, n/2)** twice. Rather, we can just call it once and use the result twice.
Below is the algorithm:
* Assumption Step:
* Define a recursive function **pow(a,n)**.
* Main Logic:
* Calculate **pow(a,n/2)** and store it in a variable **p**.
* if n is odd, then return **p * p * a**.
* else return **p * p**.
* Base Condition:
* if **n = 0**, then return **1**.
#### Pseudocode
```cpp
Function pow(int a, int n) {
if (n == 0) return 1;
int p = pow(a, n / 2);
if (n % 2 == 0) {
return p * p;
} else {
return p * p * a;
}
}
```
> Note: The above function is known as Fast Power or Fast Exponentiation.
---
### Time Complexity of Fast Power
#### Pseudocode
```cpp
Function pow(int a, int n) {
if (n == 0) return 1;
long p = pow(a, n / 2);
if (n % 2 == 0) {
return p * p;
} else {
return p * p * a;
}
}
```
Let time taken to calculate pow(a,n) = f(n).
Recurrence Relation is:
```
T(n) = T(n/2) + 1
```
Substituting the value of T(n/2) = T(n/4) + 1
```
T(n) = [T(n/4) + 1] + 1
= T(n/4) + 2
```
Substituting the value of T(n/4) = T(n/8) + 1
```
T(n) = [T(n/8) + 1] + 2
= T(n/8) + 3
```
Substituting the value of T(n/8) = T(n/16) + 1
```
T(n) = [T(n/16) + 1] + 3
= T(n/16) + 4
```
After say **k** iterations, we shall reach to the base step.
The equation will be:
```
T(n) = T(n/2^k) + k
```
Base case shall take constant time:
```
T(0) = O(1) or T(1) will also be constant
```
```
n/(2 ^ k) = 1
n = 2^k
k = log2(n)
```
Hence we can say that
```
T(n) = T(1) + log2(n)
= O(log2(n))
```
---
### Question
How many recursive call in the FAST pow(2,5)?
Choose the correct answer
**Choices**
- [ ] 0
- [ ] 2
- [x] 4
- [ ] 5
This is ~ log N calls.
Therefore, time complexity of sum of digits = O(log N) * 1 = O(log N)
---
### Space Complexity of pow(a,n)
There are total **log2(N)** recursive calls as shown below:
```
pow(a,0)
pow(a,1)
pow(a,2)
pow(a,4)
---------------
---------------
---------------
sumofdigits(a,N/2)
sumofdigits(a,N)
```
Hence, the total O(log2(N)) space required to execute all the recursive calls.
---
### Problem 2 Tower of Hanoi
There are n disks placed on tower A of different sizes.
**Goal**
Move all disks from tower A to C using tower B if needed.
**Constraint**
- Only 1 disk can be moved at a time.
- Larger disk can not be placed on a small disk at any step.
Print the movement of disks from A to C in minimum steps.
**Example 1**
**Input:** N = 1
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/185/original/Screenshot_2023-10-10_at_5.32.25_PM.png?1696939687" width="500" />
**Explanation:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/187/original/Screenshot_2023-10-10_at_5.32.32_PM.png?1696939777" width="500" />
**Output:**
1: A -> C
**Example 2**
**Input:** N = 2
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/188/original/Screenshot_2023-10-10_at_5.32.40_PM.png?1696939808" width="500" />
**Explanation:**
1: A -> B
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/190/original/Screenshot_2023-10-10_at_5.32.50_PM.png?1696939875" width="500" />
2: A -> C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/192/original/Screenshot_2023-10-10_at_5.32.57_PM.png?1696939912" width="500" />
1: B -> C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/193/original/Screenshot_2023-10-10_at_5.33.04_PM.png?1696939944" width="500" />
**Output:**
1: A -> B
2: A -> C
1: B -> C
**Example 3**
**Input:** N = 3
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/198/original/Screenshot_2023-10-10_at_5.34.12_PM.png?1696940309" width="500" />
**Explanation:**
1: A -> C
2: A -> B
1: C -> B
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/199/original/Screenshot_2023-10-10_at_5.33.19_PM.png?1696940471" width="500" />
3: A -> C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/202/original/Screenshot_2023-10-10_at_5.33.27_PM.png?1696940631" width="500" />
1: B -> A
2: B -> C
1: A -> C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/203/original/Screenshot_2023-10-10_at_5.33.34_PM.png?1696940669" width="500" />
**Output:**
1: A -> C
2: A -> B
1: C -> B
3: A -> C
1: B -> A
2: B -> C
1: A -> C
#### n disks
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/204/original/Screenshot_2023-10-10_at_5.33.41_PM.png?1696940720" width="500" />
**Step 1:**
Move (n-1) disks from A to B
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/205/original/Screenshot_2023-10-10_at_5.33.48_PM.png?1696940764" width="500" />
**Step 2:**
Move n disk to C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/206/original/Screenshot_2023-10-10_at_5.33.55_PM.png?1696940798" width="500" />
**Step 3:**
Move (n-1) disks from B to C
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/207/original/Screenshot_2023-10-10_at_5.34.03_PM.png?1696940834" width="500" />
#### Pseudocode
```cpp
src temp dest
void TOH(int n, A, B, C){
1. if(n == 0)
return;
2. TOH(n - 1, A, C, B); // move n-1 disks A->B
3. print(n : A -> C); // moving n disk A->C
4. TOH(n - 1, B, A, C); // move n-1 disks B->C
}
```
#### Dry Run
**n = 3**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/198/original/Screenshot_2023-10-10_at_5.34.12_PM.png?1696940309" width="500" />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/208/original/Screenshot_2023-10-10_at_5.35.05_PM.png?1696941053" width="450" />
**Output:**
1: A -> C
2: A -> B
1: C -> B
3: A -> C
1: B -> A
2: B -> C
1: A -> C
#### Time Complexity
It can be observed in terms of number of steps taken for N
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/160/original/Screenshot_2023-10-10_at_2.30.48_PM.png?1696928475" width="500" />
#### Space Complexity
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/161/original/Screenshot_2023-10-10_at_2.33.36_PM.png?1696928627" width="500" />

View File

@@ -0,0 +1,488 @@
# Searching 1: Binary Search on Array
---
### Introduction to Searching - Story
* Let us say you lost something
* When you go to the police, you tell them what to search for—the target—and where to search—the search space.
* It is easy to look for a word in the dictionary as compared to searching for a word in a book or newspaper. This is because along with the target element, we also have defined search space(alphabetical order).
* In the Phone book as well, we have names sorted in the contacts list, so it's easier to find a person's number.
* **Search space** - The area where we know the result exists and we search there only
* **Target** - The item we are looking for
* **Condition** - Some condition to discard some part of the search space repeatedly to make it smaller and finally reach the result.
* **Binary Search** - divide the search space into two parts and repeatedly keep on neglecting one-half of the search space.
---
### Question
In binary search, at each step, the search range is typically:
**Choices**
- [x] Halved
- [ ] Tripled
- [ ] Doubled
- [ ] Reduced by one
---
## Binary Search
### Binary Search Question
Given a sorted array with distinct elements, search the index of an element **k**, if k is not present return -1.
arr[] =
| 3 | 6 | 9 | 12 | 14 | 19 | 20 | 23 | 25 | 27 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
#### Brute Force Approach - Linear Search
* We can traverse the array and compare each element with the target element. This is done until we find the target element or all the elements of the array are compared. This method is called linear search and the time complexity in the worst case is **O(N)** where **N** is the number of elements in the array.
* We can perform the same operation with less number of comparisons and with better time complexity using Binary Search as the array is sorted.
#### Binary Search Approach
* Binary search has three elements,
* **Search space -** array
* **target -** we are given a target element to be found from the array
* **condition ->**
* array is sorted, say I am at some random position, if I compare the current element with the target element.
* If `current_element > target_element`, I can discard all the element appearing before current element and the target_element as they will always be smaller than current element.
* Similarly, if the `current_element < target_element`, the target element and the elements appearing after it can be discareded.
* We have all the three elements and thus, binary search can be easily applied to it.
* Let us take the middle index.
* if `arr[mid] == k`, i.e. we found the target, we return the index of the target.
* if `arr[mid] < k` i.e. the target exists on the right side of the array so the left half is of no use and we can move to the right.
* Similarly, if `arr[mid] > k` i.e. the target exists on the left, and the right half can be discarded.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/908/original/upload_806379972b851dba6e99f692192ada2a.png?1696270159" width=400/>
#### Dry Run
Let us dry run binary search for the array:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |8 | 9 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 3 | 6 | 9 | 12 | 14 | 19 | 20 | 23 | 25 | 27 |
**First Iteration:**
* low = 0, high = 9
* <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/947/original/Screenshot_2023-10-03_013123.png?1696276895" width=200 />
* arr[4] (14) > target (12) (Since 14 already is larger and array is sorted, so all the elements to the right of mid will be even larger, hence, we should move left.)
* go left -> high = mid - 1 = 3
**Second Iteration:**
* low = 0, high = 3
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/921/original/Screenshot_2023-10-03_000324.png?1696271619" width="200"/>
* arr[1] (6) < target (12)
* go right -> left = mid + 1 = 2
**Third Iteration:**
* low = 2, high = 3
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/922/original/Screenshot_2023-10-03_000452.png?1696271699" width="200"/>
* arr[2] (9) < target (12)
* go right -> left = mid + 1 = 3
**Fourth Iteration:**
* low = high = 3 = mid
* arr[3] (12) == target (12)
* break;
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/910/original/upload_1362cf448b060b8063fdf490450a9b14.png?1696270530" width="500"/>
* Dry run for target element not present, let's say **11**.
#### Binary Search Pseudo Code
```javascript
int search(int arr[], int N, int k) {
lo = 0, hi = N - 1;
while (lo <= hi) {
mid = lo + (hi + lo) / 2;
if (arr[mid] == k) {
return mid;
} else if (arr[mid] < k) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
```
#### Complexity
**Time Complexity:** O(log N)
**Space Complexity:** O(1)
---
### Question
If the element 'k' is found in a sorted array, what will be the time complexity of binary search?
**Choices**
- [ ] O(1)
- [x] O(log n)
- [ ] O(n)
- [ ] O(n^2)
---
### Best Practices - Binary Search
* Some write the formula of mid calculation as <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/912/original/Screenshot_2023-10-02_235404.png?1696271055" width=80 /> but it is incorrect, as in some cases it may lead to overflow.
* e.g, Let us assume that maximum number stored by a particular data type is `100` (It's Integer.Max_Int but just to make maths easy, assuming its 100), and the number of elements in the array is `100` for which last index will be `99` for zero indexing and thus, is in the limit.
* There is the posibility that the target element is at the position `98` and value of `low = 98` and `high = 99`. When we calculate `mid` for this scenario, the `high` and the `low` are in limits but while calculating the mid <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/915/original/Screenshot_2023-10-02_235615.png?1696271183" width="100"/> first the sum `197` will be calculated and stored. This will cause the overflow as the limit of the variable is `100` only(assumption).
* This may result in incorrect or negative value.
* Whereas, when we write <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/916/original/Screenshot_2023-10-02_235725.png?1696271253" width="100"/> we will get <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/917/original/Screenshot_2023-10-02_235917.png?1696271365" width="100"/> which even in the worst case be `99` and will not overflow.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/918/original/upload_8464c14ddc9d5166e7118e05dcbfdc72.png?1696271394" width="500"/>
---
### Identify 2024's First Email
All emails in your mailbox are sorted chronologically. Can you find the first mail that you received in 2024?
---
### Binary Search Problems - Find first occurrence
Given a sorted array of N elements, find the first occurrence of the target element.
arr[] =
| -5 | -5 | -3 | 0 | 0 | 1 | 1 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 8 | 10 | 10 | 15 | 15 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
For `5` first occurence is at index `7` so we have to return `7`.
* Brute force approach is linear search.
* Now the array is sorted so using binary search we can find at least one of the occurences of the given target element.
* The challenge is to **find the first occurence**. What we know about the first occurence is that it is always going to be the current position or in the left.
* Now in left, we can do linear search but in worst it will take about O(N) time complexity.
* What we have got is the potential answer, it can or cannot be final anser.
* We can store the current position in a variable, in case it is the first occurence. Next, we can apply binary search in the left side of the array.
* The only change we are required to make is to not stop if we find the target element instead keep looking in the left side of the array until `low > high`.
* If the `mid == target` store mid, go left.
* else if `mid > target` go right.
* else go left.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/919/original/upload_197946be7b82c2dc88b9782077ab3534.png?1696271433" width="500"/>
#### Dry run for the example
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/920/original/upload_5ed94acbbf1929375865577543628202.png?1696271490" width="500"/>
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| -5 | -5 | -3 | 0 | 0 | 1 | 1 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 8 | 10 | 10 | 15 | 15 |
**First Iteration:**
* low = 0, high = 18
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/923/original/Screenshot_2023-10-03_000719.png?1696271848" width="150"/>
* arr[9] (5) == target (5)
* ans = 9
* go left -> high = mid - 1 = 8
**Second Iteration:**
* low = 0, high = 8
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/924/original/Screenshot_2023-10-03_000803.png?1696271891" width="150"/>
* arr[4] (0) < target (5)
* go right -> left = mid + 1 = 5
**Third Iteration:**
* low = 5, high = 8
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/925/original/Screenshot_2023-10-03_001246.png?1696272175" width="150"/>
* arr[6] (1) < target (5)
* go right -> left = mid + 1 = 7
**Fourth Iteration:**
* low = 7, high = 8
* the mid = <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/926/original/Screenshot_2023-10-03_001415.png?1696272264" width="150"/>
* arr[7] (5) == target (5)
* go left -> high = mid - 1 = 6
* break;
---
### Question
When searching for the first occurrence of an element in a sorted array, what should you do if the current element matches the target 'k'?
**Choices**
- [ ] Return the current index
- [ ] Continue searching in the right subarray
- [x] Continue searching in the left subarray
- [ ] Stop searching immediately
---
### Question
What is the time complexity of finding the first occurrence of an element in a sorted array using binary search?
**Choices**
- [x] O(log n)
- [ ] O(n)
- [ ] O(1)
- [ ] O(n^2)
---
#### Complexity
**Time Complexity:** O(logn) (Everytime you are discarding the search space by half).
**Space Complexity:** O(1)
#### Follow up question
* Try for the last occurence
---
### Find the unique element
**Question**
Every element occurs twice except for 1, find the unique element.
**Note:** Duplicate elements are adjacent to each other but the array is not sorted.
**Example:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/816/original/Screenshot_2023-11-03_at_6.47.48_PM.png?1699017478" width=500 />
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute Force Approach
* The brute force approach can be comparing A[i] with A[i+1]. If `(A[i]!=A[i+1])`, then `A[i]` is the unique element.
#### Optimal Approach
* Can we apply Binary Search ?
* Say we land at mid, how to know current element is the answer? => We can check element at its right and at its left. If both are different, then `mid` is the ans.
* If `A[mid]` is not the answer, then how to decide in which direction shall we move?
* For that, let's make some observation.
* We are given that only one element is unique, there are two occurences of remaining elements.
* **`Can you make some observation w.r.t first occurrences of elements before and after unique element ?`**
* Before unique element, first occurrences are at even index. After unique element, all first appear at odd indices.
**Let us say the array is as follows:**
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
| -------- | -------- | -------- | -------- | -------- | -------- | ------- | -------- | -------- | -------- | -------- |
7|7|6|6|3|8|8|1|1|9|9|
* 3 is unique.
* First occurrence of 7 and 6 is at index even and after 3, first occurrences of elements, 8, 1, 9 is at odd index.
#### Steps for applying Binary Search
* Land at mid, if `A[mid] != A[mid-1] && A[mid] != A[mid+1]`, then `A[mid]` is the answer.
* NOTE: To avoid accessing invalid indices, above conditions shall be modified as follows-
* `mid == 0 || A[mid] != A[mid-1]`
* `mid == N-1 || A[mid] != A[mid+1]`
* Else, we will check index of first occurrence of the element we landed on.
* If index is even, then unique element must be present on right.
* Else, on left.
#### Dry Run for An Example
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Elements | 3 | 3 | 1 | 1 | 8 | 8 | 10 | 10 | 19 | 6 | 6 | 2 | 2 | 4 | 4 |
For the above array,
**1st Iteration:**
* `low = 0, high = 14`,
* $mid = 0 + (14-0)/2 = 7$
* It's not unique.
* `arr[mid] == arr[mid - 1]` -> `mid - 1` is the first occurence.
* `mid - 1 = 6` which is even -> go to right
* `low = mid + 1`
**2nd iteration:**
* `low = 8, high = 14`
* $mid = 8 + (14-8)/2 = 11$
* It's not unique.
* `mid - 1 = 10`
* `arr[mid] != arr[mid - 1]`
* `mid + 1 = 12`
* `arr[mid] == arr[mid + 1]` -> mid is the first occurence.
* `mid % 2 != 0` i.e. mid is odd and thus, left subarray has the unique element. We will move high to `mid - 1 = 10`.
**3rd iteration:**
* `low = 8, high = 10`
* $mid = 8 + (10-8)/2 = 9$
* Its not unique.
* `mid - 1 = 8`
* `arr[mid] != arr[mid - 1]`
* `mid + 1 = 10`
* `arr[mid] == arr[mid + 1]` -> mid is the first occurence.
* `mid % 2 != 0` i.e. mid is odd and thus, left subarray has the unique element. We will move high to `mid - 1 = 8`.
**4th iteration:**
* `low = 8, high = 8`
* `mid = (8 + (8 - 8) / 2) = 8`
* `mid - 1 = 7`
* `arr[mid] != arr[mid - 1]`
* `mid + 1 = 9`
* `arr[mid] != arr[mid + 1]` -> mid is the **unique element.** We will terminate the loop.
#### Pseudo Code
```cpp
int findUnique(int arr[], int N) {
lo = 0, hi = N - 1;
// binary search
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if ((mid == 0 || arr[mid] != arr[mid - 1]) && (mid == N - 1 || arr[mid] != arr[mid + 1])) { //checking mid is unique
return A[mid];
} else if (mid == 0 || arr[mid] == arr[mid - 1]) { //at first occurrence
if (mid % 2 == 0) lo = mid + 2;
else hi = mid - 1;
} else { //at second occurrence
if (mid % 2 == 0) hi = mid - 2;
else lo = mid + 1;
}
}
}
```
#### Complexities
**Time Complexity:** O(log(N)
**Space Complexity:** O(1)
---
### Increasing Decreasing Array
Given an increasing decreasing array with distinct elements. Find max element.
**Examples**
arr[] = {1, 3, 5, 2}
In the above array `5` is the max value.
arr[] = {1, 3, 5, 10, 15, 12, 6}
In the given example max element is `15`
The increasing decreasing array will look something like this:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/935/original/upload_600873e03a8dbd810dfb493b4729f019.png?1696273571" width="500"/>
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Solution
* Increasing decreasing arrays are the array that increases first and after reaching its peek it starts decreasing. We are supposed to find the peek or the max element of the array. The increasing side is sorted in ascending order and the decreasing side is sorted in descending order.
* Brute force approach is a linear search with O(N) time complexity.
* But as we see the elements are sorted in increasing and then decreasing order, so can we do better than O(N) time complexity?
* Can we apply **Binary Search**? What do we need ?
* **Search space** -> array
* **target** -> peak element
* **Condition:** ->
* **Case 1**: if`(arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1])` return mid;
* If immediate left and right are less than current element than we are at peek element.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/937/original/upload_9205cf3e62ccb5ba73b400184b99aa6f.png?1696273860" width="500"/>
* **Case 2**: if`(arr[mid] > arr[mid - 1] and arr[mid] < arr[mid + 1])` go right;
* Implies our mid is at the part of the array where it is still increasing. So the peek will be at the right side of the array.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/938/original/upload_96ec793a723414c54eb5e677d907a358.png?1696274049" width="600"/>
* **Case 3**: go left
* This infers that mid is at the decreasing side of the array and peek must be at left.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/939/original/upload_1722e687ab9c054bdc01a48ccb0e3d31.png?1696274076" width="600"/>
#### Pseudocode
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/884/original/Screenshot_2023-11-04_at_5.16.33_PM.png?1699098413" width=600 />
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/885/original/Screenshot_2023-11-04_at_5.16.45_PM.png?1699098432" width=700 />
---
### Local Minima in an Array
Given an array of N distinct elements, find any local minima in the array
**Local Minima** - a no. which is smaller than its adjacent neighbors.
**Examples**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/941/original/upload_964229b29d6489e936e31ff80703df2d.png?1696274200" width="500"/>
* A = {**3**,6,1,**0**,9,15,**8**}
* Here, we have 3 local minima, `3`, `0`, and `8`.
* `3 < 6`, `0 < 1 && 0 < 9`, and `8 < 15`. All these are smaller than their left and right neighbours.
* B = {21,20,19,17,15,9,**7**}
* All the numbers are in decreasing order, so we only have one local minima `7`.
* C = {**5**,9,15,16,20,21}
* Similarly, all the numbers are strictly increasing so `5` is the only local minima in this example.
* D = {**5**,8,12,**3**}
* Here, the series first increases and then decreases. So we have two local minima `5` and `3`. `5 < 8` and `3 < 12`.
* This can have multiple local minima
* We have to return any local minima
#### Solution
* **Case 1:** Current element is smaller than the next and the previous element returns the current element, since this is local minima.
* **Case 2:** If the current element is greater than the previous element and less than the next element.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/942/original/upload_70590b13011bb7620372b662ae836261.png?1696274341" width="600"/>
* Here we are not looking for global minimia, we are looking for local minima. If `arr[mid - 1] < arr[mid] < arr[m + 1]` there are two posiblities, either `arr[m - 1]` is one of the local minima or we will definitely find a local minima in left direction as elements to the left are in decreasing order.
* **Case 3:** If the current element is greater than the next element and is smaller than the previous element go to the right. As Left may or may not have local minima but the right will definitely have local minima.
* **Case 4:** The current element is greater than the previous as well next element. Then we can go to either the left or to the right, because both will contain atleast one local minima.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/943/original/upload_74fbe76524c70f0033a17c07458b7d14.png?1696274380" width="600"/>
#### Pseudo Code
```javascript
int localMinima(int[] A) {
l = 0, h = n - 1;
while (l <= h) {
mid = l + (h - l) / 2;
if ((mid == 0 || arr[mid] < arr[mid - 1]) && (mid == N - 1 || arr[mid] < arr[mid + 1])) {
return mid;
} else if (mid == 0 || arr[mid] < arr[mid - 1]) {
l = mid + 1;
} else {
h = mid - 1;
}
}
}
```
#### Dry run
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/944/original/upload_b5c3cac9cd087c8dc019d07117aae11f.png?1696274450" width="500"/>
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| ------- | ---- | --- | --- | --- | --- | --- | --- | ---- |
| Element | 9 | 8 | 2 |7 |6 |4 |1 | 5 |
**1st Iteration**
* `low = 0, high = 7`
* `mid = 3`
* The element to the left of mid -> `2 < 7` Thus, `7` cannot be local minima.
* The array is increasing and thus, one of the local minima must be in the left of the array, so we will change `high = mid - 1 = 2`.
**2nd iteration**
* `low = 0, high = 2`
* `mid = 1`
* Element to the left of mid -> `9 > 8`
* Element to the right of mid -> `2 < 8`
* `8` cannot be local minima. As `2` is smaller than `8`, we are at decreasing array and thus, the local minima must exist in the right.
* `low = mid + 1`
**3rd iteration**
* `low = 2, high = 2`
* `mid = 2`
* Element to the left of mid -> `2 < 8`
* Element to the right of mid -> `2 < 7`
* **2 is our local minima.**
#### Complexities
* **Time Complexity: O(log(N))**
* **Space Complexity: O(1)**

View File

@@ -0,0 +1,569 @@
# Searching 2: Binary Search Problems
---
## Understanding Binary Search
### Introduction:
We will continue with our second lecture on Binary Search. In our previous session, we explored the fundamental concepts of this efficient searching algorithm. Today, we will dive even deeper into the world of binary search, uncovering advanced techniques and applications that expand its capabilities.
In this lecture, we will build upon the foundation laid in the first session. We'll delve into topics such as binary search on rotated arrays, finding square root using binary search etc and addressing various edge cases and challenges that may arise during binary search implementation.
### Pseudocode
```java
function binarySearch(array, target):
left = 0
right = length(array) - 1
while left <= right:
mid = left + (right - left) / 2
if array[mid] == target:
return mid
else if array[mid] < target:
left = mid + 1
else:
right = mid - 1
return NOT_FOUND
```
### Use Cases:
Binary search has numerous applications, including:
* Searching in databases.
* Finding an element in a sorted array.
* Finding an insertion point for a new element in a sorted array.
* Implementing features like autocomplete in search engines.
---
### Question
In what scenario does Binary Search become ineffective?
**Choices**
- [x] When the dataset is unsorted.
- [ ] When the dataset is extremely large.
- [ ] When the dataset is sorted in descending order.
- [ ] When the dataset contains only unique elements.
---
### Problem 1 Searching in Rotated Sorted Arrays
### Introduction:
We'll explore the fascinating problem of searching in rotated sorted arrays using the Binary Search algorithm. This scenario arises when a previously sorted array has been rotated at an unknown pivot point. We'll discuss how to adapt the Binary Search technique to efficiently find a target element in such arrays.
### Scenario:
Imagine you have an array that was sorted initially, but someone rotated it at an unknown index. The resulting array is a rotated sorted array. The challenge is to find a specific element in this rotated array without reverting to linear search.
### Example: Finding an Element in a Rotated Array
Suppose we have the following rotated sorted array:
```javascript
Original Sorted Rotated Array: [4, 5, 6, 7, 8, 9, 1, 2, 3]
```
Let's say we want to find the element 7 within this rotated array using a brute-force approach (Linear Search).
### Brute-Force Approach:
* Initialize a variable target with the value we want to find (e.g., 7).
* Loop through each element in the array one by one, starting from the first element.
* Compare the current element with the target:
* If the current element matches the target, we have found our element, and we can return its index.
* If the current element does not match the target, continue to the next element.
* Repeat step 3 until we either find the target or reach the end of the array without finding it.
### Adapting Binary Search:
While the array is rotated, we can still leverage the divide-and-conquer nature of Binary Search. However, we need to make a few adjustments to handle the rotation.
**Intution:**
* In a rotated sorted array, elements were initially sorted in ascending order but have been rotated at some point.
* Let's asusme array contain distinct elements only.
* The goal is to find a specific target element within this rotated array.
* The key to binary search in a rotated array is to determine the pivot point, which is where the array rotation occurred.
* The pivot point is essentially the maximum element in the array.
* Once you've identified the pivot point, you have split the array into two subarrays, each of which is sorted.
* Then you can apply individual binary search in both the parts, and find the target element.
* **Another Idea of Doing it in one Binary Search we'll discuss below**
* **Partitioning of Rotated Sorted Array:**
* A rotated sorted array can be visualized as being split into two parts: part 1 and part 2.
* Crucially, both part 1 and part 2 are sorted individually, but every element in part 1 is greater than those in part 2 due to the rotation.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/290/original/upload_7109177bd564db28fb52884947596f19.jpeg?1697636298" width=600 />
* **Identifying Target's Part**
* To determine which part the Target belongs to (part 1 or 2), compare it with the 0th element.
* If the midpoint is greater than (also equals to) the 0th element, then it belongs to part 1. Otherwise, it's in part 2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/291/original/upload_de49790f61452f4caceea8736169fe3d.jpeg?1697636323" width=500 />
* **Identifying Midpoint's Part:**
* To determine which part the midpoint belongs to (part 1 or 2), compare it with the 0th element.
* If the midpoint is greater than (also equals to) the 0th element, then it belongs to part 1. Otherwise, it's in part 2.
* **Midpoint vs Target:**
* If the midpoint is the equals to the target, you've found it.
* If not, then check if the target lies in the same part as the midpoint. If yes, both target and midpoint is within the same sorted part, perform a binary search in that part to move your midpoint towards the target.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/292/original/upload_e222ee12696646bb515fe8b21149991b.png?1697636367" width=600 />
* If no, move your search towards the other part, effectively approaching the midpoint towards target.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/293/original/upload_8ab6fabad4f92c55665e78291b1befb5.png?1697636388" width=600 />
* **Iterative Process:**
* Continue adjusting your boundaries based on the decisions made in the previous step until you either find the target or exhaust your search space.
* **Result:**
* Return the index of the target if found, or -1 if not.
**Algorithm:**
* Initialize left to 0 and right to len(nums) - 1.
* While left is less than or equal to right, do the following:
* Calculate the middle index mid as left + (right - left)/2.
* If nums[mid] is equal to the target, return mid as the index of the target.
* Check if the target is less than nums[0] (indicating it's on part 2):
* If target < nums[0], check if nums[mid] is greater than or equal to nums[0]:
* If true, update left to mid + 1 to search the right half.
* If false, update right to mid - 1 based on target's relation to nums[mid].
* If the target is greater than or equal to nums[0] (indicating it's on the left side of the pivot):
* If target >= nums[0], check if nums[mid] is less than nums[0]:
* If true, update right to mid - 1 to search the left half.
* If false, update left to mid + 1 based on target's relation to nums[mid].
* Repeat steps 2-6 until left is less than or equal to right.
* If the loop exits without finding the target, return -1 to indicate the target is not in the array.
### Example:
**Scenario:**
Consider the rotated sorted array **[4, 5, 6, 7, 0, 1, 2]** and our target is 0.
**Solution:**
* Using the provided algorithm:
* Initialize left to 0 and right to 6.
* Calculate mid as (left + right) // 2, which is 3.
* Check if nums[mid] (element at index 3) is equal to the target (0). It's not equal.
* Check if target (0) is less than nums[0] (4). It's not.
* Check if nums[mid] (7) is greater than or equal to nums[0] (4). It's true.
* Update left to mid + 1, making left equal to 4.
* Calculate mid as (left + right) // 2, which is 5.
* Check if nums[mid] (element at index 5) is equal to the target (0). It is equal.
* Return mid, which is 5.
**We found the target 0 at index 5.**
---
### Searching in Rotated Sorted Arrays Pseudocode
#### Pseudocode:
```cpp
function searchRotatedArray(nums, target):
left = 0
right = length(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
return mid
if target < nums[0]:
if nums[mid] >= nums[0]:
left = mid + 1
else:
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
else:
if nums[mid] < nums[0]:
right = mid - 1
else:
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```
#### Complexity Analysis:
The time complexity of this modified Binary Search algorithm is still O(log n), making it efficient even in rotated sorted arrays.
**Reason**:
* **Divide and Conquer:**<br> The algorithm works by repeatedly dividing the search space in half. In each step, it either eliminates half of the remaining elements or finds the target element. This is a characteristic of binary search, which has a time complexity of O(log N).
* **Comparison Operations:**<br> The main operations within each iteration are comparisons of the target element with the middle element. Since we're dividing the array in half with each comparison, we need at most O(log N) comparisons to find the element or determine that it's not present.
* **No Need to Examine All Elements:**<br> Unlike linear search, which would require examining all N elements in the worst case, binary search significantly reduces the number of elements that need to be considered, leading to a logarithmic time complexity.
---
### Question
In the problem of searching for a target element in a rotated sorted array, what advantage does Binary Search offer over Linear Search?
**Choices**
- [ ] Binary Search doesn't require any comparisons.
- [ ] Binary Search works faster on unsorted arrays.
- [x] Binary Search divides the search space in half with each step.
- [ ] Binary Search is always faster than Linear Search.
**Explanation:**
Binary Search offers a significant advantage over Linear Search when searching in a rotated sorted array. With each step, Binary Search efficiently narrows down the search interval by dividing it in half, greatly reducing the number of elements under consideration. This characteristic leads to a time complexity of O(log n), making Binary Search much faster compared to Linear Search's O(n) time complexity, especially for larger arrays.
---
### Problem 2 Finding the square root of a number
### Introduction:
Now, we'll explore a fascinating application of Binary Search: finding the square root of a number. The square root operation is a fundamental mathematical operation, and we'll see how Binary Search helps us approximate this value with great efficiency.
### Motivation:
Imagine you're working on a mathematical problem or a scientific simulation that requires the square root of a number. Calculating square roots manually can be time-consuming, and a reliable and fast method is needed. Binary Search provides an elegant way to approximate square roots efficiently.
### Brute-Force Algorithm to Find the Square Root:
* **Input Validation:** If it's negative, return "Undefined" because the square root of a negative number is undefined.
* **Special Cases:** If x is 0 or 1, return x because the square root of 0 or 1 is the number itself.
* **Initialize Guess:** Start with an initial guess of 1.
* Check if the square of the current guess is less than or equal to x. If it is, continue to the next step. If not, exit the loop.
* **Increment Guess:** Increment the guess by 1.
* **Exit Loop:** When the loop exits, it means guess * guess exceeds x. The square root is approximated as guess - 1 because guess at this point is the smallest integer greater than or equal to the square root of x.
* Return Result: Return guess - 1 as the square root of x.
```cpp
function sqrt_with_floor(x):
if x < 0:
return "Undefined" // Square root of a negative number is undefined
if x == 0 or x == 1:
return x // Square root of 0 or 1 is the number itself
// Start from 1 and increment until the square is greater than x
guess = 1
while guess * guess <= x:
guess = guess + 1
// Since the loop ends when guess^2 > x, the floor(sqrt(x)) is guess - 1
return guess - 1
```
:::warning
Please take some time to think about the Binary Search approach on your own before reading further.....
:::
### Binary Search Principle for Square Root:
The Binary Search algorithm can be adapted to find the square root of a number by treating the square root as a search problem. The key idea is to search for a number within a certain range that, when squared, is closest to the target value. We'll repeatedly narrow down this range until we achieve a satisfactory approximation.
Establish a search range: The square root of a non-negative number is always within the range of 0 to the number itself. So, you set up an initial search range as [0, x], where 'x' is the number for which you want to find the square root.
**Intution**:
* **Binary search:** You then start a binary search within this range. The midpoint of the range is calculated, and you compute the square of this midpoint.
* **Comparison:** You compare the square of the midpoint to the original number (x). Three cases can arise:
* **Exact Match:** If the square of the midpoint is exactly equal to x, you've found a value very close to the square root.
* **Square Less Than x:** If the squared midpoint is less than x, it suggests that midpoint can be the answer but we can get the more closer value towards right only(if present). So, adjust the search range to be [midpoint+1, right end of current range].
* **Square Greater Than x:** If the squared midpoint is greater than x, it indicates the square root lies to the left of the midpoint. Consequently, adjust the search range to be [left end of current range, midpoint-1].
* **Convergence:** You repeat the binary search by calculating new midpoints and comparing the squares until you converge on an approximation that is sufficiently close to the actual square root.
For example:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/294/original/upload_42e49c38798729971da9ece87233dca8.png?1697636550" width=600 />
### Example: Finding Square Root using Binary Search
**Scenario:**
We want to find the square root of the number 9 using Binary Search.
**Solution:**
* Initialize left = 1 and right = 9 (since the square root of 9 won't be greater than 9).
* Calculate mid = (left + right) / 2 = 5.
* Compare 5 * 5 with 9.
* Since 25 is greater than 9, narrow the search to the left half.
* Update right = 4.
* Calculate mid = (left + right) / 2 = 2.
* Compare 2 * 2 with 9.
* Since 4 is less than 9, adjust the range to the right half.
* Update left = 3.
* Calculate mid = (left + right) / 2 = 3.
* Compare 3 * 3 with 9.
* We found an exact match! The square root of 9 is 3.
---
### Finding the square root of a number Pseudocode
#### Pseudocode:
Here's a simple pseudocode representation of finding the square root using Binary Search:
```cpp
function findSquareRoot(target):
if target == 0 or target == 1:
return target
left = 1
right = target
result = 0
while left <= right:
mid = left + (right - left) / 2
if mid * mid == target:
return mid
else if mid * mid < target:
left = mid + 1
result = mid
else:
right = mid - 1
return result
```
### Analysis and Complexity:
In each step of the Binary Search, we compare the square of the middle element with the target value. Depending on the result of this comparison, we adjust the search range. Since Binary Search divides the range in half with each step, the time complexity of this algorithm is O(log n), where n is the value of the target number.
### Use Cases:
Finding the square root using Binary Search has applications in various fields, such as mathematics, engineering, physics, and computer graphics. It's often used when precise square root calculations are required, especially in scenarios where hardware or library-based square root functions are not available.
---
### Question
What advantage does using Binary Search for finding the square root of a number offer over directly calculating the square root?
**Choices**
- [ ] Binary Search has a lower time complexity.
- [x] Binary Search provides a more precise result.
- [ ] Binary Search doesn't require any comparisons.
- [ ] Binary Search can find the square root of any number.
---
### Problem 3 Finding the Ath magical number
In this problem, we are tasked with finding the a-th magical number that satisfies a specific condition. A magical number, in the context of this problem, is defined as a positive integer that is divisible by either b or c (or both).
* Magical Number Definition: A magical number is a positive integer that is divisible by either b or c or both. In other words, if a number x is a magical number, it means that x % b == 0 or x % c == 0, or both conditions hold.
* Task: Our task is to find and return the a-th magical number based on the conditions mentioned above.
#### Example
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/055/887/original/Screenshot_2023-11-04_at_6.52.03_PM.png?1699104135" width=500 />
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Brute force
```cpp
Function findAMagicalNumberBruteForce(a, b, c):
number = 1 // Start with the first positive integer
count = 0 // Initialize the count of magical numbers found
while count < a:
if number is divisible by b or c:
count = count + 1 // Increment the count if it's divisible by either b or c
number = number + 1
return number - 1 // Subtract 1 because we increased 'number' after finding the a-th magical number
```
#### Observation
Answer has to be a multiple of either B or C. So, we know we will get answer till A * B or A * C depending on which is smaller. Therefore, our answer range will be between`[1 to A * min(B,C)]`
Example:
A = 8
B = 2
C = 3
A * B = 16
A * C = 24
So, our answer will be within range [1 to 16]
**Que: How many multiples of B, C will be within range [1 to x]?** => x/B + x/C - x/LCM(B,C)$
`The LCM of 'b' and 'c' represents the smallest common multiple of 'b' and 'c' such that any number that is divisible by both 'b' and 'c' will be a multiple of their LCM and we will have to subtract it`
Example:
A = 5
B = 3
C = 4
Range => [1 to 15]
Multiples
=> 15/3 + 15/4 - 15/LCM(3,4)
=> 5 + 3 + 1 = 7 `[3, 4, 6, 8, 9, 12, 15]`
**Que: How to calculate LCM(B,C) ?**
LCM(B,C) = (B * C) / GCD(B,C) [We know how to calculate GCD!]
### Can we apply Binary Search ?
**Search Space** => `[1 to A * min(B,C)]`
**Target** => Ath Magical Number
**Condition** =>
* Say we land at mid.
* To check mid is magical, we need to know how many magical numbers are there in the range [1, mid].
* Compare with A: If the count is more than A, it means we need to search in the lower range [low, mid-1].
* Otherwise, if count is < A, we need to search in higher range
* If count == A, then we store mid as answer, and go left.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/297/original/upload_843ecddf1f70df2f9b0438fae6efe6ee.png?1697636713" width=600 />
#### Pseudocode:
```cpp
int count(x, B, C) {
return x/B + x/C - x/LCM(B,C);
}
int magical(A, B, C) {
l = 1, h = A * min(B,C)
while(l <= h) {
m = l + (h-l)/2;
if(count(m,B,C) > A) {
h = m-1;
}
else if(count(m,B,C) < A) {
l = m+1;
}
else {
ans = m;
h = m-1;
}
}
return ans;
}
```
---
### Question
What is the time complexity of the binary search approach for finding the a-th magical number in terms of A, B, and C?
**Choices**
- [ ] O(A)
- [x] O(log A)
- [ ] O(A * B * C)
- [ ] O(log(A * B * C))
---
### Problem 4 Finding median of array
**What is Median?**
The median of an array is the middle element of the array when it is sorted. For arrays with an odd number of elements, the median is the value at the exact center. For arrays with an even number of elements, the median is typically defined as the average of the two middle elements. It's a measure of central tendency and divides the data into two equal halves when sorted.
### Brute-Force Algorithm to Find the Median of an Array:
* Sort the given array in ascending order. You can use any sorting algorithm (e.g., bubble sort, insertion sort, quicksort, or mergesort).
* Calculate the length of the sorted array, denoted as n.
* If n is odd, return the middle element of the sorted array as the median (e.g., sorted_array[n // 2]).
* If n is even, calculate the average of the two middle elements and return it as the median (e.g., (sorted_array[n // 2 - 1] + sorted_array[n // 2]) / 2).
```cpp
def find_median_brute_force(arr):
# Step 1: Sort the array
sorted_array = sorted(arr)
# Step 2: Calculate the length of the sorted array
n = len(sorted_array)
# Step 3: Find the median
if n % 2 == 1:
median = sorted_array[n // 2]
else:
median = (sorted_array[n // 2 - 1] + sorted_array[n // 2]) / 2.0
return median
```
:::warning
Please take some time to think about the Binary Search approach on your own before reading further.....
:::
### Binary Search Approach:
The Binary Search technique can be harnessed to find the median of two sorted arrays by partitioning the arrays in such a way that the elements on the left side are less than or equal to the elements on the right side. The median will be either the middle element in a combined array (for an odd number of total elements) or the average of two middle elements (for an even number of elements).
### Example: Finding Median of Two Sorted Arrays
**Scenario**:
Consider the two sorted arrays: nums1 = [1, 3, 5] and nums2 = [2, 4, 6]. We want to find the median of the combined array.
**Intuition:**
* **Combined Sorted Array:** To find the median of two sorted arrays, you can think of combining them into a single sorted array. The median of this combined array will be our solution.
* **Partitioning:** The key idea is to partition both arrays into two parts such that:
* The elements on the left side are smaller than or equal to the elements on the right side.
* The partitioning should be done in such a way that we can calculate the median easily.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/298/original/upload_e44a66607d277bde52444cb943fdd5a6.png?1697636987" width=600 />
* **Binary Search:** To achieve this, we can perform a binary search on the smaller array (in this case, nums1). We calculate a partition point in nums1, and then we can calculate the corresponding partition point in nums2.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/299/original/upload_3759b6f6f4cb57981e8ddf27c4c31541.png?1697637273" width=600 />
* **Median Calculation:** Once we have the partitions, we can calculate the maximum element on the left side (max_left) and the minimum element on the right side (min_right) in both arrays. The median will be the average of max_left and min_right.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/300/original/upload_7d4dede78ac17c636e6f6681bc76427e.png?1697637315" width=600 />
* **Handling Even and Odd Lengths:** Depending on whether the total length of the combined array is even or odd, the median calculation varies. If it's even, we average the two values; if it's odd, we take the middle value.
**Solution**:
* We start by calculating the total length of the combined arrays to determine if the median will be even or odd.
* Then, we use binary search on the smaller array (nums1) to find a partition point that satisfies the conditions mentioned earlier. This ensures that elements on the left are smaller or equal to elements on the right.
* We calculate max_left and min_right for both arrays based on the partitions.
* Finally, we calculate the median as the average of max_left and min_right.
**Binary Search:**
* Initialize left = 0 and right = len(nums1) = 3.
* Iteration 1:
* Calculate partition_nums1 = $(0 + 3) / 2 = 1$.
* Calculate partition_nums2 = $(6 + 1) / 2 - 1 = 2$.
* Calculate max_left_nums1 = 1 and max_left_nums2 = 2.
* Calculate min_right_nums1 = 3 and min_right_nums2 = 4.
* Since 1 <= 4 and 2 <= 3, we have found the correct partition.
* Since the total length is even (6), the median is the average of the maximum of left elements and the minimum of right elements, which is $(2 + 3) / 2 = 2.5$.
---
#### Pseudocode:
Here's a simplified pseudocode representation of finding the median of two sorted arrays using Binary Search:
```cpp
function findMedianSortedArrays(nums1, nums2):
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
total_length = len(nums1) + len(nums2)
left = 0
right = len(nums1)
while left <= right:
partition_nums1 = (left + right) / 2
partition_nums2 = (total_length + 1) / 2 - partition_nums1
max_left_nums1 = float('-inf') if partition_nums1 == 0 else nums1[partition_nums1 - 1]
max_left_nums2 = float('-inf') if partition_nums2 == 0 else nums2[partition_nums2 - 1]
min_right_nums1 = float('inf') if partition_nums1 == len(nums1) else nums1[partition_nums1]
min_right_nums2 = float('inf') if partition_nums2 == len(nums2) else nums2[partition_nums2]
if max_left_nums1 <= min_right_nums2 and max_left_nums2 <= min_right_nums1:
if total_length % 2 == 0:
return (max(max_left_nums1, max_left_nums2) + min(min_right_nums1, min_right_nums2)) / 2
else:
return max(max_left_nums1, max_left_nums2)
elif max_left_nums1 > min_right_nums2:
right = partition_nums1 - 1
else:
left = partition_nums1 + 1
```
#### Analysis:
In each iteration, the algorithm adjusts the partition positions based on the comparison of maximum elements on the left side with minimum elements on the right side of the partitions. The Binary Search nature of this algorithm leads to a time complexity of O(log(min(m, n))), where m and n are the lengths of the two input arrays.
#### Use Cases:
The concept of finding the median of two sorted arrays is crucial in various fields, including data analysis, algorithms, and statistics.
---
### Observations
* **Sorted Arrays:** Binary Search excels in sorted arrays, capitalizing on their inherent order to quickly locate elements.
* **Search Space:** Identify the range within which the solution exists, which guides setting up the initial search range.
* **Midpoint Element:** The middle element provides insights into the properties of elements in different subranges, aiding decisions in adjusting the search range.
* **Stopping Condition:** Define conditions under which the search should stop, whether an element is found or the search range becomes empty.
* **Divide and Conquer:** Binary Search employs a "divide and conquer" strategy, progressively reducing the problem size.
* **Boundary Handling:** Pay special attention to handling boundary conditions, avoiding index out-of-bounds errors.
* **Precision & Approximations:** Binary Search can yield approximate solutions by adjusting the search criteria.

View File

@@ -0,0 +1,441 @@
# Searching 3: Binary Search on Answer
---
## Problem 1 Painter's Partition
We have to paint all N boards of length [C0, C1, C2, C3 … CN - 1]. There are K painters available and each of them takes 1 units of time to paint 1 unit of the board.
Calculate and return the minimum time required to get the job done.
> NOTE:
> 1. Two painters cannot share a board to paint. That is to say, a board cannot be painted partially by one painter, and partially by another.
> 2. A painter will only paint contiguous boards. This means a painter paints a continous subarray of boards
**Example 1**
Below are some of the possible configurations:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/056/078/original/IMG_3AFFFE9FBC6A-1.jpeg?1699349867" width=600 />
Configuration 1: Max is 31
Configuration 2: Max is 26
Configuration 3: Max is 25
**Out of above least is 25**, hence configuration 3 is better. We want to minimize the maximum value.
There can be more configurations, but you'll find the 3rd to be the best, hence **`25`** is the answer.
**Example 2**
```cpp
A = [10,20,30,40]
K = 2
```
P1 => red
P2 => green
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/948/original/Screenshot_2023-10-17_123615.png?1697526385" width=200 />
Max = 70
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/949/original/Screenshot_2023-10-17_123726.png?1697526456" width=200 />
Max = 60
**Output**
60
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Painter's Partition Greedy Approach
* Greedy Approach:- We can just divide the total time by total number of painters.
* One might think it as by dividing the boards among the painters would result in least time per painter
* But is this idea valid ?
### Flaw:
```cpp
A = [1,2,3,4,100] K = 2
```
According to Idea 1 :- $110/2 = 55$
But we see that it is impossible, because we can't divide the boards among two painters with 55 length each.
---
### Question
What is the minimum time to get the job done?
A = [1,2,3,4,100] K = 2
**Choices**
- [ ] 55
- [x] 100
- [ ] 1
- [ ] 110
**Explanation:**
The minimum time required to Finish the job is 100.
The configuration of the boards is as follows
* painter1 = [1, 2, 3, 4] = 10
* painter2 = [100] = 100
Thus the maximum of (10, 100) is the minimum time taken to complete the job.
Among all possible configuration **100** is the minimum time achieved.
---
### Painter's Partition Binary Search
Lets's look at example below :-
`[3, 5, 1, 7, 8, 2, 5, 3, 10, 1, 4, 7, 5, 4, 6]` ans `K = 4`
Color code for each painter:
> P1 -> Red
> P2 -> Green
> P3 -> Blue
> P4 -> Orange
---
#### Search Space
**Best Case**
Say we have as many painters as the number of boards, in which case each painter can paint one board. The maximum value will be the answer.
**Example:**
`A[ ] = {2, 5, 3, 8}, K = 4`
`Then 8 is the answer.`
**Worst Case**
There is ony 1 painter. In this case, sum(array) is the answer.
So, our Search Space will be within range: **[max(array) to sum(array)]**
---
#### Target
The max time to complete the task
---
#### Condition
* Say we land at mid. How can we decide whether mid is the answer?
* We can check if we can complete the task within mid amount of time at max.
* If yes, then we should save it as the answer and move left to try for a lesser time.
* Else, move right(it means we will need more time to complete the task )
---
### Painter's Partition Dry Run and Pseudocode
`[3, 5, 1, 7, 8, 2, 5, 3, 10, 1, 4, 7, 5, 4, 6]` ans `K = 4`
* Intially the **Lo = 10** and **Hi = 71** (By using above defined criteria for search space) therefore using the above algorithm Mid = $10 + (71 - 10)/2 = 40$ then we check if it is possible to paint all boards in atleast 40 units below is the configuration that satisfy the condition :-
* Painter P1 takes = $3 + 5 + 1 + 7 + 8 + 2 + 5 + 3 = 34$
* Painter P2 takes = $10 + 1 + 4 + 7 + 5 + 4 + 6 = 37$
* <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/955/original/Screenshot_2023-10-17_124357.png?1697526848" width=250 />
* Since the condition is satisfied let's go to left i.e. $Hi = mid -1 = 40 - 1 = 39$
* Now **Hi = 39** and **Lo = 10**; Mid = $10 + (39 - 10)/2 = 24$
* Painter P1 takes = $3 + 5 + 1 + 7 + 8 = 24$
* Painter P2 takes = $2 + 5 + 3 + 10 + 1 = 21$
* Painter P3 takes = $4 + 7 + 5 + 4 = 20$
* Painter P4 takes = 6
* <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/956/original/Screenshot_2023-10-17_124440.png?1697526887" width=250 />
* Since the condition is satisfied let's go to left i.e. $Hi = mid -1 = 24 - 1 = 23$
* Now Hi = 23 and Lo = 10 therefore using the above algorithm Mid = $10 + (23 - 10)/2 = 16$ then we check if it is possible to paint all boards in atleast 10 units We find that there is no configuration that satisfy the condition therefore we go to right.
* Similarly we follow the algorithm to arrive at the solution.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/957/original/upload_2f20dca15bacdd111b2ee85772b291c9.png?1697526929" width=750 />
#### Pseudocode
```cpp
// Find minimum painters required for given maximum length (Length that painter can paint)
paintersNumber(arr[], N, mid, K) {
res = 0, numPainters = 1;
for (i = 0; i < N; i++) {
res += arr[i];
if (res > mid) {
res = arr[i];
numPainters++;
}
}
//if we have used less than or equal to given number of painters,
//then the configurations works
if (numPainters <= K) return true;
else return false;
}
partition(arr[], N, K) {
Lo = maxEle(arr, N);
Hi = sumArr(arr, N);
while (Lo <= Hi) {
mid = Lo + (Hi - Lo) / 2;
if (paintersNumber(arr, N, mid, K))
ans = mid
Hi = mid - 1;
else
Lo = mid + 1;
}
return ans;
}
```
#### Complexities
**Time Complexity:** O(log (sum - max) * N )
**Space Complexity:** O(1)
---
### Question
What is the time complexity of the Painters Partition Problem?
**Choices**
- [x] O( log(k) * (sum(boards) - max(boards)))
- [ ] O(k * log(sum(boards) - max(boards)))
- [ ] O(N * log(sum(boards) - max(boards)))
- [ ] O(k * log N)
---
### Problem 2 Aggresive Cows
Given N cows & M stalls ,all M stalls are located at the different locations at x-axis, place all the cows such that minimum distance between any two cows is maximized.
> Note :
> 1. There can be only one cow in a stall at a time
> 2. We need to place all cows
**Testcase 1**
```cpp
stalls = [1, 2, 4, 8, 9]
cows = 3
stall = 5
```
**Solution**
```cpp
T = 3
```
**Explaination TestCase 1**
| 1 | 2 | 4 | 8 | 9 | Min distance |
|:---:|:---:|:---:|:---:|:---:|:------------:|
| c1 | c2 | c3 | | | 1 |
| c1 | | c2 | | c3 | 3 |
| c1 | | | c2 | c3 | 1 |
* If we put cows according to the first configuration then min distance = 1 because of c1 and c2 (shortest distance between any two cows is 1).
* If we put cows according to the Second configuration then min distance = 3 because of c1 and c2 (shortest distance between any two cows is 3)
* If we put cows according to the third configuration then min distance = 1 because of c2 and c3 (shortest distance between any two cows is 1).
* Therefore answer = max(1,3,1) = 3
**Testcase 2**
```cpp
stalls = [2, 6, 11, 14, 19, 25, 30, 39, 43]
cows = 4
stall = 9
```
**Solution**
```cpp
T = 12
```
**Explaination TestCase 2**
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:------------:|
| c1 | c2 | c3 | c4 | | | | | | 3 |
| c1 | | c2 | | c3 | | c4 | | | 8 |
| c1 | | | c2 | | | c3 | | c4 | 12 |
* If we put cows according to the first configuration then min distance = 3
* If we put cows according to the Second configuration then min distance = 8
* If we put cows according to the third configuration then min distance = 12
* Therefore answer = max(3,8,12) = 12
---
### Question
What is the objective of the problem described?
**Choices**
- [ ] Place cows in stalls randomly.
- [ ] Place cows in stalls such that the distance between any two cows is minimized.
- [x] Place cows in stalls such that the minimum distance between any two cows is maximized.
- [ ] Place cows in stalls such that the total distance is minimized.
---
### Question
What will be the maximum value of the distance between the closest cows in this case?
A: 0, 3, 4, 7, 9, 10
K = 4
**Choices**
- [ ] 10
- [ ] 4
- [x] 3
- [ ] 2
**Explanation:**
The 4 cows are placed in stalls at 0, 3, 7, 10. This is the optimal configuration.
The value between the closest cows can be found by
= min(3 - 0, 7 - 3, 10 - 7)
= min(3, 4, 3)
= 3
Thus the maximum result is 3 over all possible configurations.
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Aggresive Cows Binary Search Approach
Let's use testcase 2 to get the intuition of the question.
This question is similar to Painter's Partition problem. Instead of minimising the maximum answer, we have to maximise the minimum distance.
#### Search Space
* **Worst Case:**
If say there are same cows as the number of stalls, then we place each cow at 1 stall. Then we can find difference between adjacent stalls. The minimum out of them is the answer.
**Example:**
`A[ ] = {4, 7, 14, 20}`
`7 - 4 = 3`
`14 - 7 = 7`
`20 - 14 = 6`
`min(3, 7, 6) = 3(answer)`
Though, we can take 1 as the minimum value.
* **Best Case:**
There are two cows. Then, we can place them at the corner stalls. The distance between first and last stall will be the answer.
**Search Space:** [1 A[N-1]-A[0]]
#### Condition
Say we land at mid, now we can check if it is possible to keep cows at a minimum distance of mid.
* If yes, save it and check for farther distance, i.e, move right.
* Else, if keeping at a distance of mid is not possible, then we should try reducing the distance; hence, move left.
**Example 1:**
*Let's check if we can put 4 cows at minimum distance of 20.*
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:------------:|
| c1 | | | | | c2 | | | | 20 |
In above configuration minimum distance is 20 but we are unable to accommodate all cows(no place for c3 and c4). This means that we have to reduce the distance to accomodate all cows.
**Example 2:**
*Let's check if we can put cows at minimum distance of atleast 5 below is a configuration that satisfy the condition.*
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:------------:|
| c1 | | c2 | | c3 | c4 | | | | 5 |
Since we are able to place all cows at a minimum distance of 5, we should save it as answer and try to maximise this distance.
---
### Aggresive Cows Dry Run and Pseudocode
Below is the trace of algorithm on above Example :-
* Intially the Hi = 41 and Lo = 3 (By using above defined criteria for search space) therefore using the above algorithm Mid = $3 + (41 - 3)/2 = 22$ then we check if it is possible to accommodate 4 cows completely in the shelters with min distance being 22 units We could not find any such configuration that satisfy the condition (got to left) below one failed configuration :-
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:-----------------------------------:|
| c1 | | | c2 | | | | c3 | | N/A since all cows not accommodated |
* Now the Hi = 21 and Lo = 3 therefore using the above algorithm Mid = $3 + (21 - 3)/2 = 12$ then we check if it is possible to accommodate 4 cows completely in the shelters with min distance being 12 units below is configuration that satisfies the condition (we go to right) :-
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:| --- | --- |:---:| --- | --- |:------------:|
| c1 | | | c2 | | | c3 | | c4 | 12 |
* Now the Hi = 21 and Lo = 13 therefore using the above algorithm Mid = $13 + (21 - 13)/2 = 17$ then we check if it is possible to accommodate 4 cows completely in the shelters with min distance being 17 units We could not find any such configuration that satisfy the condition (got to left) below one failed configuration :-
| 2 | 6 | 11 | 14 | 19 | 25 | 30 | 39 | 43 | Min distance |
|:---:|:---:|:---:|:---:| --- | --- |:---:| --- | --- |:------------:|
| c1 | | | | c2 | | | c3 | | N/A since all cows not accommodated |
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/958/original/upload_7a89654912ea0ca4894085816a208e52.png?1697527259" width=600 />
#### Pseudocode
```cpp
bool check(v[], int x, int c) {
n = v.size();
count = 1;
last = 0;
for (i = 0; i < n; i++) {
if (v[i] - v[last] >= x) {
last = i; //cow placed
count++;
}
if (count >= c) {
return true;
}
}
return false;
}
// Function to find the maximum possible
// minimum distance between the cows
aggressive_cows(v[], size, cows) {
int lo = 0;
for (i = 1; i < n; i++) {
lo = min(lo, v[i] - v[i - 1]);
}
hi = v[n - 1] - v[0];
ans = -1;
// Applying Binary search
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if (check(v, mid, cows)) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
```
---
### Binary Search Problems Identification
* These type of problems generally has following characteristics :-
* There are two or three parameter & constraints
* Requirement is to maximize or minimize the given parameter
* One tricky point is to find search space which is generally the parameter asked to maximize or minimize.
* The problem should be **Monotonic** in nature i.e after one point it is not feasible to solve or vice versa.

View File

@@ -0,0 +1,556 @@
# Count Sort & Merge Sort
---
## Count Sort
Find the smallest number that can be formed by rearranging the digits of the given number in an array. Return the smallest number in the form an array.
**Example:**
A[ ] = `{6, 3, 4, 2, 7, 2, 1}`
Answer: `{1, 2, 2, 3, 4, 6, 7}`
A[ ] = `{4, 2, 7, 3, 9, 0}`
Answer: `{0, 2, 3, 4, 7, 9}`
#### Observation/Hint
we can to construct a number using digits. The digits in a number can only `range from 0 to 9`, thus instead of sorting the number which takes `O(N log N)` time, one can leverage this fixed range to derive a faster solution.
#### Approach
* **Frequency Count:** Create an `array of size 10` to count the frequency of each digit in the given number.
* Using the frequency array, reconstruct the original array in ascending order.
* This method of sorting based on frequency counting is often called "**`Count Sort`**".
#### Pseudocode
```cpp
Frequency Array of size 10
F = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i -> 0 to(N - 1) {
F[A[i]]++
}
k = 0
for d -> 0 to 9 { // For each digit
for i -> 1 to F[d] {
A[k] = d
k++
}
}
return A
```
#### Dry Run
* A = `[1, 3, 8, 2, 3, 5, 3, 8, 5, 2, 2, 3]` (Given Array)
* F = `[0, 1, 3, 4, 0, 2, 0, 0, 2, 0]` (Frequency Array)
* Reconstructing A using F:
1 (once), 2 (three times), 3 (four times), 5 (two times), 8 (two times)
* Resulting A = `[1, 2, 2, 2, 3, 3, 3, 3, 5, 5, 8, 8]`
#### TC and SC
* **Time Complexity:** O(N)
* **Space Complexity:** O(1) (Since the size of the frequency array is constant, regardless of the size of N).
---
### Count Sort on large values
### Will Count Sort work if the range of A[i] is more than $10^9$?
* Count Sort isn't suitable for a range of $10^9$ because a frequency array of this size would demand too much memory.
* Count Sort works well when the range of A[i] is ~ $10^6$.
Each integer typically occupies `4 Bytes`.
Storing $10^9$ integers requires 4GB, which is often impractical. An array up to $10^6$ in length is more manageable, needing 4MB.
---
### Count Sort on Negative Numbers
Implement Count Sort for an array containing negative numbers.
#### Observation/Hint
Unlike conventional **Count Sort**, which operates on non-negative integers, this variation needs to account for negative numbers. The method involves adjusting indices in the frequency array based on the smallest element in the original array.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* **Find Range:** Determine the smallest and largest elements in the array to ascertain the range.
* **Adjust for Negative Numbers:** By adjusting indices in the frequency array based on the smallest element, negative numbers can be accounted for.
**Example**
* Given A = [-2, 3, 8, 3, -2, 3]
* Smallest = -2, Largest = 8
* Range = 11 (8 - (-2) + 1)
* Frequency array F = [2, 0, 0, 3, 0, 0, 0, 0, 1]
* 0th index frequency is mapped with -2, 1st index with -1, and so on.
* Reconstructed A using F: -2, -2, 3, 3, 3, 8
#### Pseudocode
```cpp
//Find smallest and largest elements in A
//Create a frequency array F of size (largest - smallest + 1)
for i -> 0 to(N - 1) {
F[A[i] - smallest_element]++
}
//Reconstruct array A using F
for each index i in F {
while F[i] > 0 {
Append(i + smallest_element) to A
F[i]--
}
}
```
#### TC and SC
* **Time Complexity (TC):** O(N)
* **Space Complexity (SC):** O(N + Range)
---
### Merge two sorted arrays
Giver an integer array where all odd elements are sorted and all even elements are sorted. Sort the entire array.
A[] = {`2, 5, 4, 8, 11, 13, 10, 15, 21`}
#### Approach
We can take two separate arrays to keep even(EVEN[]) and odd(ODD[]) elements. Then we can merge them in the original array.
We will keep three pointers here: `a(for original array)`, `e(for even array)` and `o(for odd array)`, all starting at index 0.
If A[a] is odd, ODD[o]=A[a], o++, a++
If A[a] is even, EVEN[e]=A[a], e++, a++
---
#### Pseudocode
```java
void merge(A[]) {
int N = A.length();
//n1: count of even elements
//n2: count of odd elements
int EVEN[n1], ODD[n2];
int a = 0, e = 0, o = 0;
for (int i = 0; i < N; i++) {
if (A[a] % 2 == 0) {
EVEN[e] = A[a];
e++;
} else {
ODD[o] = A[a];
o++;
}
a++;
}
a = 0; // moves over A
e = 0; // moves over EVEN
o = 0; // moves over ODD
while (e < n1 && o < n2) {
if (EVEN[e] < ODD[o]) {
A[a] = EVEN[e];
e++;
} else {
A[a] = ODD[o];
o++;
}
a++;
}
while (e < n1) {
A[a] = EVEN[e];
e++;
a++;
}
while (o < n2) {
A[a] = ODD[o];
a++;
o++;
}
}
```
---
### Question
Iteration of merging 2 Arrays?
**Choices**
- [ ] N ^ 3
- [ ] N ^ 2
- [x] 2 * N
- [ ] Constant
---
### Merge Sort
### Example: Sorting Examination Sheets
>A teacher collected the examination sheets of students randomly. Now, she needs to sort those sheets as per roll number of students. As she is smart, instead of sorting it by herself, she divided the sheets into two halves and gave each half to Kishore and Suraj for sorting.
>Once she has the sorted halves, she just need to merge two sorted halves, which is significantly easier.
>Kishore and Suraj also decided to repeat this and divided the sheets in two halves and gave them to their friends for sorting.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/864/original/upload_40b520e7af8dd0f922e1d9c2d89636cf.png?1697472522" width="500" />
>In this way, the last students will have one sheet only. They can directly gave that sheet to the students before them whose job will be to arrange those two sheets and pass it above.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/865/original/upload_adb5507f2cfca8b1765468ce198b10b1.png?1697472567" width="500" />
>In this way, the sheets are finally sorted.
**Example: Sorting Numbers**
Sort the array, A = {3, 10, 6, 8, 15, 2, 12, 18, 17}
#### Divide
* The idea is to divide the numbers in two halves and then start merging the sorted arrays from bottom and pass above.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/866/original/upload_7e5df36dc120d7420e309c41164356a3.png?1697472603" width="500" />
#### Merge
- Merging [3] and [10] as [3, 10]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/869/original/upload_6ec547929c68fa72ea4313246feda12f.png?1697472658" width="500" />
- Merging [3, 10] and [6] as [3, 6, 10]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/870/original/upload_c4ab90c586f56f05b3251e0e9e156f56.png?1697472722" width="500" />
- Merging [8] and [15] as [8, 15]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/871/original/upload_1cba3e08b9c70b828a83a2dd3918efe9.png?1697472758" width="500" />
- Merging [3, 6, 10] and [8, 15] as [3, 6, 8, 10, 15]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/872/original/upload_611d5e13b458afb7740064b342a6b033.png?1697472843" width="500" />
- Merging [2] and [12] as [2, 12]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/874/original/upload_ed17cfb54776ca14d04018b75f249a3d.png?1697472907" width="500" />
- Merging [18] and [17] as [17, 18]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/877/original/upload_75715655b476438b9f8b89bbc7897a01.png?1697472953" width="500" />
- Merging [2, 12] and [17, 18] as [2, 12, 17, 18]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/878/original/upload_888c80aade9ad006676f296b54a593f7.png?1697472999" width="500" />
- Merging [3, 6, 8, 10, 15] and [2, 12, 17, 18] as [2, 3, 6, 8, 10, 12, 15, 17, 18]
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/879/original/upload_0ef9c62a941f2bff356661587a27008a.png?1697473037" width="500" />
In this way, we have finally sorted the array.
***This algorithm of dividing the array into multiple subproblems and merging them one by one is called Merge Sort.***
*Since we are breaking down the array into multiple subproblems and applying the same idea to merge them, we are using the technique of Recursion.*
#### Psuedocode
```java
void merge(A[], l, mid, r) {
int N = A.length();
int n1 = mid - l + 1;
int n2 = r - mid;
int B[n1], C[n2];
int idx = 0;
for (int i = l; i <= mid; i++) {
B[idx] = A[i];
idx++;
}
idx = 0;
for (int i = mid + 1; i <= r; i++) {
C[idx] = A[i];
idx++;
}
idx = l;
i = 0; // moves over A
j = 0; // moves over B
while (i < n1 && j < n2) {
if (B[i] <= C[j]) {
A[idx] = B[i];
i++;
} else {
A[idx] = C[j];
j++;
}
idx++;
}
while (i < n1) {
A[idx] = B[i];
idx++;
i++;
}
while (j < n2) {
A[idx] = C[j];
idx++;
j++;
}
}
void mergeSort(int A[], l, r) {
if (l == r) return; // base case
int mid = (l + r) / 2;
mergeSort(A, l, mid);
mergeSort(A, mid + 1, r);
merge(A, l, mid, r);
}
```
#### Complexity Analysis:
If we divide the arrays in two halves, we will have a tree structure as:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/903/original/Screenshot_2023-10-25_at_4.22.50_PM.png?1698231187" width=400/>
<br/><br/>
The time taken at every level is the time taken by merging the arrays which will be O(N).
Height of Tree / Number of Levels - O(log N)
Thus,
***Time Complexity:* O(N * log(N))**
**Space Complexity:** O(N)
For recursive stack, we require O(logN) space. And at every level, we are using O(N) space for merging but since we are freeing that as well. We are utilizing O(N) in total merging.
Thus, space complexity is O(logN) + O(N) = O(N)
> Merge sort is stable as arrangement of elements is taking place at merge step which is essentially maintaining the relative order of elements.
---
### Calculate no of pairs such that A[i] > B[j]
Given two array, A[n] and B[m]; Calculate number of pairs i,j such that A[i] > B[j].
**Example**
A[3] = `{7, 3, 5}`
B[3] = `{2, 0, 6}`
**Explanation**
`(7,2) (7,0) (7,6) (3,2) (3,0) (5,2) (5,0)` (7 pairs)
:::warning
Please take some time to think about the bruteforce approach on your own before reading further.....
:::
#### Brute Force Approach
Take 2 loops and compare the values
#### TC & SC
* Time complexity is O(n * m)
* Space complexity is O(1)
#### Appoach 2 with Dry Run
1. Sort both the arrays
2. Create one array, C[6] for merging both the arrays
3. Assign pointer P1, P2, P3 to A[0], B[0], C[0] respectively
4. A[3] = {3, 5, 7} `<-- P1`
5. B[3] = {0, 2, 6} `<-- P2`
6. `B[0] < A[0]` means 0 is smaller than every element in A from index 0 onwards; **`count of pairs = 3 (3,0)(5,0)(7,0)`**; C[] ={0}; `P2=1`
7. `B[1] < A[0]` means 2 is smaller than every element in A from index 0 onwards; **`count of pairs = 6 (3,0)(5,0)(7,0)(3,2)(5,2)(7,2)`**; C[] ={0, 2}; `P2=2`
8. `B[2] > A[0]` means 6 can't form a pair with 3. We are done with 3, because if 6 can't make a pair, no other element after 6 can make a pair with 3; C[]={0, 2, 3}; `P1=1`
9. `B[2] > A[1]` means 6 can't form a pair with 5. We are done with 5, because if 6 can't make a pair, no other element after 6 can make a pair with 5; C[]={0, 2, 3, 5}; `P1=2`
10. `B[2] < A[2]` means 6 is smaller than every element in A from index 2 onwards; **`count of pairs = 7(3,0)(5,0)(7,0)(3,2)(5,2)(7,2)(7,6)`**; C[] ={0, 2, 3, 5, 6}; `P2=3`
11. B is empty, we can push all elements remaining in A to C; C[] ={0, 2, 3, 5, 6, 7};
#### Time Complexity
O(nlogn + mlogm + m + n)
Here nlogn is the time complexity of sorting A array, mlogm is the time complexity for B array and m+n is the time complexity for merging both the arrays
---
### Inversion Count
Given an a[n], calculate no of pairs [i,j] such that i<j && a[i]>a[j], i and j are index of array.
Given a[5] = {10, 3, 8, 15, 6}
| i < j | a[i] > a[j] |
|:-------:|:-------------:|
| i=0, j=1 | a[0] > a[1] |
| i=0, j=2 | a[0] > a[2] |
| i=0, j=4 | a[0] > a[4] |
| i=2, j=4 | a[2] > a[4] |
| i=3, j=4 | a[3] > a[4] |
Hence from the above table we can conclude that the ans is 5 as it is valid for only 5 pairs.
### Question
Consider the following array: [5, 2, 6, 1]. Calculate the inversion count for this array.
**Choices**
- [ ] 1
- [ ] 2
- [ ] 3
- [x] 4
---
### Question
Consider the following array: [5, 3, 1, 4, 2]. Calculate the inversion count for this array.
**Choices**
- [ ] 0
- [ ] 5
- [ ] 6
- [x] 7
---
### Inversion Count Brute Force
Create all the pairs and check.
#### Pseudocode
```java
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // since j is greater than i
if (a[i] > a[j])
cnt++
}
}
```
TC for the above code is $O(n^2)$
> This code will give us time limited exceeded error. So, we need to find a better apporach
#### Optimised Approach
**IDEA:**
We will slipt the array into two equal parts, and keep on splitting the array till only 1 element is left, just like we do in MERGE SORT.
Now, at the time of merging, we can keep counting the pairs.
Basically, it will be same as what we did in previous question. As we merge the arrays, we can keep on calculating the answer.
#### Pseudocode - Small change to merge function
```cpp
void merge(A[], l, mid, r) {
inv_count = 0;
int N = A.length();
int n1 = mid - l + 1;
int n2 = r - mid;
int B[n1], C[n2];
int idx = 0;
for (int i = l; i <= mid; i++) {
B[idx] = A[i];
idx++;
}
idx = 0;
for (int i = mid + 1; i <= r; i++) {
C[idx] = A[i];
idx++;
}
idx = l;
i = 0; // moves over A
j = 0; // moves over B
while (i < n1 && j < n2) {
if (B[i] <= C[j]) {
A[idx] = B[i];
i++;
} else {
A[idx] = C[j];
j++;
//**ONLY CHANGE IS THE BELOW LINE**
//Here, we found element on right subarray to be smaller than an element on left,
//so we will count all the elements on left [i m-1] = m - i
inv_count = inv_count + (m - i);
}
idx++;
}
while (i < n1) {
A[idx] = B[i];
idx++;
i++;
}
while (j < n2) {
A[idx] = C[j];
idx++;
j++;
}
}
```
---
## Stable Sort & Inplace
### Stable Sort
#### Definition:
Relative order of equal elements should not change while sorting w.r.t a parameter.
**Examples**
A[ ] = {6, 5, 3, 5}
After Sorting
A[ ] = {3, 5, 5, 6}
In this case, which 5 comes first, which later, doesn't matter since it is just a singular data.
But in actually scenario the objects to be sorted is collection of data.
> Scenario: Let's talk about an Airport checkin line!
> It should be First Come first serve, whoever comes first should be allowed first to checkin.
> But according to airline, all the members are not same. Some would be economic, business class, priveledged/ priorty...
> Say Anand(economic class) is standing and Amir(economic class) comes and tries to move ahead Anand, will Anand be okay with it? Not Really!
> Say Anupriya(Business Class), now Anand would be okay!
> The above example explains why stable sorting is important.
**Another Example:**
| Name | Marks |
| -------- | -------- |
| A | 8 |
| B | 5 |
| C | 8 |
| D | 4 |
| E | 8 |
Sort acc to marks. In which case, if this is stable sort, A,C,E should appear in the same order.
After Sorting
| Name | Marks |
| -------- | -------- |
| D | 4 |
| B | 5 |
| A | 8 |
| C | 8 |
| E | 8 |
#### Inplace
- No extra space
- Space complexity: O(1)

View File

@@ -0,0 +1,606 @@
# Sorting 2: Quick Sort & Comparator Problems
---
## Problem 1 Partition the array
**Problem Description**
Given an integer array, consider first element as pivot, rearrange the elements such that for all **`i`**:
if **`A[i] < p`** then it should be present on left side
if **`A[i] > p`** then it should be present on right side
**Note:** All elements are distinct
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/591/original/Screenshot_2023-11-22_at_4.36.54_PM.png?1700651249" width=500 />
### Example:
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/592/original/Screenshot_2023-11-22_at_4.38.39_PM.png?1700651328" width=600 />
<br><br>
**The State of the array after Partitioning will be:**
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/593/original/Screenshot_2023-11-22_at_4.40.21_PM.png?1700651431" width=500 />
---
### Question
Given an integer array, consider first element as pivot **p**, rearrange the elements such that for all **`i`**:
if **`A[i] < p`** then it should be present on left side
if **`A[i] > p`** then it should be present on right side
`A = [10, 13, 7, 8, 25, 20, 23, 5]`
**Choices**
- [ ] left side = [10, 7, 5, 8] right side = [10, 13, 25, 20, 23]
- [ ] left side = [10, 13, 7, 8] right side = [25, 20, 23, 5]
- [ ] left side = [13, 25, 20, 23] right side = [7, 8, 5]
- [x] left side = [7, 8, 5] right side = [13, 25, 20, 23]
**Explanation**:
The pivot value is `10`
The elements lesser than the pivot are `[7, 8, 5]`
The elements greater than the pivot are `[13, 25, 20, 23]`
Thus, `left side = [7, 8, 5] right side = [13, 25, 20, 23]`
---
### Partition the array Approach
* Partitioning begins by locating two position markers—lets call them **`leftmark`** and **`rightmark`**—at the beginning and end of the remaining items in the list.
* The goal of the partition process is to move items that are on the wrong side with respect to the pivot value while also converging on the split point.
#### Process
* We begin by incrementing leftmark until we locate a value that is greater than the pivot value.
* We then decrement rightmark until we find a value that is less than the pivot value.
* At this point we have discovered two items that are out of place with respect to the eventual split point. **For our example, this occurs at 93 and 20. Now we can exchange these two items and then repeat the process again.**
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/594/original/Screenshot_2023-11-22_at_4.58.09_PM.png?1700652500" width=550 />
**Continue:**
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/595/original/Screenshot_2023-11-22_at_4.59.22_PM.png?1700652572" width=450 />
* **At the point where rightmark becomes less than leftmark, we stop**. The position of rightmark is now the split point. The pivot value can be exchanged with the contents of the split point and the pivot value is now in place
><img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/596/original/Screenshot_2023-11-22_at_5.01.35_PM.png?1700652707" width=450 />
* **Now, we can exchange the 54(Pivot) with 31**
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/593/original/Screenshot_2023-11-22_at_4.40.21_PM.png?1700651431" width=500 />
#### Pseudocode
```cpp
partition(A,first,last):
pivotvalue = A[first]
leftmark = first+1
rightmark = last
while leftmark <= rightmark:
if A[leftmark] <= pivotvalue:
leftmark = leftmark + 1
else if A[rightmark] > pivotvalue:
rightmark = rightmark -1
else:
temp = A[leftmark]
A[leftmark] = A[rightmark]
A[rightmark] = temp
// swap pivot element with element present at rightmark
temp = A[first]
A[first] = A[rightmark]
A[rightmark] = temp
```
---
## Quick Sort
*Sorting is the process of organizing elements in a structured manner.*
**Quicksort** is one of the most popular sorting algorithms that uses **nlogn** comparisons to sort an array of n elements in a typical situation. Quicksort is based on the **divide-and-conquer strategy**. Well take a look at the Quicksort algorithm in this session and see how it works.
* A quick sort first selects a value, which is called the **pivot value**.
* Although there are many different ways to choose the pivot value, we will simply use the first item in the list.
* The role of the pivot value is to assist with splitting the list.
* The actual position where the pivot value belongs in the final sorted list, commonly called the **split point**, will be used to divide the list for subsequent calls to the quick sort.
As per the previous example,
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/593/original/Screenshot_2023-11-22_at_4.40.21_PM.png?1700651431" width=500 />
Now that there are two separate subarrays, we can apply partitioning on both separately and recursively. With each call, pivot element will be placed at its correct possition and eventually all elements will come at their correct place.
### Steps to execute Quick Sort
1. **Pick**: Select an element.
2. **Divide**: Split the problem set, move smaller parts to the left of the pivot and larger items to the right.
3. **Repeat and combine**: Repeat the steps on smaller subarrays and combine the arrays that have previously been sorted.
#### Dry Run
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/736/original/Screenshot_2023-11-23_at_3.45.45_PM.png?1700734589" width=700 />
#### Pseudocode
Below is the code for QuickSort
```java
void quicksort(int[] A, int start, int end) {
if (start < end) {
int pivotIndex = partition(A, start, end);
quicksort(A, start, pivotIndex - 1);
quicksort(A, pivotIndex + 1, end);
}
}
```
---
### Quick Sort Time Complexity and Space Complexity
#### Best-Case Time Complexity:
The best-case scenario for QuickSort occurs when the pivot chosen at each step divides the input into approximately equal-sized subarrays.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/737/original/Screenshot_2023-11-23_at_3.52.53_PM.png?1700735000" width=600 />
#### Worst-Case Time Complexity:
The worst-case scenario for QuickSort occurs when the pivot chosen at each step is either the smallest or largest element in the remaining unsorted portion of the array. This leads to imbalanced partitions, and the algorithm performs poorly. The worst-case time complexity is $O(N^2)$, which occurs when the input is already sorted in ascending or descending order.
> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/738/original/Screenshot_2023-11-23_at_3.53.02_PM.png?1700735046" width=600 />
#### Average-Case Time Complexity
There are many ways to avoid the worst case of quicksort, like choosing the element from the middle of the array as pivot, randomly generating a pivot for each subarray, selecting the median of the first, last, and middle element as pivot, etc. By using these methods, we can ensure equal partitioning, on average. Thus, quick sort's average case time complexity is O(NlogN)
#### Space Complexity
The Space Complexity in quick sort will be because of recursion space. Partition function doesn't take any extra space.
So, space in Quick Sort is only because of Recursion Stack whereas in Merge Sort, the extra space is also taken by Merge Fucntion.
**In Quick Sort**,
In worst case, Space is **O(N)** since in recursive tree we have N levels.
In best case, Space is **O(log N)** since there are log N levels.
---
### Randomised QuickSort
The randomised quicksort is a technique where we randomly pick the pivot element, not necessarily the first and last.
There is a random function available in all the languages, to which we can pass Array and get random index. Now, we can swap random index element with first element and execute our algorithm as it is.
#### Why picking random element helps?
Randomised quicksort help us to get away with the worst case time complexity.
The odds of always choosing the minimum element or maximum element is very low.
**Example:**
Given N elements, probablity that a random element is minimum - 1/N
Probability that again next time the random element is munimum - 1/N-1
Then,.. 1/N-2
Then,.. 1/N-3...
1/N * 1/N-1 * 1/N-2 * .....
1/N!
This value is very small!!
Hence, using randomised quick sort, we can achieve average case of O(N logN) most of the time.
---
## Comparator
* In programming, a **comparator** is a function that compares two values and returns a result indicating whether the values are equal, less than, or greater than each other.
* The **comparator** is typically used in sorting algorithms to compare elements in a data structure and arrange them in a specified order.
**Comparator** is a function that takes **two arguments**.
For languages - **Java, Python, JS, C#, Ruby**, the following logic is followed.
```
1. In sorted form, if first argument should come before second, -ve value is returned.
2. In sorted form, if second argument should come before first, +ve value is returned.
3. If both are same, 0 is returned.
```
For **C++**, following logic is followed.
```
1. In sorted form, if first argument should come before second, true is returned.
2. Otherwise, false is returned.
```
---
### Problem 2 Sorting based on factors
Given an array of size n, sort the data in ascending order of count of factors, if count of factors are equal then sort the elements on the basis of their magnitude.
**Example 1**
```plaintext
A[ ] = { 9, 3, 10, 6, 4 }
Ans = { 3, 4, 9, 6, 10 }
```
**Explanation:**
Total number of factors of 3, 4, 9, 6, 10 are 2, 3, 3, 4, 4.
---
### Question
Given an array A of size n, sort the data in ascending order of count of factors, if count of factors are equal then sort the elements on the basis of their magnitude.
`A = [10, 4, 5, 13, 1]`
**Choices**
- [ ] [1, 4, 5, 10, 13]
- [x] [1, 5, 13, 4, 10]
- [ ] [13, 10, 4, 5, 1]
- [ ] [1, 4, 5, 13, 10]
**Explanation:**
Total number of factors of 1, 5, 13, 4, 10 are 1, 2, 2, 3, 4.
---
### Sorting based on factors Solutions
#### C++
```cpp
int factors(int n) {
int count = 0;
int sq = sqrt(n);
// if the number is a perfect square
if (sq * sq == n)
count++;
// count all other factors
for (int i = 1; i < sqrt(n); i++) {
// if i is a factor then n/i will be
// another factor. So increment by 2
if (n % i == 0)
count += 2;
}
return count;
}
bool compare(int val1, int val2) {
int cnt_x = count_factors(x);
int cnt_y = count_factors(y);
if (factors(val1) == factors(val2)) {
if (val1 < val2) {
return true;
}
return false;
} else if (factors(val1) < factors(val2)) {
return true;
}
return false;
}
vector < int > solve(vector < int > A) {
sort(A.begin(), A.end(), compare);
return A;
}
```
#### Python
```cpp
import functools
//please write the code for finding factors by yourself
def compare(v1, v2):
if (factors(v1) == factors(v2)):
if (v1 < v2):
return -1;
if (v2 < v1):
return 1;
else
return 0;
elif(factors(v1) < factors(v2)):
return -1;
else
return 1;
class Solution:
def solve(self, A):
A = sorted(A, key = functools.cmp_to_key(compare))
return A
```
#### Java
```cpp
//please write the code for finding factors by yourself
public ArrayList < Integer > solve(ArrayList < Integer > A) {
Collections.sort(A, new Comparator < Integer > () {
@Override
public int comp(Integer v1, Integer v2) {
if (factors(v1) == factors(v2)) {
if (v1 < v2) return -1;
else if (v2 < v1) return 1;
return 0;
} else if (factors(v1) < factors(v2)) {
return -1;
}
return 1;
}
});
return A;
}
```
---
### Problem 3 B Closest Points to Origin
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the B closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., $√(x1 - x2)^2 + (y1 - y2)^2$).
You may return the answer in any order.
**Example 1:**
><img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/057/739/original/Screenshot_2023-11-23_at_4.01.31_PM.png?1700735500" width=400/>
>**Input:** points = [[1,3],[-2,2]], B = 1
**Output:** [[-2,2]]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest B = 1 points from the origin, so the answer is just [[-2,2]].
**Example 2:**
>**Input:** points = [[3,3],[5,-1],[-2,4]], B = 2
**Output:** [[3,3],[-2,4]]
**Explanation:** The answer [[-2,4],[3,3]] would also be accepted.
---
**B Closest Points to Origin Approach**
We find the B-th distance by creating an array of distances and then sorting them using custom sorting based on distances from origin or points.
After, we select all the points with distance less than or equal to this K-th distance.
**Logic for Custom Sorting**
Say there are two points, (x1, y1) and (x2, y2),
The distance of (x1, y1) from origin will be ${sqrt((x1-0)^2 + (y1-0)^2)}$
The distance of (x2, y2) from origin will be ${sqrt((x2-0)^2 + (y2-0)^2)}$
We can leave root part and just compare $(x1^2 + y1^2) and (x2^2 + y2^2)$
**Below logic works for languages like - Java, Python, JS, ...**
```cpp
// Need to arrange in ascending order based on distance
// If first argument needs to be placed before, negative gets returned
if((x1*x1 + y1*y1) < (x2*x2 + y2*y2))
return -1;
// If second argument needs to be placed before, positive gets returned
else if ((x1*x1 + y1*y1) > (x2*x2 + y2*y2))
return 1;
// If both are same, 0 is returned
else return 0
---------------------------------------------
// Instead of writing like above, we could have also written
return ((x1*x1 + y1*y1) - (x2*x2 + y2*y2))
```
#### Below logic works for C++
```cpp
// If first argument needs to be placed before, true gets returned
if ((x1 * x1 + y1 * y1) < (x2 * x2 + y2 * y2))
return true;
//Else false is returned
else return false
```
---
### Problem 4 Largest Number
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example 1:
>Input: nums = [10,2]
Output: "210"
Example 2:
>Input: nums = [3,30,34,5,9]
Output: "9534330"
#### Idea:
Should we sort the numbers in descending order and append them ?
While it might be tempting to simply sort the numbers in descending order,
but this doesn't work.
**For example,** sorting the problem example in descending order would produce the number **9534303**, while the correct answer is achieved by putting **3** before **30**.
---
### Question
Given a list of non-negative integers **nums**, arrange them such that they form the largest number and return it.
nums = [10, 5, 2, 8, 200]
**Choices**
- [ ] 20010825
- [x] 85220010
- [ ] 88888888
- [ ] 85200210
**Explanation:**
After rearrangeing the nums, [8, 5, 2, 200, 10] will form the largest number as **"85220010"**.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
---
### Larget Number Approach
We shall use **custom sorting**.
Say we pick two numbers **X** and **Y**. Now, we can check if **`X (appends) Y`** > **`Y (appends) X`**, then it means that **Y** should come before **X**.
For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Once the array is sorted, the most "signficant" number will be at the front.
**Edge Case**
There is a minor edge case that comes up when the array consists of only
zeroes, so if the most significant number is 0, we can simply return 0. Otherwise, we build a string out of the sorted array and return it.
**Example**
Upon sorting this array - **`[3,30,34,5,9]`**,
we shall get - **`[9, 5, 34, 3, 30]`**
Now, we can simply append the numbers to get - **`9534330`**
#### Complexity
**Time complexity :** O(n log n)
Although we are doing extra work in our comparator, it is only by a constant factor. Therefore, the overall runtime is dominated by the complexity of sort, which is O(n log n).
**Space complexity :** O(n)
Space depends on the type of algorithm used by the sort function internally.
---
### Larget Number Codes in different langauges
#### C++
```cpp
bool compare(int a, int b) {
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
}
string largestNumber(vector < int > & A) {
sort(A.begin(), A.end(), compare);
string ans = "";
for (auto & x: A)
ans += to_string(x);
if (ans[0] == '0') return "0";
return ans;
}
```
#### Java
```cpp
public class Solution {
public String largestNumber(ArrayList < Integer > A) {
Collections.sort(A, new Comparator < Integer > () {
public int compare(Integer a, Integer b) {
String XY = String.valueOf(a) + String.valueOf(b);
String YX = String.valueOf(b) + String.valueOf(a);
return XY.compareTo(YX) > 0 ? -1 : 1;
}
});
StringBuilder ans = new StringBuilder();
for (int x: A) {
ans.append(String.valueOf(x));
}
if (ans.charAt(0) == '0')
return "0";
return ans.toString();
}
}
```
#### Python
```cpp
from functools import cmp_to_key
class Solution:
# @param A : list of integers
# @return a strings
def largestNumber(self, A):
def cmp_func(x, y):
if x + y > y + x:
return -1
elif x == y:
return 0
else:
return 1
nums = [str(num) for num in A]
nums.sort(key = cmp_to_key(cmp_func))
if nums[0] == '0':
return '0'
return ''.join(nums)
```
---
### Question
Best case TC of quick sort?
**Choices**
- [ ] N
- [ ] N^2
- [x] N log N
- [ ] Constant
### Question
Worst case TC of quick sort?
**Choices**
- [ ] N
- [x] N^2
- [ ] N log N
- [ ] Constant
---
### Question
Worst case SC of quick sort?
**Choices**
- [x] N
- [ ] N^2
- [ ] N log N
- [ ] Constant
---
### Question
Best case SC of quick sort?
**Choices**
- [ ] N
- [ ] N^2
- [ ] N log N
- [x] log N

View File

@@ -0,0 +1,507 @@
# Stacks 1: Implementation & Basic Problems
---
## Introduction to Stacks with Example
### Definition
* A stack is a linear data structure that stores information in a sequence, from **bottom to top**.
* The data items can only be accessed from the top and new elements can only be added to the top, i.e it follows **LIFO (Last In First Out)** principle.
**Examples**
Before proceeding to more technical examples, let's start from the real life basic examples.
1. **Pile of Plates**:<br> Imagine a scenario where you have a pile of plates, you can only put a plate on the pile from top also only pick a plate from top. You can't really see the plates underneath the top one without first removing the top plate, which means only the first plate is accessible to you.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/269/original/upload_c7cbffcd88e4f6148d52d73c16ab8642.png?1695925299" width=300/>
2. **Stack of Chairs**:<br> We usually place identical chairs on the top of on another, which makes them look like a stack. Similar to the previous example you can only position or choose a chair from top, and you won't be able to take or see the chair in middle without picking out all chairs on top of that one.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/270/original/upload_925bbda5341c2cda418d4a5e79b58961.png?1695925337" width=300/>
### Algorithmic Examples
1. **Recursion**:<br> Recursion happens when a function calls itself. Each call is stacked on top of the previous one. When call execution finishes, control goes back to the second-to-last function call. This all happens with a stack data structure.
2. **Undo / Redo Operations**:<br> In software programs, stacks are commonly used to store the state during Undo and Redo operations. Consider the given example we have performed several calculations here, our first stack stores the current state. As soon as user performs UNDO operation the state is moved to REDO stack so that later it can be restored from there.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/271/original/upload_b94fe74ac3ed8ce1ba35a58b1bc59c49.png?1695925403" width=500/>
---
### Question
What is the most common application of a stack?
**Choices**
- [ ] Evaluating arithmetic expressions
- [ ] Implementing undo/redo functionality
- [ ] Representing parenthesis in expressions
- [x] All of the above
Answer: All of the above
Explanation: Stacks are versatile data structures that find applications in various domains. They are commonly used in expression evaluation, undo/redo functionality, and representing parenthesis in expressions.
---
### Operations on Stack
These operations are generally used on the stack. The time complexity for all of these operations is constant **O(1)**.
#### 1. Push
Push operation is to insert a new element into the top of stack.
```cpp
push(data)
```
#### 2. Pop
Pop operation is to remove an element from the top of stack.
```cpp
pop()
```
#### 3. Peek
Peek means to access the top element of the stack, this operation is also called as **top**.
```cpp
data = peek()
// or
data = top()
```
#### 4. isEmpty
This operation is used to check whether stack is empty or not. It is an important operation because it allows program to run efficiently by checking conditions of overflow and underflow.
```cpp
isEmpty()
```
### Question
What is the time complexity of the push and pop operations in a stack?
**Choices**
- [x] O(1) for both push and pop
- [ ] O(n) for push and O(1) for pop
- [ ] O(1) for push and O(n) for pop
- [ ] O(n) for both push and pop
Answer: O(1) for both push and pop
Explanation: The push and pop operations in a stack operate on the top element, making them constant time operations. This is because the top element is always accessible regardless of the stack's size.
---
### Implement Stack using Arrays
* Just try to think what a data structure is, a data structure is nothing but a way to store some data in memory along with some rules to insert/access/modify that data.
* So, stacks is also a way to store data with LIFO principle. The conclusion of this is we can implement stacks by using arrays.
* You might know that array is filled from left to right so the **rightmost part of the array can act as top of stack**, for each pop operation we can remove the rightmost element from array.
* We can keep track of the top element index in array because we can always know how many elements we have inserted so directly access that index from array to know about top element.
* To store an element we can just add 1 to top index and assign the element.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/272/original/upload_e8a49a3429c4b6c4436549b942d039d1.png?1695925468" width=600/>
#### Pseudocode
```cpp
// Consider an array `A`.
int A[];
// Consider a counter to keep track of stack size and currently used index
int t = -1;
```
1. For push operation we can keep pushing data from left to right.
```cpp
void push(data){
t++;
A[t] = data;
}
```
2. And as we are maintaining a counter we can always access the top element in O(1) by just index access of array.
```cpp
int top(){
return A[t];
}
```
3. To remove element we can simply decrement our counter. Also we can place some value at that index to denote that it is not part of our data.
```cpp
void pop(){
t--;
}
```
4. We are maintaining our counter in such a way that it indicates the size of stack. We can simply perform an equality check on counter to know whether stack is empty.
```cpp
bool isEmpty(){
return t == -1;
}
```
---
### Overflow and Underflow in stack and it's solution
* Overflow occurs when we try to store new data even when there is no empty space in array. For this we have to introduce a overflow condition before push operation.
```cpp
void push(x){
// Whenever our counter reaches to the size of the array
// It means stack is already full
if(t >= A.size())
return;
t++;
A[t] = x;
}
```
* Underflow means when we try to perform pop operation or try to access the element of stack but there are none. Again we have to introduce conditions during pop and top operation.
```cpp
void pop(){
if(!isEmpty()) return;
t--;
}
```
```cpp
int top(){
if(!isEmpty()) return -1;
return A[t];
}
```
### Problem with implementation using Arrays
We have to predefine the size of stack to create array. To overcome this problem we can create a dynamic array which can grow or shrink at runtime according to need.
---
### Question
What happens when you try to pop an element from an empty Stack?
**Choices**
- [ ] It returns null
- [ ] It returns the top element
- [x] It causes an underflow
- [ ] It causes an overflow
Attempting to pop an element from an empty stack will cause an underflow.
---
### Implement Stack using Linked List
* We can also implement stack using linked list, similar to the array it also has constant `O(1)` time complexity for all operations.
* We choose head as our top element because push and pop operations can be executed in `O(1)` in that case.
* Unlike array linkedlist can grow or shrink at runtime, because all operations are performed at head.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/274/original/upload_208dc0a5d19dc57d2f2be8a50c5554c0.png?1695925709" width=500/>
#### Pseudocode
1. To push data into stack, just create a node and attach before head.
```cpp
void push(data) {
new_node = Create a new Node with 'data'
new_node.next = head
head = new_node
// Increment size
t++
}
```
2. To pop data just remove one node from the beginning of linked list.
```cpp
void pop() {
if (!isEmpty()) return;
head = head.next
// Decrement size
t--
}
```
3. To find the data on top just access the head node.
```cpp
int top() {
if (!isEmpty()) return -1;
return head.data;
}
```
> Note: While accessing top value in function, We can use another concept to indicate that stack is empty if we are using -1 as value to store in stack.
---
### Problem 3 Balanced Paranthesis Concept with Implementation
Check whether the given sequence of parenthesis is valid ?
#### Explanation of Problem
Imagine you have a bunch of different types of brackets, like `{` and `}` (curly brackets), `[` and `]` (square brackets), and `(` and `)` (round brackets).
A valid sequence of these brackets means that for every opening bracket, there is a matching closing bracket. It's like having pairs of shoes; you need a left shoe and a right shoe for each pair. In a valid sequence, you have the same number of left and right brackets, and they are correctly matched.
For example, `(({}))` is a valid sequence because for each opening bracket `(` or `{`, there is a corresponding closing bracket `)` or `}`.
On the other hand, `{{})` is not valid because the second curly bracket `}` doesn't have a matching opening bracket, so it's like having an extra right shoe without a left shoe to match with.
In summary, a valid sequence of brackets is like having balanced pairs of brackets, where each opening bracket has a matching closing bracket.
**Technical Application -**
Imagine you are writing a small compiler for your college project and one of the tasks (or say sub-tasks) for the compiler would be to detect if the parenthesis are in place or not.
---
### Question
Which of the following expressions is balanced with respect to parentheses?
**Choices**
- [x] `(a + b) * c`
- [ ] `(a + b)) * c`
- [ ] `(a + b)(c`
- [ ] `(a + b)c`
---
### Balanced Parenthesis Implementation
#### Idea
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/279/original/upload_3ac6edf960237dc2a57e328052515438.png?1695930871" width=500/>
#### Hint
What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression?
The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* Iterate through the sequence, and whenever you encounter an opening parenthesis, you push it onto the stack.
* When you encounter a closing parenthesis, you pop the top element from the stack and compare it to the current closing parenthesis. If they are of the same type (matching), you continue; otherwise, the sequence is invalid.
Additionally, if you finish iterating through the sequence and the stack is not empty, the sequence is also invalid.
#### Pseudocode
```cpp
bool is_valid_parentheses(sequence):
// Initialize an empty stack
For each character 'char' in sequence:
If 'char' is an opening parenthesis ('(', '{', '['):
Push 'char' onto the stack
Else if 'char' is a closing parenthesis (')', '}', ']'):
If the stack is empty:
Return false
Pop the top element from the stack into 'top'
If 'top' is not of the corresponding opening type for 'char':
Return false
If the stack is not empty:
Return false
Else:
Return true
```
#### Dry Run
**Example:** `{()[]}`
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/280/original/upload_eed9c829bc8d00d0ff3ed04247044436.png?1695930919" width=600/>
1. Iterate on the example string.
2. First of all we will encounter `{`. We will push it onto the stack.
3. Next we have `(` again push onto the stack.
4. Now when we encountered `)`, It means there is a match so pop the top element and continue the iteration.
5. In next iteration we will encounter `[`. Similarly we will find the closing bracket in next iteration `]`. Pop that from stack.
6. In the end stack will only contain `{`. Now when we will encounter `}`, we will again pop the topmost bracket.
7. Finally there is nothing to iterate on as well as the stack is now empty. Which means the paranthesis sequence was valid.
---
### Problem 4 Remove equal pair of consecutive elements till possible
Given a string, remove equal pair of consecutive elements till possible
**Example**
Let's say we have a string like `abcddc`, The idea here is to check if there are any consecutive pairs of characters that are the same. In this case, we see `dd` is such a pair. When you find such a pair, you simply remove it from the string, and it becomes `abcc` Then, you repeat the process with the new string, searching for and removing consecutive matching pairs of letters. This cycle continues until there are no more matching pairs left to remove.
In the end the final string would be the solution.
**Approach**
This problem can be solved very efficiently by using the concept of stack. The stack will help you keep track of the elements that haven't been canceled out by a matching element.
```cpp
string remove_equal_pairs(s):
Initialize an empty stack
For each character 'char' in s:
If the stack is not empty and 'char' matches the character at the top of the stack:
Pop the element from the stack
Else:
Push 'char' onto the stack
Initialize an empty string 'result'
While the stack is not empty:
Pop an element from the stack and prepend it to 'result'
Return 'result'
```
#### Complexity
**Time Complexity:** O(n)
**Space Complexity:** O(n)
---
### Question
If we remove equal pair of consecutive characters in this string multiple times then what will be the final string: `abbcbbcacx`
**Choices**
- [ ] empty string
- [ ] ax
- [x] cx
- [ ] x
**Explanation:**
Let's go through the step-by-step process for the given example: `abbcbbcacx`.
1. Begin by pushing `a` onto the stack: **Stack - [a]**
2. Next, push `b` onto the stack: **Stack - [a, b]**
3. During the next iteration, we will encounter `b` which matches the top element `b` of the stack. Continue iterating with a pop operation. **Stack - [a]**
4. Proceed to push `c` during the next iteration, followed by `b`. **Stack - [a, c, b]**
5. During the subsequent iteration, encountering `b` matches the top element of the stack. Since a consecutive pair is found, perform a pop operation to remove the topmost character, which is `b`. **Stack - [a, c]**
6. As we encounter `c` again, and another `c` is already at the top of stack, pop `c` and continue iterating. **Stack - [a]**
7. The stack now contains only `a`. In the next iteration, encountering `a` leads to a pop operation for the existing `a`. **Stack - []**
8. Towards the end, push `c` and `x` onto the stack. Since there's no more to continue, the final stack **[c, x]**, represents the answer.
---
### Problem 5 Evaluate Postfix Expression
Given a postfix expression, evaluate it.
**Postfix Expression** contains operator after the operands.
Below is an example of postfix expression:
```cpp
2 + 3 => Postfix => 2 3 +
```
#### Idea
An operator is present after the operands on which we need to apply that operator, hence stack is perfect data structure for this problem.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
We'll process the expression as follows-
**Example 1**
```cpp
[2, 3, +]
```
1. First we push 2 on stack.
2. Then we push 3.
3. Then we found '`+`', so we will pop top two operands, i.e 3 & 2 in this case
4. Final result is 2 + 3 = 5
**Example 2**
```cpp
[4, 3, 3, *, +, 2, -]
```
1. First we push 4 on stack.
2. Then we push 3 and again 3.
3. Then we found ' `*` ', so we will pop top two operands, i.e 3 & 3 in this case and push 3 * 3 to the stack. So push 9.
4. Again we found '`+`', so pop the top two operands 9 and 4. Apply '`+`' operator 9 + 4 = 13 and push into the stack. Push 13.
5. Push 2.
6. Now we have an operator again '`-`', hence pop top two operands and push the result on the stack. 13-2 = 11. Push 11.
7. In the end the single operand on the stack will be our final answer which is 11.
---
### Question
What is the final answer obtained using the stack-based evaluation algorithm for the expression `[5, 2, *, 3, -]`?
**Choices**
- [ ] 8
- [ ] 13
- [x] 7
- [ ] 15
**Explanation:**
1. Push 5 onto the stack.
`Stack: [5]`
2. Push 2 onto the stack.
`Stack: [5, 2]`
3. Encountering '*' - Pop the top two operands (2 and 5), and push the result (2 * 5 = 10) onto the stack.
`Stack: [10]`
4. Push 3 onto the stack.
`Stack: [10, 3]`
5. Encountering '-' - Pop the top two operands (3 and 10), and push the result (10 - 3 = 7) onto the stack.
`Stack: [7]`
6. Therefore, the final answer obtained using the stack-based evaluation algorithm for the expression `[5, 2, *, 3, -]`is 7.
---
### Question
Evaluate the given postfix expression:
```cpp
3 5 + 2 - 2 5 * -
```
**Choices**
- [ ] 0
- [ ] 4
- [x] -4
- [ ] 8
**Explanation:**
Let's evaluate the given postfix expression step by step: `3 5 + 2 - 2 5 * -`
1. Push 3 onto the stack: **Stack - [3]**
2. Push 5 onto the stack: **Stack - [3, 5]**
3. Encounter '`+`', pop 5 and 3, perform 3 + 5 = 8, push 8 onto the stack: **Stack - [8]**
4. Push 2 onto the stack: **Stack - [8, 2]**
5. Encounter '`-`', pop 2 and 8, perform 8 - 2 = 6, push 6 onto the stack: **Stack - [6]**
6. Push 2 onto the stack: **Stack - [6, 2]**
7. Push 5 onto the stack: **Stack - [6, 2, 5]**
8. Encounter '` * `', pop 5 and 2, perform 2 * 5 = 10, push 10 onto the stack: **Stack - [6, 10]**
9. Encounter '`-`', pop 10 and 6, perform 6 - 10 = -4, push -4 onto the stack: **Stack - [-4]**
10. End of the expression, the stack contains the final result: -4
11. So, the result of the expression `3 5 + 2 - 2 5 * -` is `-4`.
---
### Evaluate Postfix Expression Pseudocode
#### Pseudocode
```cpp
int evaluate_postfix(expression):
Initialize an empty stack
For each element 'element' in expression:
If 'element' is an operand:
Push 'element' onto the stack
Else if 'element' is an operator:
Pop 'operand2' from the stack
Pop 'operand1' from the stack
Perform the operation 'element' on 'operand1' and 'operand2'
Push the result back onto the stack
The final result is at the top of the stack
Pop and return the result
```
#### Complexity
**Time Complexity:** O(n)
**Space Complexity:** O(n)

View File

@@ -0,0 +1,506 @@
# Stacks 2: Nearest Smaller/Greater Element
---
## Problem 1 Nearest smallest element on left
Given an integer array A, find the index of nearest smallest element on left for all i index in A[].
Formally , for all i find j such that `A[j] < A[i]`, `j < i` and j is maximum.
**Example:**
A[] = [8, 2, 4, 9, 7, 5, 3, 10]
Answer = [-1, -1, 1, 2, 2, 2, 1, 6]
For each element in the input array, the output indicates the index of the nearest smaller element on the left side of that element. If there's no smaller element on the left, it's represented by -1.
| Element | Nearest Smaller Element | Index of Nearest Smaller Element |
|:-------:|:-----------------------:|:--------------------------------:|
| 8 | NA | -1 |
| 2 | NA | -1 |
| 4 | 2 | 1 |
| 9 | 4 | 2 |
| 7 | 4 | 2 |
| 5 | 4 | 2 |
| 3 | 2 | 1 |
| 10 | 3 | 6 |
---
### Question
Given N array elements, find the nearest smaller element on the left side for all the elements. If there is NO smaller element on left side, return -1. (Assume all elements are positive).
A = [4, 6, 10, 11, 7, 8, 3, 5]
**Choices**
- [ ] [-1, 4, 6, 10, 4, 7, -1, 3]
- [ ] [-1, 4, 6, 10, 6, 6, -1, 3]
- [x] [-1, 4, 6, 10, 6, 7, -1, 3]
---
### Question
Given N array elements, find the nearest smaller element on the left side for all the elements. If there is NO smaller element on left side, return -1. (Assume all elements are positive).
A = [4, 5, 2, 10, 8, 2]
**Choices**
- [ ] [4, 4, -1, 2, 2, -1]
- [x] [-1, 4, -1, 2, 2, -1]
- [ ] [-1, 4, 4, 2, 2, -1]
- [ ] [-1, 4, 2, 2, 2, 2]
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Nearest smallest element on left Brute Force
For each element in the array, iterate through all the elements to its left.
#### Pseudocode
```java
result[n];
for (int i = 0; i < n; i++) {
int nearestSmaller = -1;
for (int j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
nearestSmaller = j;
break;
}
}
result[i] = nearestSmaller;
}
return result;
```
#### Time Complexity
This approach has a time complexity of $O(n^2)$ because for each element, it requires checking all elements to its left. It is inefficient for large input arrays.
---
### Question
If A = [8, x, x, x, x, 5, x, x, x, x...]
For any element > 5 can the element 8 become nearest smaller element on left?
**Choices**
- [ ] Yes
- [x] No
#### Explanation
Not really since 5 will be the answer for them.
---
### Nearest Smallest Element Optimized Approach
#### Observation/Intuition:
When iterating through the array from left to right, we want to find the nearest smaller element on the left for each element efficiently.
* Using a stack helps us keep track of potential candidates for the nearest smaller element as we move from left to right. The stack stores the indices of elements that have not yet found their nearest smaller element.
* When we encounter a new element, we check if it is smaller than the element at the top of the stack (the most recent candidate for the nearest smaller element). If it is, we know that the element at the top of the stack cannot be the nearest smaller element for any future elements because the new element is closer and smaller. Therefore, we pop elements from the stack until we find an element that is smaller than the current element or until the stack becomes empty.
* The popped elements from the stack are assigned as the nearest smaller elements on the left for the corresponding indices.
* By doing this, we efficiently find the nearest smaller element for each element in the array without the need for nested loops or extensive comparisons, resulting in a linear time complexity of O(n).
#### Optimized Approach:
* Create an empty stack to store the indices of elements.
* Initialize an empty result array with -1 values.
* Iterate through the input array from left to right.
* For each element, while the stack is not empty and the element at the current index is less than or equal to the element at the index stored at the top of the stack, pop elements from the stack and update the result array for those popped elements.
* After the loop, the stack will contain indices of elements that haven't found their nearest smaller element. These elements have no smaller element on the left side.
* The result array will contain the index of the nearest smaller element for all other elements.
* Return the result array.
---
### Nearest Smallest Element Optimized Approach Dry Run
* Initialize an empty stack and an empty result array of the same length as A filled with -1s.
* Start iterating through the array from left to right:
| i | Element | Pop index | Stack | Nearest Smaller Element | Push index |
|:---:|:-------:|:---------:|:-----:|:-----------------------:|:----------:|
| 0 | 8 | NIL | EMPTY | NA | 0 |
| 1 | 2 | 0 | EMPTY | NA | 1 |
| 2 | 4 | NIL | 1 | 2 | 2 |
| 3 | 9 | NIL | 1, 2 | 4 | 3 |
| 4 | 7 | 3 | 1, 2 | 4 | 4 |
| 5 | 5 | 4 | 1, 2 | 4 | 5 |
| 6 | 3 | 5, 2 | 1 | 2 | 6 |
| 7 | 10 | NIL | 1, 6 | 3 | 7 |
**Code:**
```java
for (int i = 0; i < n; i++) {
// While the stack is not empty and the element at the current index is less than or
// equal to the element at the index stored at the top of the stack, pop elements from
// the stack and update the result array.
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
stack.pop();
}
// If the stack is not empty, the top element's index is the nearest smaller element on the left.
if (!stack.isEmpty()) {
result[i] = stack.peek();
}
// Push the current index onto the stack.
stack.push(i);
}
return result;
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Nearest Smallest Element related questions
### Question-2
For all `i`, find nearest smaller or equal element on left
**ANS:** For this question, we need to change the sign from `<=` to `<` in the above code of the approach in line number 5.
### Question-3
For all `i`, find nearest greater element on left
**ANS:** For this question, we need to change the sign from `<=` to `>=` in the above code of the approach.
### Question-4
For all `i`, find nearest greater or equal element on left.
**ANS:** For this question, we need to change the sign from `<=` to `>` in the above code of the approach.
### Question-5
For all `i`, find nearest smaller element on right.
**ANS:** For this question, the for loop iterates through the input array arr in reverse order (from right to left), and it finds the nearest smaller element on the right for each element using a stack.
```java
for (int i = n - 1; i >= 0; i--) {
// While the stack is not empty and the element at the current index is less than or
// equal to the element at the index stored at the top of the stack, pop elements from
// the stack and update the result array.
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
stack.pop();
}
// If the stack is not empty, the top element's index is the nearest smaller element on the right.
if (!stack.isEmpty()) {
result[i] = stack.peek();
}
// Push the current index onto the stack.
stack.push(i);
}
return result;
```
### Question-6
For all `i`, find nearest smaller or equal element on right.
**ANS:** For this question, we need to change the sign from `<=` to `>` in the above code of the approach.
### Question - 7
For all `i`, find nearest greater element on right.
**ANS:** For this question, we need to change the sign from `<=` to `>=` in the above code of the approach.
### Question-8
For all `i`, find the nearest greater or equal element on right.
**ANS:** For this question, we need to change the sign from `<=` to `>` in the above code of the approach.
---
### Problem 2 Largest Rectangle in histogram
Given an integer array A, where
A[i] = height of i-th bar.
Width of each bar is = 1.
Find the area of the largest rectangle formed by continious bars.
**Given Array (heights):** [8, 6, 2, 5, 6, 5, 7, 4]
The goal is to find the largest rectangle that can be formed using continuous bars from this array. In this example, the largest rectangle is formed by bars with heights 5, 6, 5, and 7. The width of each bar is 1, so the area of this rectangle is 5 (height) * 4 (width) = 20.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/493/original/upload_1a381873534ce89cd41fd72c9f479c12.png?1697181086" width=600/>
Sure, here is a brief MCQ based on finding the largest rectangle formed by continuous bars in an integer array representing bar heights:
---
### Question
Find the area of the largest rectangle formed by continious bars.
bars = [1, 2, 3, 2, 1]
**Choices**
- [ ] 5
- [ ] 9
- [ ] 7
- [x] 6
- [ ] 3
**Explanation:**
The largest rectangle is formed from [2, 3, 2] whose contribution is [2, 2, 2] thus the area of the largest rectangle is 6.
#### Largest Rectangle Brute Force
**Brute - Force Approach Pseudo Code:**
```cpp
function findMaxRectangleArea(hist):
maxArea = 0
for i from 0 to len(hist) - 1:
// Consider each bar as a potential starting point
minHeight = hist[i]
for j from i to len(hist) - 1:
// Iterate through bars to the right
minHeight = min(minHeight, hist[j])
width = j - i + 1
area = minHeight * width
maxArea = max(maxArea, area)
return maxArea
```
The brute-force approach involves nested loops and has a time complexity of O(n^2) because it considers all possible combinations of starting and ending points for rectangles.
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
#### Optimized Approch
**Mathematical Representation:**
* Let a[i] represent the height of the bar at index i.
* We use j to represent the index of the nearest smaller bar to the left of i.
* Similarly, we use k to represent the index of the nearest smaller bar to the right of i.
* The area of the rectangle that can be formed with the bar at index i as its base is given by `a[i] * (k - j - 1)`.
**Observation/Intuition:**
* The key insight here is that for each potential base (represented by indices in the stack), we can efficiently calculate the area of the rectangle by finding the width between the current index and the index at the top of the stack.
* By using a stack, we maintain a list of potential bases and calculate the area of rectangles as we encounter new heights, ensuring we consider all possible rectangles efficiently.
**Optimized Approach Pseudo Code:**
```cpp
function findMaxRectangleArea(hist):
stack = [] // Initialize an empty stack to store indices of bars.
maxArea = 0
for i from 0 to len(hist) - 1:
while (stack is not empty and hist[i] < hist[stack.top()]):
// Pop elements from the stack and calculate areas
// with their heights as the potential bases.
height = hist[stack.pop()]
width = (i - stack.top() - 1) if stack is not empty else i
area = height * width
maxArea = max(maxArea, area)
stack.push(i) // Push the current index onto the stack.
while (stack is not empty):
// Process the remaining elements in the stack.
height = hist[stack.pop()]
width = (len(hist) - stack.top() - 1) if stack is not empty else len(hist)
area = height * width
maxArea = max(maxArea, area)
return maxArea
```
**Mathematical Representation of the Answer:**
* The answer (maximum area) is given by the formula:
* $ans ~=~ max(a[i] * (nearest~smaller~right[i] * nearest~smaller~left[i] - 1))$
* Where a[i] is the height of the bar at index i.
* `nearest_smaller_right[i]` is the index of the nearest smaller bar to the right of i.
* `nearest_smaller_left[i]` is the index of the nearest smaller bar to the left of i.
* We subtract 1 from the product of `nearest_smaller_right[i]` and `nearest_smaller_left[i]` to account for the width of the rectangle.
---
### Problem 3 Sum of (Max-Min) of all subarrays
Giver an integer array with distinct integers, for all subarrays find (max-min) and return its sum as the answer.
**Example:**
Given Array: [2, 5, 3]
The goal is to find the sum of the differences between the maximum and minimum elements for all possible subarrays.
* Subarray [2]: Max = 2, Min = 2, Difference = 0
* Subarray [5]: Max = 5, Min = 5, Difference = 0
* Subarray [3]: Max = 3, Min = 3, Difference = 0
* Subarrays of length 2:
* [2, 5]: Max = 5, Min = 2, Difference = 3
* [5, 3]: Max = 5, Min = 3, Difference = 2
* Subarray [2, 5, 3]: Max = 5, Min = 2, Difference = 3
The sum of all differences is 0 + 0 + 0 + 3 + 2 + 3 = 8.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Sum of (Max-Min) of all subarrays Brute force approach
**Brute-Force Approach Pseudo Code:**
```cpp
function sumOfDifferences(arr):
result = 0
for start from 0 to len(arr) - 1:
for end from start to len(arr) - 1:
// Find the maximum and minimum elements within the subarray
maxElement = arr[start]
minElement = arr[start]
for i from start to end:
maxElement = max(maxElement, arr[i])
minElement = min(minElement, arr[i])
// Calculate the difference between the maximum and minimum elements
difference = maxElement - minElement
// Add this difference to the result
result += difference
return result
```
#### Complexity
**Time Complexity:** O(N * N)
**Space Complexity:** O(1)
---
### Question
Giver an integer array, A with distinct integers, for all subarrays find (max-min) and return its sum as the answer.
A = [1, 2, 3]
**Choices**
- [x] 4
- [ ] 6
- [ ] 5
- [ ] 0
#### Explanation:
The goal is to find the sum of the differences between the maximum and minimum elements for all possible subarrays.
Subarrays of length 1:
* [1]: Max = 1, Min = 1, Difference = 0
* [2]: Max = 2, Min = 2, Difference = 0
* [3]: Max = 3, Min = 3, Difference = 0
Subarrays of length 2:
* [1, 2]: Max = 2, Min = 1, Difference = 1
* [2, 3]: Max = 3, Min = 1, Difference = 1
Subarrays of length 3:
* [1, 2, 3]: Max = 3, Min = 1, Difference = 2
The sum of all differences is 0 + 0 + 0 + 1 + 1 + 2 = 4.
---
### Sum of (Max-Min) of all subarrays Optimized approach
#### Optimized Approach
**Intuition:**
* The contribution technique eliminates redundant calculations by efficiently counting the number of subarrays in which each element can be the maximum or minimum element.
* By tracking the elements that are greater or smaller than the current element in both directions, we can calculate their contributions to the sum of (max - min) differences without repeatedly considering the same subarrays.
**Optimized Approach Pseudo code:**
```cpp
function sumOfDifferences(arr):
n = length of arr
left = new array of size n
right = new array of size n
max_stack = empty stack
min_stack = empty stack
result = 0
// Initialize left and right arrays
for i from 0 to n - 1:
left[i] = (i + 1) * (n - i)
right[i] = (i + 1) * (i + 1)
// Calculate left contributions
for i from 0 to n - 1:
while (not max_stack.isEmpty() and arr[i] > arr[max_stack.top()]):
max_stack.pop()
if (max_stack.isEmpty()):
left[i] = (i + 1) * (i + 1)
else:
left[i] = (i - max_stack.top()) * (i + 1)
max_stack.push(i)
// Calculate right contributions
for i from n - 1 to 0:
while (not min_stack.isEmpty() and arr[i] < arr[min_stack.top()]):
min_stack.pop()
if (min_stack.isEmpty()):
right[i] = (n - i) * (n - i)
else:
right[i] = (min_stack.top() - i) * (n - i)
min_stack.push(i)
// Calculate the sum of (max - min) differences
for i from 0 to n - 1:
contribution = (right[i] * left[i]) * arr[i]
result += contribution
return result
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)

View File

@@ -0,0 +1,521 @@
# Trees 1: Structure & Traversal
---
## What is a tree
Till now, we have seen data structures such as Arrays, Linked Lists, Stacks, Queues... They are **Linear Data Structure** which means we can access them in sequencial order.
The other category is **Non Linear Data Structure**
At a lot of places, you must have seen hierarchy - Family, Office, Computer File System, etc. Therefore, there arise a need to be able to store such type of data and process it.
**Tree is an example of a non/linear or hierarchical data structure.**
### Example
Let us see the **hierachy of people in an organization**:
```sql
CEO (Chief Executive Officer)
├── CTO (Chief Technology Officer)
├── Engineering Manager
├── Software Development Team Lead
├── Software Engineer
└── Software Engineer
└── QA Team Lead
├── QA Engineer
└── QA Engineer
└── IT Manager
├── IT Specialist
└── IT Specialist
├── CFO (Chief Financial Officer)
├── Finance Manager
├── Accountant
└── Accountant
└── Procurement Manager
├── Procurement Officer
└── Procurement Officer
└── CMO (Chief Marketing Officer)
├── Marketing Manager
├── Marketing Specialist
└── Marketing Specialist
└── Sales Manager
├── Sales Representative
└── Sales Representative
```
As we know that every tree has roots which are below the leaves but in the computer science the case is different the roots are at the top and leaves below it.
---
## Tree naming
Example
```sql
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
```
* **Node**: An element in a tree that contains data and may have child nodes connected to it. 1, 2, 3, 4, 5, 6, 7, 8.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/525/original/gHw4HO4.png?1697188175" width=500/>
* **Root**:<br> The topmost node in a tree from which all other nodes descend. It has no parent. Node 1 is the root.
* **Parent**:<br> A node that has child nodes connected to it. Nodes 1, 2, 3 and 7..
* **Child**:<br> A node that has a parent node connected to it. Nodes 2, 3, 4, 5, 6, and 7 are children.
* **Leaf**:<br> A node that has no child nodes. It's a terminal node. Nodes 4, 5, 6, and 8 are leaves.
* **Depth:**<br> The level at which a node resides in the tree. The root is at depth 0. Depth of node 1 is 0, 2 and 3 are at depth 1, 4, 5, 6, and 7 are at depth 2, and 8 is at depth 3.
* **Height:**<br> The length of the longest path from a node to a leaf. The height of the tree is the height of the root node. Height of the tree is 3, which is the number of edges from the root to a farthest leaf (8).
* **Subtree**:<br> A tree structure that is part of a larger tree. Subtree rooted at node 2 consists of nodes 2, 4, and 5.
* **Siblings**:<br> Nodes that share the same parent node. Nodes 2 and 3 are siblings.
* **Ancestor:**<br> All nodes from parent to the root node upwards are the ancestors of a node. Nodes 1, 3, 7 are ancestors of node 8.
* **Descendant**:<br> All nodes from child to the leaf node along that path. Nodes 4 and 5 are descendants of node 2.
---
### Question
Can a leaf node also be a subtree?
**Choices**
- [x] YES
- [ ] NO
- [ ] Can't say
**Explanation:**
Yes, a leaf node can also be considered a subtree. A subtree is a portion of a tree structure that is itself a tree.
---
### Question
Do all nodes have a parent node?
**Choices**
- [ ] YES
- [x] NO
- [ ] Can't say
**Explanation:**
In a tree data structure, all nodes except for the root node have a parent node.
---
### Levels of a tree
```sql
1 Level 0
/ \
2 3 Level 1
/ \
4 5 Level 2
```
In this example:
* **Level 0:** Node 1 is at level 0 (root level).
* **Level 1:** Nodes 2 and 3 are at level 1.
* **Level 2:** Nodes 4 and 5 are at level 2.
---
### Question
What is the height of the leaf node in any tree?
**Choices**
- [x] 0
- [ ] 1
- [ ] 2
- [ ] 3
**Explanation**
The height of a leaf node in any tree, including a binary tree, is 0. This is because the height of a node is defined as the length of the longest path from that node to a leaf node, and a leaf node is a node that doesn't have any children. Since there are no edges to traverse from a leaf node to a leaf node, the length of the path is 0.
---
### Binary Tree
A type of tree in which each node can have at most two children i.e, either 0, 1 or 2, referred to as the left child and the right child.
**Example of a binary tree:**
```sql
10
/ \
5 15
/ \ / \
3 8 12 18
```
---
### Traversals in a Tree
### How can we traverse a Tree ?
There are many ways to traverse the tree.
**L:** Left Subtree, **R:** Right Subtree, **N:** Root Node
| L N R | L R N | R N L |
|:---------:|:---------:|:---------:|
| **R L N** | **N L R** | **N R L** |
Having so many traversals can be confusing and are unnecessary. Threfore, a standard has been set where first we'll always consider the Left Subtree and then the Right Subtree.
Therefore, we boil down to 3 traverals.
| L N R | **Named as Inorder** |
|:---------:|:----------------------:|
| **N L R** | **Named as Preorder** |
| **L R N** | **Named as Postorder** |
Names are given w.r.t the position of the root node.
> There are more techniques for traversing a tree that'll be covered in next set of sessions.
#### Pre-order
Pre-order traversal is a depth-first traversal technique used to visit all nodes of a binary tree in a specific order. In pre-order traversal, you start from the root node and follow these steps for each node:
1. Visit the current node.
2. Traverse the left subtree (recursively).
3. Traverse the right subtree (recursively).
**This traversal order ensures that the root node is visited before its children and the left subtree is explored before the right subtree.**
**Example:**
```sql
10
/ \
5 15
/ \ / \
3 8 12 18
```
Pre-order traversal sequence: 10, 5, 3, 8, 15, 12, 18
#### Pseudocode
```cpp
void preorder(root) {
if (root == null)
return;
print(root.data); //node
preorder(root.left); //left
preorder(root.right) //right
}
```
#### In-order traversal
In-order traversal is another depth-first traversal technique used to visit all nodes of a binary tree, but in a specific order. In in-order traversal, you follow these steps for each node:
1. Traverse the left subtree (recursively).
2. Visit the current node.
3. Traverse the right subtree (recursively).
**This traversal order ensures that nodes are visited in ascending order if the binary tree represents a search tree.**
Here's an example of in-order traversal on a binary tree:
```cpp
10
/ \
5 15
/ \ / \
3 8 12 18
```
In-order traversal sequence: 3, 5, 8, 10, 12, 15, 18
#### Pseudocode
```cpp
void inorder(root) {
if (root == null)
return;
inorder(root.left); //left
print(root.data); //node
inorder(root.right) //right
}
```
#### Post-order Traversal
Post-order traversal is another depth-first traversal technique used to visit all nodes of a binary tree, but in a specific order. In post-order traversal, you follow these steps for each node:
1. Traverse the left subtree (recursively).
2. Traverse the right subtree (recursively).
3. Visit the current node.
**This traversal order ensures that nodes are visited from the bottom up, starting from the leaf nodes and moving towards the root node.**
**Example**
```cpp
10
/ \
5 15
/ \ / \
3 8 12 18
```
Post-order traversal sequence: 3, 8, 5, 12, 18, 15, 10
#### Pseudocode:
```cpp
void postorder(root) {
if (root = null) return;
postorder(root.left) left
postorder(root.right) right
print(root.data) Node
}
```
---
### Question
What is the inorder traversal sequence of the below tree?
```cpp
1
/ \
2 4
/ / \
3 5 6
```
**Choices**
- [ ] [1, 2, 3, 4, 5, 6]
- [x] [3, 2, 1, 5, 4, 6]
- [ ] [3, 2, 1, 4, 5, 6]
- [ ] [4, 5, 6, 1, 2, 3]
**Explanation**
The inorder traversal sequence is [3, 2, 1, 5, 4, 6].
---
### Iterative Inorder traversal
### Approach:
* Iterative Inorder traversal is a method to visit all the nodes in a binary tree in a specific order without using recursion.
* In the case of Inorder traversal, you visit the nodes in the following order: left subtree, current node, right subtree.
* Here's how you can perform an iterative Inorder traversal using a stack data structure, along with an example:
Let's say we have the following binary tree as an example:
```cpp
1
/ \
2 3
/ \
4 5
```
#### Dry-Run:
* Start at the root node (1).
* Push 1 onto the stack and move left to node 2.
* Push 2 onto the stack and move left to node 4.
* Push 4 onto the stack and move left; there are no left children, so pop 4, visit it, and move right (which is null).
* Pop 2, visit it, and move to its right child, node 5.
* Push 5 onto the stack and move left; there are no left children, so pop 5, visit it, and move right (which is null).
* Pop 1, visit it, and move to its right child, node 3.
* Push 3 onto the stack and move left; there are no left children, so pop 3, visit it, and move right (which is null).
* The stack is empty, and all nodes have been visited.
* So, the iterative Inorder traversal of the tree is 4, 2, 5, 1, 3.
#### Need of recursion/stack:
In inorder traversal of a binary tree, you need a data structure like a stack or recursion because you need to keep track of the order in which you visit the nodes of the tree. The reason for using these techniques is to handle the backtracking that's inherent in traversing a binary tree in inorder fashion. In a binary tree's inorder traversal, you visit nodes in a specific order: left, current, right. You use a stack or recursion to remember where you left off in the tree when moving between nodes, ensuring you visit nodes in the correct order and navigate through the tree efficiently. This backtracking is essential for proper traversal.
#### Pseudocode:
```cpp
cur = root;
while (cur != null || st.isempty()) {
if (cur != null) {
st.push(curr)
cur = cur.left;
} else {
cur = st.pop();
print(cur.data)
cur = cur.right
}
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Construct binary tree from inorder and post order
Constructing a binary tree from its inorder and postorder traversals involves a recursive process. Here's a brief explanation with an example:
#### Brute-Force Approach
* Generate all possible permutations of the given inorder traversal.
* For each permutation, check if it forms a valid binary tree when combined with the given postorder traversal.
* Return the first valid binary tree found.
**Example:**
Inorder: [4, 2, 7, 5, 1, 3, 6]
Postorder: [4, 7, 5, 2, 6, 3, 1]
#### Dry-Run:
* Identify the root: In the postorder traversal, the last element is 1, which is the root of the binary tree.
* Split into left and right subtrees: In the inorder traversal, find the position of the root element (1). Elements to the left of this position represent the left subtree, and elements to the right represent the right subtree.
* Recurse on left subtree: For the left subtree, the root is 2 (found in postorder traversal). Split the left subtree's inorder and postorder traversals, and repeat the process.
* Recurse on right subtree: For the right subtree, the root is 3 (found in postorder traversal). Split the right subtree's inorder and postorder traversals, and repeat the process.
* Continue the recursion: Repeat steps 3 and 4 for each subtree until the entire binary tree is constructed.
#### Pseudocode:
```cpp
function buildTreeBruteForce(inorder, postorder):
for each permutation of inorder:
if formsValidBinaryTree(permutation, postorder):
return constructBinaryTree(permutation, postorder)
return null
```
#### Complexity
**Time Complexity:** O(N! * N)
**Space Complexity:** O(N)
---
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
### Most-Optimised Approach:
* The last element in the postorder traversal is the root of the binary tree.
* Find the root element in the inorder traversal to determine the left and right subtrees.
* Recursively repeat the process for the left and right subtrees.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/527/original/M1IKDA8.png?1697188735" width=300/>
Now as we can see in the above image let us understand this with the help of a dry/run:
#### Dry-Run/Example:
inorder={4,2,7,5,1,3,6} and postorder={4,7,5,2,6,3,1}
1. The last element in the postorder traversal is 1, which is the root of the binary tree.
Binary Tree:
```plaintext
1
```
2. Find 1 in the inorder traversal to split it into left and right subtrees. The elements to the left are the left subtree, and the elements to the right are the right subtree.
```cpp
Inorder: [4,2,7,5,1,3,6]
Postorder: [4,7,5,2,6,3,1]
```
Left Subtree (Inorder: [4,2,7,5], Postorder: [4,7,5,2]):
```cpp
1
/
2
\
5
/ \
4 7
```
Right Subtree (Inorder: [3,6], Postorder: [6,3]):
```cpp
6
\
3
```
3. Repeat the process for the left and right subtrees:
For the left subtree:
* The last element in the postorder traversal is 2, which is the root of the left subtree.
* Find 2 in the inorder traversal to split it into left and right subtrees.
* Left Subtree (Inorder: [4], Postorder: [4]):
```cpp
2
/
4
```
Right Subtree (Inorder: [7,5], Postorder: [7,5]):
```cpp
5
/
7
```
For the right subtree:
* The last element in the postorder traversal is 3, which is the root of the right subtree.
* Find 3 in the inorder traversal to split it into left and right subtrees.
* Left Subtree (Inorder: [6], Postorder: [6]):
```cpp
3
\
6
```
The final binary tree would look like this:
```cpp
1
/ \
2 3
/ \ \
4 5 6
/
7
```
---
### Question
The inorder traversal sequence `[4, 2, 5, 1, 6, 3]` and the postorder traversal sequence `[4, 5, 2, 6, 3, 1]`. What is the root of the binary tree?
**Choices**
- [x] 1
- [ ] 2
- [ ] 3
- [ ] 4
**Explanation:**
In postorder traversal, the last element is always the root of the tree, so here, 1 is the root.
---
### Construct binary tree Pseudocode
#### Pseudocode:
* rootIndex is the index of the root value in the inorder array.
* rootIndex + 1 represents the start of the right subtree in the arrays.
* end represents the end of the right subtree in the arrays.
* start represents the start of the left subtree in the arrays.
* rootIndex - 1 represents the end of the left subtree in the arrays.
```cpp
function buildTree(inorder, postorder):
if postorder is empty:
return null
// The last element in postorder is the root of the current subtree
rootValue = postorder.last
root = new TreeNode(rootValue)
// Find the index of the rootValue in inorder to split it into left and right subtrees
rootIndex = indexOf(inorder, rootValue)
// Recursive call for right subtree
root.right = buildTree(subarray(inorder, rootIndex + 1, end), subarray(postorder, rootIndex, end - 1))
// Recursive call for left subtree
root.left = buildTree(subarray(inorder, start, rootIndex - 1), subarray(postorder, start, rootIndex - 1))
return root
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)

View File

@@ -0,0 +1,601 @@
# Advanced DSA : Trees 2: Views & Types
---
## Level Order Traversal
Input: 1, 2, 3, 5, 8, 10, 13, 6, 9, 7, 4, 12, 11.
The diagram for the following nodes will be:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/528/original/EBDvTnv.jpg?1697189390" width=500 />
```cpp
1
2 3
5 8 10 13
6 9 7 4
12 11
```
---
### Question
Will the last level node always be a leaf node?
**Choices**
- [x] YES
- [ ] NO
- [ ] Cant say
**Explanation**
Yes, in the context of a binary tree's right view, the last level node will always be a leaf node. This is because the right view of a binary tree focuses on the rightmost nodes at each level as seen from a top-down view.
---
### Question
Which traversal is best to print the nodes from top to bottom?
**Choices**
- [x] Level order traversal
- [ ] Pre order
- [ ] post order
**Explanation:**
When you want to print nodes from top to bottom, the level-order traversal, also known as Breadth-First Search (BFS), is the best choice. Level-order traversal ensures that nodes at the same level are processed before moving to the next level. This results in a top-to-bottom exploration of the tree.
---
### Level order traversal Observations
#### Observations:
* Level order traversal visits nodes level by level, starting from the root.
* It uses a queue to keep track of the nodes to be processed.
* Nodes at the same level are processed before moving on to the next level.
* This traversal ensures that nodes at higher levels are visited before nodes at lower levels.
Since this will be done level by level hence we will be requiring a queue data structure to solve this problem:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/529/original/Wf3Hhch.png?1697189478" width=500/>
After the whole process the queue data strucutre will look somewhat like this:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/530/original/8VJIelj.png?1697189508" width=500/>
Like this(in theabove example) it will be done for all of the nodes.
Let us see the pseudocde to solve the problem in printing in one line only:
#### Pseudocode:
```cpp
q.enqueue(root) {
while (!q.eempty()) {
x = q.dequeue()
print(x.data)
if (x.left != null) q.enqueue(x.left)
if (x.right != null) q.enqueue(x.right)
}
}
```
Each level will be printed in seperate line:
```cpp
1
2 3
5 8 10 13
6 9 7 4
12 11
```
#### Observations:
* Level order traversal prints nodes at the same depth before moving to the next level, ensuring that nodes on the same level are printed on separate lines.
#### Approach:
1. Start with the root node and enqueue it.
2. Initialize last as the root.
3. While the queue is not empty:
* Dequeue a node, print its data.
* Enqueue its children (if any).
* If the dequeued node is the same as last, print a newline and update last.
#### Dry-Run:
```cpp
1
/ \
2 3
/ \
4 5
```
* Enqueue root node 1 and initialize last as 1.
* Dequeue 1 and print it. Enqueue its children 2 and 3.
* Dequeue 2 and print it. Enqueue its children 4 and 5.
* Dequeue 3 and print it. Since 3 is the last node in the current level, print a newline.
* Dequeue 4 and print it. There are no children to enqueue for 4.
* Dequeue 5 and print it. There are no children to enqueue for 5.
**Final Output:**
```plaintext
1
2
3
4
5
```
Let us see the pseudocode to solve the problem in printing in **seperate** line only:
#### Pseudocode:
```cpp
q.enqueue(root) {
last = root;
while (!q.empty()) {
x.dequeue()
print(x.data)
if (x.left != null) q.enqueue(x.left)
if (x.right != null) q.enqueue(x.right)
if (x == last && !q.empty()) {
print("\n");
last = q.rear();
}
}
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
---
### Problem 2 Right and left view
### Example:
Let us see an example below:
```cpp
1
/ \
2 3
/ \ \
4 5 6
\
7
```
The right view of this tree would be [1, 3, 6, 7] when viewed from the right side.
To solve this we need to print last node of every level.
---
### Question
Print right view of the given binary tree,
```cpp
1
/ \
2 3
\ \
5 6
/ \
8 7
/ \
9 10
```
**Choices**
- [ ] [1, 3, 6, 7]
- [ ] [1, 3, 6, 8, 9]
- [ ] [1, 3, 6, 7, 8, 9, 10]
- [x] [1, 3, 6, 7, 10]
- [ ] [1, 2, 5]
---
### Right view Observations
#### Observations/Idea
* The idea behind obtaining the right view of a binary tree is to perform a level-order traversal, and for each level, identify and print the rightmost node. This process ensures that we capture the rightmost nodes at each level, giving us the right view of the binary tree. We can obtain the right-view of the tree using a breadth-first level-order traversal with a queue and a loop.
#### Approach:
1. Initialize an empty queue for level order traversal and enqueue the root node.
2. While the queue is not empty, do the following:
* Get the number of nodes at the current level (levelSize) by checking the queue's size.
* Iterate through the nodes at the current level.
* If the current node is the rightmost node at the current level, print its value.
* Enqueue the left and right children of the current node if they exist.
* Repeat this process until the queue is empty.
Let us see the pseudocode to solve the problem:
#### Pseudocode:
```cpp
q.enqueue(root)
last = root;
while (!q.empty(1)) {
x = q.dequeue()
if (x.left != null) q.enqueue(x.left)
if (x.right != null) q.enqueue(x.right)
if (x == last) {
print(x.data)
if (!q.empty()) {
print("\n");
last = q.rear();
}
}
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(M)
---
### Vertical Order traversal
**Examples:**
Consider the following binary tree:
```cpp
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
```
Vertical order traversal of this tree would yield the following output:
```cpp
Vertical Line 1: 4
Vertical Line 2: 2, 8
Vertical Line 3: 1, 5, 6
Vertical Line 4: 3, 9
Vertical Line 5: 7
```
We need to print the vertical lines from top to bottom.
---
### Question
Consider the following binary tree:
```cpp
1
/ \
2 3
\ \
5 6
/ \
8 7
/ \
9 10
```
Pick the vertical order traversal of the given Binary Tree.
**Choices**
- [x] [2, 1, 5, 9, 3, 8, 6, 10, 7]
- [ ] [1, 2, 5, 3, 6, 8 ,9, 10, 7]
- [ ] [1, 2, 3, 5, 6, 8, 7, 9, 10]
- [ ] [1, 5, 2, 3, 6, 10, 8, 7, 9]
**Explanation:**
Vertical order traversal of this tree would yield the following output:
```cpp
Vertical Line 1: 2
Vertical Line 2: 1, 5, 9
Vertical Line 3: 3, 8
Vertical Line 4: 6, 10
Vertical Line 5: 7
```
---
### Vertical Order traversal Observations
#### Observation:
* Vertical order traversal of a binary tree prints nodes column by column, with nodes in the same column printed together.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
These are the steps to Print vertical order traversal:
#### Approach:
* Assign horizontal distances to nodes (root gets distance 0, left decreases by 1, right increases by 1).
* Create a map/hash table where keys are distances and values are lists of node values.
* Update the map while traversing: append node values to corresponding distance lists.
* After traversal, print the values from the map in ascending order of distances.
---
### Vertical Order traversal Pseudocode
#### Pseudocode
Let us see the pseudocode to solve this:
```cpp
procedure levelOrderTraversal(root)
if root is null
return
Create a queue
Enqueue root
while queue is not empty
currentNode = dequeue a node from the queue
print currentNode's value
if currentNode has left child
enqueue left child
end if
if currentNode has right child
enqueue right child
end if
end while
end procedure
```
---
### Problem 4 Top View
**Example:**
Consider the following binary tree:
```cpp
1
/ \
2 3
/ \ / \
4 5 6 7
```
The top view of this tree would be [4, 2, 1, 3, 7].
---
### Question
Consider the following binary tree:
```cpp
1
/ \
2 3
\ \
5 6
/ \
8 9
```
What is the top view of the given binary tree.
**Choices**
- [ ] [5, 2, 1, 3, 6, 9]
- [ ] [8, 5, 2, 1, 3, 6, 9]
- [ ] [2, 1, 5, 3, 8, 6, 9]
- [x] [2, 1, 3, 6, 9]
**Explanation:**
The Top view of the Given Binary tree is [2, 1, 3, 6, 9].
---
### Top View Observations
#### Observations:
* Assign Horizontal Distances: Nodes are assigned horizontal distances, with the root at distance 0, left children decreasing by 1, and right children increasing by 1. This helps identify the nodes in the top view efficiently.
#### Approach:
For this we need to follow these steps:
* Traverse the binary tree.
* Maintain a map of horizontal distances and corresponding nodes.
* Only store the first node encountered at each unique distance.
* Print the stored nodes in ascending order of distances to get the top view.
#### Pseudocode:
```cpp
procedure topView(root)
if root is null
return
Create an empty map
Queue: enqueue (root, horizontal distance 0)
while queue is not empty
(currentNode, currentDistance) = dequeue a node
if currentDistance is not in the map
add currentDistance and currentNode's value to map
enqueue (currentNode's left child, currentDistance - 1) if left child exists
enqueue (currentNode's right child, currentDistance + 1) if right child exists
Print values in map sorted by keys
end procedure
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(W)
---
### Types of binary tree
1. **Proper Binary Tree (Strict Binary Tree):**
Every node has either 0 or 2 children (never 1 child).
Diagram:
```cpp
A
/ \
B C
/ \ / \
```
2. **Complete Binary Tree:**
All levels are filled except possibly the last level, which is filled left to right.
Diagram:
```cpp
A
/ \
B C
/ \ /
```
3. **Perfect Binary Tree:**
All internal nodes have exactly two children, and all leaf nodes are at the same level.
Diagram:
```cpp
A
/ \
B C
/ \ / \
```
---
### Question
Perfect Binary Trees are also:
**Choices**
- [ ] Proper binary tree
- [ ] Complete binary tree
- [x] both
- [ ] none
**Explanation:**
A perfect binary tree is a specialized case of both a proper binary tree and a complete binary tree, where all internal nodes have two children, all leaf nodes are at the same level, and all levels are completely filled.
---
### Problem 5 : Check height balanced tree
### Definition
For all nodes if(`height_ofleftchild-height_ofrightchild`) <= 1
**Example:**
```cpp
1
/ \
2 3
/ \
4 5
/
6
```
This tree is not height-balanced because the left subtree of node 2 has a height of 3, while the right subtree of node 2 has a height of 0, and the difference is greater than 1.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
### Brute Force
#### Approach
* For each node in the binary tree, calculate the height of its left and right subtrees.
* Check if the absolute difference between the heights of the left and right subtrees for each node is less than or equal to 1.
* If step 2 is true for all nodes in the tree, the tree is height-balanced.
#### Pseudocode:
```cpp
// Helper function to calculate the height of a tree
function calculateHeight(root):
if root is null:
return -1
return 1 + max(calculateHeight(root.left), calculateHeight(root.right))
function isHeightBalanced(node):
if node is null:
return true // An empty tree is height-balanced
// Check if the current node's subtrees are height-balanced
leftHeight = calculateHeight(node.left)
rightHeight = calculateHeight(node.right)
// Check if the current node is height-balanced
if abs(leftHeight - rightHeight) > 1:
return false
// Recursively check the left and right subtrees
return isHeightBalanced(node.left) && isHeightBalanced(node.right)
// Example usage:
root = buildTree() // Build your binary tree
result = isHeightBalanced(root)
```
> NOTE: For a null node: **height = -1**
#### Complexity
**Time Complexity:** $O(N^2)$
**Space Complexity:** O(N)
---
### Question
Which traversal is best to use when finding the height of the tree?
**Choices**
- [ ] Level order
- [ ] Inorder
- [x] postorder
- [ ] preorder
**Explanation:**
Postorder traversal works best for calculating the height of a tree because it considers the height of subtrees before calculating the height of parent nodes, which mirrors the hierarchical nature of tree height calculation.
---
### Check height balanced tree Optimised Approach
#### Observation/Idea:
* To solve the problem of determining whether a binary tree is height-balanced we can consider using a recursive approach where you calculate the height of left and right subtrees and check their balance condition at each step. Keep track of a boolean flag to indicate whether the tree is still balanced.
#### Approach:
* We use a helper function height(root) to calculate the height of each subtree starting from the root.
* In the height function:
* If the root is null (i.e., an empty subtree), we return -1 to indicate a height of -1.
* We recursively calculate the heights of the left and right subtrees using the height function.
* We check if the absolute difference between the left and right subtree heights is greater than 1. If it is, we set the ishb flag to false, indicating that the tree is not height-balanced.
* We return the maximum of the left and right subtree heights plus 1, which represents the height of the current subtree.
* The ishb flag is initially set to true, and we start the height calculation from the root of the tree.
* If, at any point, the ishb flag becomes false, we know that the tree is not height-balanced, and we can stop further calculations.
* After the traversal is complete, if the ishb flag is still true, the tree is height-balanced.
#### Example:
```cpp
1
/ \
2 3
/ \
4 5
```
This tree is height-balanced because the height of the left and right subtrees of every node differs by at most 1.
#### Pseudocode
```cpp
int height(root, ishb) {
if (root == null) return -1;
l = height(root.left)
r = height(root.right)
if (abs(l - r) > 1) ishb = false;
return max(l, r) + 1
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(log N)

View File

@@ -0,0 +1,484 @@
# Advanced DSA : Trees 3: BST
---
## Binary Search Tree
Binary search tree is searching data in an organized dataset using divide and conquer.
For a node X in a binary search tree everything on the left has data less than x and on the right greater than x.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/535/original/6mtWOem.png?1697191199" width=500/>
Example of a binary search tree:
```cpp
5
/ \
3 8
/\ /\
1 4 6 9
```
---
### Question
What is a Binary Search Tree (BST)?
**Choices**
- [ ] A tree with only two nodes
- [ ] A tree where the left child of a node has a value <= the node, and the right child has a value > the node
- [x] A tree where for a node x, everything on the left has data <= x and on the right > x.
- [ ] A tree that has height log N.
---
### Problem 1 Searching in Binary Search Tree
Searching in a Binary Search Tree (BST) involves utilizing the property that values in the left subtree are smaller and values in the right subtree are larger than the current node's value. This property allows for efficient search operations.
Here's an example using the BST diagram from earlier:
```cpp
5
/ \
3 8
/\ /\
1 4 6 9
```
**Suppose you're searching for the value 6:**
* Start at the root (value 5).
* Compare 6 with 5. Since 6 is greater, move to the right child (value 8).
* Compare 6 with 8. Since 6 is smaller, move to the left child (value 6).
* The value 6 matches the current node's value, so the search is successful.
---
### Question
What is the number of nodes you need to visit to find the number `1` in the following BST?
```cpp
5
/ \
3 8
/\ /\
1 4 6 9
```
**Choices**
- [ ] 2
- [x] 3
- [ ] 4
- [ ] 1
**Explanation**
First node: 5. From 5 you move left.
Second node: 3. From 3 you move left, again.
Third node: 1. You finally get 1.
---
### Searching in Binary Search Tree Pseudo Code
#### Pseudo Code
```cpp
function search(root, target):
if root is None:
return None
if root.value == target:
return root
if target < root.value:
return search(root.left, target)
if target > root.value:
return search(root.right, target)
```
---
### Problem 2 Insertion in Binary Search Tree
### Insertion in BST:
Inserting a new value into a Binary Search Tree (BST) involves maintaining the property that values in the left subtree are smaller and values in the right subtree are larger than the current node's value.
Here's an example using the BST diagram from earlier:
```cpp
5
/ \
3 8
/\ /\
1 4 6 9
```
**Suppose you want to insert the value 7:**
* Start at the root (value 5).
* Compare 7 with 5. Since 7 is greater, move to the right child (value 8).
* Compare 7 with 8. Since 7 is smaller, move to the left child (value 6).
* Compare 7 with 6. Since 7 is greater, move to the right child (null).
* Insert the value 7 as the right child of the node with value 6.
The updated tree after insertion:
```cpp
5
/ \
3 8
/\ /\
1 4 6 9
\
7
```
#### Pseudocode:
```cpp
function insert(root, value):
if root is null:
return createNode(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
```
---
### Question
Where does the node with the smallest value resides in a BST?
**Choices**
- [x] We keep on going left and we get the smallest one.
- [ ] Depends on the tree.
- [ ] We keep on going right and we get the smallest one.
- [ ] The root node.
For every node, we need to go to its left, that's the only way we can reach the smallest one.
---
### Problem 3 Find smallest in Binary Search Tree
Find smallest in Binary Search Tree
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach**
The left most node in the tree, will be the smallest.
**Example:**
Suppose we have the following BST:
```cpp
5
/ \
3 8
/ \ \
2 4 9
```
To find the smallest element:
* Start at the root node (5).
* Move to the left child (3).
* Continue moving to the left child until you reach a node with no left child.
* The node with no left child is the smallest element in the BST. In this case, it's the node with the value 2.
* So, in this example, the smallest element in the BST is 2.
#### Pseudocode
```cpp
temp = root // not null
while (temp.left != null) {
temp = temp.left
}
return temp.data;
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 4 Find largest in Binary Search Tree
#### Approach
The right most node in the tree, will be the largest.
**Example:**
Suppose we have the following BST:
```cpp
5
/ \
3 8
/ \ \
2 4 9
```
* To find the largest element:
* Start at the root node (5).
* Move to the right child (8).
* Continue moving to the right child until you reach a node with no right child.
* The node with no right child is the largest element in the BST. In this case, it's the node with the value 9.
* So, in this example, the largest element in the BST is 9.
#### Pseudocode
```cpp
temp = root // not null
while (temp.right != null) {
temp = temp.right
}
return temp.data;
```
---
### Problem 5 Deletion in Binary Search Tree
Deleting a node from a Binary Search Tree (BST) involves maintaining the BST property while handling various cases depending on the node's structure. Here's how the deletion process works:
* Find the Node to Delete: Start at the root and traverse the tree to find the node you want to delete. Remember to keep track of the parent node as well.
#### Case 1: Node with No Children (Leaf Node)
In this case, we have a node with no children (a leaf node). Deleting it is straightforward; we simply remove it from the tree.
**Example:**
Suppose we have the following BST, and we want to delete the node with the value 7.
```cpp
10
/ \
5 15
/ \ / \
3 7 12 18
```
After deleting the node with the value 7, the tree becomes:
```cpp
10
/ \
5 15
/ / \
3 12 18
```
#### Case 2: Node with One Child
In this case, the node to be deleted has only one child. To delete it, we replace the node with its child.
**Example:**
Suppose we have the following BST, and we want to delete the node with the value 5.
```cpp
10
/ \
5 15
/ / \
3 12 18
```
After deleting the node with the value 5, we replace it with its child (3):
```cpp
10
/ \
3 15
/ \
12 18
```
#### Case 3: Node with Two Children
In this case, the node to be deleted has two children. To delete it, we find either the in-order predecessor or successor and replace the node's value with the value of the predecessor or successor. Then, we recursively delete the predecessor or successor.
**Example:**
Suppose we have the following BST, and we want to delete the node with the value 10 (which has two children).
```cpp
10
/ \
5 15
/ \ / \
3 9 12 18
```
To delete the node with value 10, we can either choose its in-order predecessor (9) or in-order successor (12). Let's choose the in-order predecessor (9):
* Find the in-order predecessor (the largest value in the left subtree). In this case, it's 9.
* Replace the value of the node to be deleted (10) with the value of the in-order predecessor (9).
* Recursively delete the in-order predecessor (9), which falls into either Case 1 (no children) or Case 2 (one child).
* After deleting the node with the value 10, the tree becomes:
```cpp
9
/ \
5 15
/ / \
3 12 18
```
These are the three main cases for deleting a node in a Binary Search Tree (BST).
#### Pseudo Code
Here's the pseudo code with each of the cases mentioned.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/059/687/original/Screenshot_2023-12-19_at_9.48.10_PM.png?1703002703" width=550 />
### Question
What is the purpose of balancing a Binary Search Tree?
**Choices**
- [ ] To make it visually appealing
- [ ] To ensure all nodes have the same value
- [x] To maintain efficient search, insert, and delete operations
- [ ] Balancing is not necessary in a Binary Search Tree
---
### Problem 6 Construct a binary search tree
#### Approach:
* Find the middle element of the sorted array.
* Create a new node with this middle element as the root of the tree.
* Recursively repeat steps 1 and 2 for the left and right halves of the array, making the middle element of each subarray the root of its respective subtree.
* Continue this process until all elements are processed.
* The final tree will be a valid BST with the given sorted array as its inorder traversal.
* Here's an example construction of a BST using the values 8, 3, 10, 1, 6, 14, 4, 7, and 13:
#### Example:
* Sorted Array - 1, 3, 4, 6, 7, 8, 10, 13, 14
* Create the root node with value 8.
* Insert 3: Move to the left child of the root (value 3).
* Insert 10: Move to the right child of the root (value 10).
* Insert 1: Move to the left child of the node with value 3 (value 1).
* Insert 6: Move to the right child of the node with value 3 (value 6).
* Insert 14: Move to the right child of the root (value 14).
* Insert 4: Move to the left child of the node with value 6 (value 4).
* Insert 7: Move to the right child of the node with value 6 (value 7).
* Insert 13: Move to the left child of the node with value 14 (value 13).
The constructed BST:
```cpp
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
```
#### Pseudocode:
```cpp
function insert(root, value):
if root is null:
return [value, null, null]
if value < root[0]:
root[1] = insert(root[1], value)
else:
root[2] = insert(root[2], value)
return root
// Construct a BST by inserting values
root = null
values = [8, 3, 10, 1, 6, 14, 4, 7, 13]
for each value in values:
root = insert(root, value)
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(logn)
---
### Problem 7 Check if a binary tree is a binary search tree
To check if a binary tree is a binary search tree (BST), you can perform an inorder traversal of the tree and ensure that the values encountered during the traversal are in ascending order. Here's how you can do it:
**Conditions are:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/053/537/original/yd0ry4C.png?1697191775" width=500/>
#### Approach:
* Perform an inorder traversal of the binary tree.
* During the traversal, keep track of the previously visited node's value.
* At each step, compare the current node's value with the previously visited node's value.
* If the current node's value is less than or equal to the previously visited node's value, the tree is not a BST.
* If you complete the entire traversal without encountering any violations of the BST property, the tree is a BST.
**Example:**
Suppose we have the following binary tree:
```cpp
4
/ \
2 6
/ \ / \
1 3 5 7
```
* Initialize prevValue as -∞ (negative infinity).
* Begin the inorder traversal:
* Start at the root node (4).
* Recursively traverse the left subtree (node 2).
* Check 2 > -∞, so it's okay.
* Update prevValue to 2.
* Recursively traverse the left subtree (node 1).
* Check 1 > 2. This is a violation.
* Since there's a violation, the tree is not a BST.
---
### Question
Check where the given binary tree is a Binary Search Tree.
```cpp
5
/ \
2 6
/ \ / \
1 3 4 7
```
**Choices**
- [ ] Yes, It is a Binary Search Tree
- [x] No, It is not a Binary Search Tree
- [ ] May be
- [ ] Not sure
**Explanation:**
No, It is not a Binary Search Tree.
The node with the value 4 should not be on the right sub of the root node, since the root is 5, the node has to be placed on left subtree.
---
### Pseudocode:
```cpp
function isBST(root):
// Initialize a variable to keep track of the previously visited node's value
prevValue = -infinity // A small negative value
// Helper function for the inorder traversal
function inorderTraversal(node):
if node is null:
return true // Reached the end of the subtree, no violations
// Recursively traverse the left subtree
if not inorderTraversal(node.left):
return false
// Check if the current node's value violates the BST property
if node.value <= prevValue:
return false
// Update the previously visited node's value
prevValue = node.value
// Recursively traverse the right subtree
return inorderTraversal(node.right)
// Start the inorder traversal from the root
return inorderTraversal(root)
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)

View File

@@ -0,0 +1,726 @@
# Advanced DSA : Trees 4: LCA
---
## Understanding Binary Trees and Binary Search Trees
### Binary Trees
A Binary Tree is a hierarchical data structure composed of nodes, where each node has at most two children: a left child and a right child. The top node is called the root, and nodes without children are called leaves.
### Binary Search Trees (BSTs)
A Binary Search Tree is a type of binary tree with an additional property: for each node, all nodes in its left subtree have values smaller than the node's value, and all nodes in its right subtree have values greater than the node's value.
---
### Problem 1 Finding the kth Smallest Element in a Binary Search Tree
Given a Binary Search Tree and a positive integer k, the problem is to find the kth smallest element in the BST.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
### In-Order Traversal storing elements in array(Brute Force):
#### Algorithm
1. Initialize a binary search tree (BST) as root.
2. Iterate through the elements of the array and insert each element into the BST.
3. Perform an in-order traversal of the BST to collect the elements in sorted order.
4. Access the Kth element from the sorted elements list.
5. Return the Kth element as the Kth smallest element.
#### Pseudocode:
```java
// Define a TreeNode structure
Struct TreeNode:
val
left
right
// Function to find the Kth smallest element in a BST
Function findKthSmallestElement(arr, k):
If arr is empty:
Return None // Array is empty, no elements to find
Root = null // Initialize the root of the binary search tree
// Step 1: Create a binary search tree (BST) from the array
For each element in arr:
Root = insert(Root, element)
SortedElements = [] // Initialize an empty list to store sorted elements
// Step 2: Perform an in-order traversal of the BST
InorderTraversal(Root, SortedElements)
// Step 3: Return the Kth element from the sorted elements list
If 1 <= k <= length(SortedElements):
Return SortedElements[k - 1] // Subtract 1 because indices are 0-based
Else:
Return None // Handle the case when k is out of bounds
// Function to insert a value into a BST
Function insert(root, value):
If root is null:
Return TreeNode(value) // Create a new node with the given value
If value < root.val:
root.left = insert(root.left, value) // Insert into the left subtree
Else:
root.right = insert(root.right, value) // Insert into the right subtree
Return root
// Function to perform an in-order traversal of the BST
Function InorderTraversal(root, result):
If root is null:
Return
// Step 4: Perform an in-order traversal recursively
InorderTraversal(root.left, result)
Append root.val to result
InorderTraversal(root.right, result)
// Example usage:
Elements = [12, 3, 7, 15, 9, 20]
K = 3 // Find the 3rd smallest element
Result = findKthSmallestElement(Elements, K)
If Result is not null:
Output "The Kth smallest element is: " + Result
Else:
Output "Invalid value of K: " + K
```
#### In-Order Traversal Approach(Count Method):
The in-order traversal of a BST visits the nodes in ascending order. Therefore, by performing an in-order traversal and keeping track of the count of visited nodes, we can identify the kth smallest element when the count matches k.
#### Example: Finding the 3rd Smallest Element in a BST
**BST:**
```java
4
/ \
2 6
/ \ / \
1 3 5 7
```
**Scenario:**
We want to find the 3rd smallest element in the given BST.
**Solution:**
* Perform an in-order traversal of the BST:
* In-order traversal: 1, 2, 3, 4, 5, 6, 7
* The 3rd smallest element is 3.
#### Pseudocode:
Here's a simplified pseudocode representation of finding the kth smallest element using in-order traversal:
```java
function findKthSmallest(root, k):
count = 0
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
count += 1
if count == k:
return root.val
root = root.right
```
#### Analysis:
The in-order traversal visits every node once, making the time complexity of this algorithm $O(n)$, where n is the number of nodes in the BST. The space complexity is $O(h)$, where h is the height of the BST, due to the stack used for traversal.
---
### Problem 2 Morris Traversal
#### Morris Traversal Approach:
Morris Traversal takes advantage of unused null pointers in the tree structure to link nodes temporarily, effectively threading the tree. By doing so, it enables us to traverse the tree in a specific order without requiring a stack or recursion.
#### In-Order Morris Traversal:
* Start at the root.
* Initialize the current node as the root.
* While the current node is not null:
* If the current node's left child is null, print the current node's value and move to the right child.
* If the current node's left child is not null:
* Find the rightmost node in the left subtree.
* Make the current node the right child of the rightmost node.
* Move to the left child of the current node.
* Repeat the process until the current node becomes null.
#### Pre-Order Morris Traversal:
* Start at the root.
* Initialize the current node as the root.
* While the current node is not null:
* Print the current node's value.
* If the current node's left child is null, move to the right child.
* If the current node's left child is not null:
* Find the rightmost node in the left subtree.
* Make the current node the right child of the rightmost node.
* Move to the left child of the current node.
* Repeat the process until the current node becomes null.
**Example:**
```java
1
/ \
2 3
/ \
4 5
```
We will carefully go through each step:
- **Step 1: Start at the root node, which is 1.**
1. Initialize current pointer as current = 1.
- **Step 2: At node 1:**
1. Check if the left subtree of the current node is null.
2. Since the left subtree of 1 is not null, find the rightmost node in the left subtree. This is node 5.
3. Create a thread (temporary link) from 5 to the current node (1): 5 -> 1.
4. Update the current node to its left child: current = 2.
- **Step 3: At node 2:**
1. Check if the left subtree of the current node is null.
2. The left subtree of 2 is not null, so find the rightmost node in the left subtree of 2, which is 5.
3. Remove the thread from 5 to 1 (undoing the link created earlier).
4. Print the current node's value, which is 2.
5. Move to the right child of the current node: current = 3
- **Step 4: At node 3:**
1. Check if the left subtree of the current node is null.
2. The left subtree of 3 is null, so print the current node's value, which is 3.
3. Move to the right child of the current node (null): current = None.
- **Step 5:** Since the current node is now None, we've reached the end of the traversal.
1. The Morris Inorder Traversal of the binary tree 1 -> 2 -> 4 -> 5 -> 3 allows us to visit all the nodes in ascending order without using additional data structures or modifying the tree's structure. It's an efficient way to perform an inorder traversal.
#### Pseudocode Example (In-Order):
```java
function morrisInOrderTraversal(root):
current = root
while current is not null:
if current.left is null:
print current.value
current = current.right
else:
pre = current.left
while pre.right is not null and pre.right != current:
pre = pre.right
if pre.right is null:
pre.right = current
current = current.left
else:
pre.right = null
print current.value
current = current.right
```
#### Analysis:
Morris Traversal eliminates the need for an explicit stack, leading to a constant space complexity of $O(1)$. The time complexity for traversing the entire tree remains $O(n)$, where n is the number of nodes.
---
### Question
What is the primary advantage of Morris Traversal for binary trees?
**Choices**
- [ ] It uses an auxiliary stack to save memory.
- [ ] It guarantees the fastest traversal among all traversal methods.
- [ ] It allows for traversal in reverse order (right-to-left).
- [x] It achieves memory-efficient traversal without using additional data structures.
---
### Problem 3 Finding an element
#### Approach:
Finding an element in a binary tree involves traversing the tree in a systematic way to search for the desired value. We'll focus on a common approach known as depth-first search (DFS), which includes pre-order, in-order, and post-order traversal methods.
#### Algorithm:
1. Start at the root node of the binary tree.
2. If the root node is null (indicating an empty tree), return False (element not found).
3. Check if the value of the current node matches the target value:
4. If they are equal, return True (element found).
5. Recursively search for the target element in the left subtree by calling the function with the left child node.
6. Recursively search for the target element in the right subtree by calling the function with the right child node.
7. If the element is found in either the left or right subtree (or both), return True.
8. If the element is not found in either subtree, return False.
#### Example:
```java
1
/ \
2 3
/ \
4 5
```
**Dry Run:**
1. Start at the root (1).
2. Check if it matches the target (3) - No.
3. Move to the left child (2).
4. Check if it matches the target (3) - No.
5. Move to the left child (4).
6. Check if it matches the target (3) - No.
7. Move to the right child (null).
8. Move back to 4's parent (2).
9. Move to the right child (5).
10. Check if it matches the target (3) - No.
11. Move to the left child (null).
12. Move back to 5's parent (2).
13. Move back to 2's parent (1).
14. Check if it matches the target (3) - Yes, found!
15. Finish the search.
#### Pseudocode Example:
```java
function findElement(root, target)
if root is null
return False // Element not found in an empty tree
if root.value is equal to target
return True // Element found at the current node
// Recursively search in the left subtree
found_in_left = findElement(root.left, target)
// Recursively search in the right subtree
found_in_right = findElement(root.right, target)
// Return True if found in either left or right subtree
return found_in_left OR found_in_right
```
#### Analysis:
The time complexity of finding an element in a binary tree using DFS depends on the height of the tree. In the worst case, it's O(n), where n is the number of nodes in the tree. The space complexity is determined by the depth of the recursion stack.
---
### Problem 4 Path from root to node in Binary Tree
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach:
To find the path from the root to a specific node, we'll leverage depth-first search (DFS), a versatile traversal method that includes pre-order, in-order, and post-order traversal techniques.
#### DFS Pre-Order Traversal for Finding Path:
1. Initialize an empty list path to store the path.
2. Define a recursive function findPath(root, target, path):
3. If root is null, return False.
4. If root matches the target, append it to path and return True.
5. Recursively call findPath on the left subtree and right subtree.
6. If either subtree returns True, append root to path and return True.
7. Start the search from the root node by calling findPath(root, target, path).
8. If the search returns True, reverse the path list to get the path from root to target.
9. Return the reversed path.
#### Pseudocode Example (DFS Pre-Order):
```java
function findPath(root, target):
if root is null:
return false // Element not found in an empty tree
if root.value == target:
list.add(root) // Add the current node to the list (path found)
return true; // Element found
res = findPath(root -> left, target) OR findPath(root -> right, target)
if res == true:
list.add(root) // Add the current node to the list (part of the path)
return res;
// Reverse the list to get the answer (the path from root to target)
```
#### Analysis:
The time complexity of finding the path from the root to a node using DFS depends on the height of the tree. In the worst case, it's O(n), where n is the number of nodes in the tree. The space complexity is determined by the depth of the recursion stack and the length of the path.
---
### Question
What is the primary benefit of using depth-first search (DFS) for finding the path from the root to a specific node in a Binary Tree?
**Choices**
- [ ] DFS guarantees the shortest path between the root and the target node.
- [ ] DFS ensures that the tree remains balanced during traversal.
- [ ] DFS enables efficient path finding with a time complexity of O(log n).
- [x] DFS allows us to explore the structure of the tree while tracking visited nodes.
---
### Problem 5 finding the Lowest Common Ancestor (LCA) of two nodes
#### Approach:
To find the LCA of two nodes in a binary tree, we'll utilize a recursive approach that capitalizes on the tree's structure. The LCA is the deepest node that has one of the nodes in its left subtree and the other node in its right subtree.
#### Recursive Algorithm for LCA:
* Start at the root of the binary tree.
* If the root is null or matches either of the target nodes, return the root as the LCA.
* Recursively search for the target nodes in the left and right subtrees of the current root.
* If both target nodes are found in different subtrees, the current root is the LCA.
* If only one target node is found, return that node as the LCA.
* If both target nodes are found in the same subtree, continue the search in that subtree.
**Example**:
```java
1
/ \
2 3
/ \
4 5
/ \
6 7
```
**LCA of nodes 6 and 3 is node 1.**
1. Start at the root (1).
2. Check for nodes 6 and 3 in the subtree rooted at 1.
3. Recursively search the left subtree (2).
4. Continue searching left (4).
5. Continue searching left (6).
6. Found node 6, but not node 3 in the left subtree.
7. Go back to node 4 and check the right subtree (null).
8. Go back to node 2 and check the right subtree (5).
9. Continue searching right (5).
10. Not found node 6 in the right subtree.
11. Go back to node 2 and check for nodes 6 and 3.
12. Found node 6 in the left subtree.
13. Return node 2 as the Lowest Common Ancestor (LCA).
#### Pseudocode Example:
```java
function findLCA(root, node1, node2):
# Base case: if root is null or matches either of the nodes, return root
if root is null or root == node1 or root == node2:
return root
# Recursively search for the target nodes in the left and right subtrees
left_lca = findLCA(root.left, node1, node2)
right_lca = findLCA(root.right, node1, node2)
# Determine the LCA based on the search results
if left_lca and right_lca:
return root # Current root is the LCA
if left_lca:
return left_lca # LCA found in the left subtree
return right_lca # LCA found in the right subtree
```
#### Analysis:
The time complexity of finding the LCA in a binary tree using this recursive approach is O(n), where n is the number of nodes in the tree. The space complexity is determined by the depth of the recursion stack.
---
### Problem 6 Lowest Common Ancestor (LCA) in a Binary Search Tree (BST)
#### Approach:
To find the LCA of two nodes in a Binary Search Tree, we'll utilize the properties of BSTs that make traversal and comparison more efficient.
#### Algorithm for Finding LCA in a BST:
* Start at the root of the BST.
* Compare the values of the root node, node1, and node2.
* If both nodes are smaller than the root's value, move to the left subtree.
* If both nodes are larger than the root's value, move to the right subtree.
* If one node is smaller and the other is larger than the root's value, or if either node matches the root's value, the root is the LCA.
* Repeat steps 2-5 in the chosen subtree until the LCA is found.
#### Example: Finding LCA in a Binary Search Tree
**BST:**
```java
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
```
Let's find the LCA of nodes 4 and 7 in this BST:
- **Step 1:**
1. Start at the root, which is node 8.
2. Compare node 4 and node 7 with the current node's value (8).
3. Both are smaller, so move to the left subtree (node 3).
- **Step 2:**
1. Move to node 3.
2. Compare node 4 and node 7 with the current node's value (3).
3. Both are larger, so move to the right subtree (node 6).
- **Step 3:**
1. Move to node 6.
2. Compare node 4 and node 7 with the current node's value (6).
3. Node 4 is smaller, and node 7 is larger.
4. The current node (6) is the LCA of nodes 4 and 7.
5. So, in this example, the LCA of nodes 4 and 7 in the BST is node 6.
#### Pseudocode Example:
```java
function findLCA(root, node1, node2):
if root is null:
return null // If the tree is empty, there's no LCA
while root is not null:
// If both nodes are smaller than the current node, go left
if node1.value < root.value and node2.value < root.value:
root = root.left
// If both nodes are larger than the current node, go right
else if node1.value > root.value and node2.value > root.value:
root = root.right
// If one node is smaller and the other is larger, or if one matches, this is the LCA
else:
return root
return null // If no LCA is found (unlikely in a valid BST)
```
#### Analysis:
The time complexity of finding the LCA in a BST is O(h), where h is the height of the BST. In a balanced BST, the height is log(n), making the LCA operation highly efficient. The space complexity is determined by the depth of the recursion stack.
---
### Problem 7 In-time and Out-time of Binary Tree
#### Approach:
The Interval Assignment technique involves three main steps: DFS traversal, interval assignment, and construction of the rooted tree.
:::warning
Please take some time to think about the further solution approach on your own before reading further.....
:::
#### DFS Traversal and Interval Assignment:
* Start a DFS traversal of the tree from any chosen starting node.
* As nodes are visited, assign start times when a node is entered and finish times when the traversal returns from that node. These times define intervals for each node.
#### Constructing the Rooted Tree:
1. From the DFS traversal, we have a collection of intervals (start and finish times) for each node.
2. Choose the node with the smallest start time as the root of the rooted tree.
3. For each remaining node:
1. Find the node with the largest start time that is still smaller than the current node's finish time. This node becomes the parent of the current node in the rooted tree.
2. Repeat this process for all nodes.
---
### Question
What is the significance of in-time and out-time values in DFS traversal?
**Choices**
- [ ] They indicate the number of times each node is visited during the traversal.
- [ ] They represent the depth of each node in the tree.
- [x] They help create hierarchical visualizations of trees.
- [ ] They are used to determine the balance of the tree.
**Example:**
```java
1
/ \
2 3
/ \
4 5
```
1. We initialize the global time variable to 1.
2. We traverse the tree using Depth-First Search (DFS):
3. Starting at Node 1:
4. In-Time for Node 1 is recorded as 1.
5. We recursively visit the left child, Node 2.
6. At Node 2:
7. In-Time for Node 2 is recorded as 2.
8. We recursively visit the left child, Node 4.
9. At Node 4:
10. In-Time for Node 4 is recorded as 3.
11. Since Node 4 has no further children, we record its Out-Time as 5.
12. Now, we return to Node 2:
13. We recursively visit the right child, Node 5.
14. At Node 5:
15. In-Time for Node 5 is recorded as 8.
16. Since Node 5 has no further children, we record its Out-Time as 10
17. We return to Node 2 and record its Out-Time as 11.
18. We return to Node 1 and recursively visit its right child, Node 3.
19. At Node 3:
20. In-Time for Node 3 is recorded as 12.
21. We recursively visit its right child, but it's null.
22. We record the Out-Time for Node 3 as 14.
23. Finally, we return to Node 1 and record its Out-Time as 15.
**The in-time and out-time values are now calculated:**
* Node 1 - In-Time: 1, Out-Time: 15
* Node 2 - In-Time: 2, Out-Time: 11
* Node 3 - In-Time: 12, Out-Time: 14
* Node 4 - In-Time: 3, Out-Time: 5
* Node 5 - In-Time: 8, Out-Time: 10
#### Pseudocode
```java
function calculateInTimeOutTime(root):
global time // A global variable to keep track of time
// Initialize arrays to store in-time and out-time for each node
inTime = [0] * (2 * n) // Assuming 'n' is the number of nodes in the tree
outTime = [0] * (2 * n)
// Helper function for DFS traversal
function dfs(node):
nonlocal time
// Record the in-time for the current node and increment time
inTime[node] = time
time = time + 1
// Recursively visit left child (if exists)
if node.left is not null:
dfs(node.left)
// Recursively visit right child (if exists)
if node.right is not null:
dfs(node.right)
// Record the out-time for the current node and increment time
outTime[node] = time
time = time + 1
// Start DFS traversal from the root
dfs(root)
```
---
### Problem 8 For multiple queries find LCA(x,y)
#### Algorithm:
1. Calculate In-Time and Out-Time for Each Node:
2. First, calculate the in-time and out-time for each node in the binary tree as explained in a previous response.
3. Answer LCA Queries:
4. To find the LCA of multiple pairs of nodes (x, y):
5. For each LCA query (x, y):
6. Check if inTime[x] is less than or equal to inTime[y] and outTime[x] is greater than or equal to outTime[y]. If true, it means that node x is an ancestor of node y.
7. Check if inTime[y] is less than or equal to inTime[x] and outTime[y] is greater than or equal to outTime[x]. If true, it means that node y is an ancestor of node x.
8. If neither of the above conditions is met, it means that x and y have different ancestors.
9. In such cases, move up the tree from the deeper node until you find a node that is at the same level as the shallower node. This node will be their LCA.
#### Example
```java
1
/ \
2 3
/ \
4 5
```
And we'll find the Lowest Common Ancestor (LCA) for a few pairs of nodes (x, y) using the in-time and out-time approach.
* **Step 1: Calculate In-Time and Out-Time** <br>We've already calculated the in-time and out-time values for this tree as follows:
1. Node 1 - In-Time: 1, Out-Time: 10
2. Node 2 - In-Time: 2, Out-Time: 7
3. Node 3 - In-Time: 8, Out-Time: 9
4. Node 4 - In-Time: 3, Out-Time: 4
5. Node 5 - In-Time: 5, Out-Time: 6
* **Step 2: Find LCA for Pairs**
* Find LCA(4, 5):
* Check in-time and out-time:
* In-Time(4) <= In-Time(5) and Out-Time(4) >= Out-Time(5) is true.
* So, LCA(4, 5) is 4.
* Find LCA(2, 3):
* Check in-time and out-time:
* In-Time(2) <= In-Time(3) and Out-Time(2) >= Out-Time(3) is false.
* Now, bring both nodes to the same depth:
* Move 2 up once: 2 is now at the same depth as 3.
* Continue moving both nodes up:
* LCA(2, 3) is 1.
* Find LCA(4, 3):
* Check in-time and out-time:
* In-Time(4) <= In-Time(3) and Out-Time(4) >= Out-Time(3) is false.
* Now, bring both nodes to the same depth:
* Move 4 up once: 4 is now at the same depth as 3.
* Continue moving both nodes up:
* LCA(4, 3) is 1.
* Find LCA(5, 2):
* Check in-time and out-time:
* In-Time(5) <= In-Time(2) and Out-Time(5) >= Out-Time(2) is false.
* Now, bring both nodes to the same depth:
* Move 5 up once: 5 is now at the same depth as 2.
* Continue moving both nodes up:
* LCA(5, 2) is 1.
#### Pseudocode:
```java
function findLCA(x, y):
if inTime[x] <= inTime[y] and outTime[x] >= outTime[y]:
return x # x is an ancestor of y
if inTime[y] <= inTime[x] and outTime[y] >= outTime[x]:
return y # y is an ancestor of x
# Move x and y up the tree to the same depth
while depth[x] > depth[y]:
x = parent[x]
while depth[y] > depth[x]:
y = parent[y]
# Move x and y up simultaneously until they meet at the LCA
while x != y:
x = parent[x]
y = parent[y]
return x # LCA found
```
---
### Question
What is the primary purpose of constructing a rooted tree using the start and finish times obtained during the DFS traversal?
**Choices**
- [ ] To optimize the tree structure for faster traversal.
- [ ] To visualize the tree with nodes arranged in increasing order.
- [x] To efficiently represent the hierarchy and relationships within the tree.
- [ ] To eliminate the need for recursion in tree traversal.
---
### Observations
* **In-Order Traversal:**<br> It visits Binary Search Tree (BST) nodes in ascending order, enabling efficient kth smallest element retrieval.
* **Morris Traversal:**<br> An efficient memory-saving tree traversal method with O(1) space complexity.
* **Path from Root:**<br> DFS traversal is used to find the path from the root to a node, with space complexity tied to recursion depth.
* **Lowest Common Ancestor (LCA) in Tree:**<br> LCA is found through recursion with O(n) time complexity and stack space.
* **In-Time & Out-Time:**<br> These values in DFS help create hierarchical visualizations of trees.
* **Interval Assignment Visualization:**<br> Provides a visual hierarchy for analyzing complex structures in various fields.
* **Finding LCA for Multiple Queries:**<br> LCA retrieval for multiple pairs involves adjusting node depths until they meet.

View File

@@ -0,0 +1,587 @@
# Advanced DSA : Trees 5: Problems on Trees
---
## Problem 1 Invert Binary Tree
Given the root node of a binary tree, write a function to invert the tree.
**Example**
Original Binary Tree :
```plaintext
1
/ \
2 3
/ \
4 5
```
After Inverting the Binary Tree :
```plaintext
1
/ \
3 2
/ \
5 4
```
---
### Question
Select the correct inverted binary tree for this given tree:
```
4
/ \
2 7
/ \ \
1 3 9
```
**Choices**
- [ ] **Option 1:**
```
4
/ \
7 2
/ \ /
9 3 1
```
- [ ] **Option 2:**
```
4
/ \
7 2
\ / \
3 1 9
```
- [ ] **Option 3:**
```
4
/ \
2 7
\ / \
1 9 3
```
- [x] **Option 4:**
```
4
/ \
7 2
/ \ /
9 1 3
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Solution**
To solve this problem,we can recursively invert the binary tree by swapping the left and right subtrees for each node.
```cpp
void invertTree(TreeNode * root) {
if (root == nullptr) {
return; // Return if the root is null
}
// Use a temporary variable to swap left and right subtrees
TreeNode * temp = root -> left;
root -> left = root -> right;
root -> right = temp;
// Recursively invert the left and right subtrees
invertTree(root -> left);
invertTree(root -> right);
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(H)
---
### Problem 2 Equal Tree Partition
Given the root of a binary tree, return ***true*** if the tree can be split into two non-empty subtrees with equal sums, or ***false*** otherwise.
**Example 1**
```cpp
Input:
5
/ \
10 10
/ \
2 3
Output: True
```
**Explanation:**
```cpp
5
/
10
Sum: 15
```
```cpp
10
/ \
2 3
Sum: 15
```
**Example 2**
```cpp
Input:
1
/ \
2 10
/ \
2 15
Output: false
```
**Explanation:**
There is no way to split the tree into two subtrees with equal sums.
---
### Question
Check whether the given tree can be split into two non-empty subtrees with equal sums or not.
```cpp
5
/ \
10 10
/ \
20 3
/
8
```
**Choices**
- [x] Yes, It is possible.
- [ ] It is impossible.
**Explanation:**
Yes It is possible to split the tree into two non-empty subtrees with sum 28.
Sub-Tree 1:
```cpp
5
/ \
10 10
\
3
```
Sub-Tree 2:
```cpp
20
/
8
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Solution**
1. **Total Sum Check**:
If the total sum of all nodes in the binary tree is odd, it is impossible to divide the tree into two subtrees with equal sums. This is because the sum of two equal values is always even, and if the total sum is odd, it cannot be divided equally into two parts.
2. **Subtree Sum Check**:
If we can find a subtree in the binary tree with a sum equal to half of the total sum, we can split the tree into two equal partitions by removing the edge leading to the root of that subtree. This means that we don't necessarily need to compare sums of all possible subtrees, but we can look for a single subtree that meets the subtree sum check condition.
#### Pseudocode
```cpp
int sum(TreeNode * root) {
if (!root) {
return 0;
}
return sum(root -> left) + sum(root -> right) + root -> val;
}
bool hasSubtreeWithHalfSum(TreeNode * root, int totalSum) {
if (!root) {
return false;
}
int leftSum = sum(root -> left);
int rightSum = sum(root -> right);
if ((leftSum == totalSum / 2 || rightSum == totalSum / 2) || hasSubtreeWithHalfSum(root -> left, totalSum) || hasSubtreeWithHalfSum(root -> right, totalSum)) {
return true;
}
return false;
}
bool isEqualTreePartition(TreeNode * root) {
if (!root) {
return false; // An empty tree cannot be partitioned
}
int totalSum = sum(root);
if (totalSum % 2 == 1) {
return false; // If the total sum is odd, partition is not possible
}
return hasSubtreeWithHalfSum(root, totalSum);
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(H)
---
### Problem 3 Next Pointer in Binary Tree
Given a perfect binary tree initially with all next pointers set to nullptr, modify the tree in-place to connect each node's next pointer to the next node in the same level from left to right, following an in-order traversal.
**Example**
```cpp
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output :
1 -> nullptr
/ \
2 -> 3 -> nullptr
/ \ / \
4 -> 5 -> 6 -> 7 -> nullptr
```
:::warning
Please take some time to think about the bruteforce approach on your own before reading further.....
:::
#### Brute force solution
**Level order Traversal** :
1. We check if the binary tree is empty; if so, we return the root since there's nothing to connect.
2. A queue is created for level order traversal, initialized with the root node.
3. In the main loop, we process nodes at the current level.
4. At the start of each level, we determine the number of nodes at the current level (levelSize).
5. In the inner loop, we process each node at the current level:
* We dequeue the current node from the front of the queue.
* If the current node is not the last node in the level (i.e., i < levelSize - 1), we update its next pointer to point to the front of the queue, which connects nodes from left to right within the same level.
* We enqueue the left and right children of the current node (if they exist) into the queue for the next level.
6. The loop continues until all levels are processed.
7. Finally, the function returns the modified root of the binary tree, which now has next pointers connecting nodes at the same level, except for the last node in each level, whose next pointer remains nullptr.
#### Pseudocode :
```cpp
Node * connect(Node * root) {
// Check if the tree is empty
if (root is null) {
return null;
}
// Create a queue and enqueue the root
queue < Node * > q;
q.push(root);
// Traverse the tree level by level
while (!q.empty()) {
int levelSize = q.size();
// Process nodes at the current level
for (int i = 0; i < levelSize; ++i) {
Node * node = q.front();
q.pop();
// Connect the current node to the next node in the same level
if (i < levelSize - 1) {
node -> next = q.front();
}
// Enqueue the left and right children (if they exist) for the next level
if (node has a left child) {
q.push(node 's left child);
}
if (node has a right child) {
q.push(node 's right child);
}
}
}
// Return the modified root
return root;
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(N)
#### Optimized Solution:
1. We create a dummy node and a temp pointer initially pointing to it.
2. We traverse the tree level by level from left to right.
3. For each node:
* If it has a left child, we connect the temp node's next pointer to the left child and update temp.
* If it has a right child, we connect the temp node's next pointer to the right child and update temp.
4. Level Completion:
5. When the current level is done, we move to the next level by updating root to the dummy node's next. We reset dummy's next and reset temp to the dummy node.
6. We repeat these steps until all levels are traversed.
7. The loop ends when there are no more levels to traverse.
#### Pseudocode
```cpp
void populateNextPointers(Node * root) {
if (!root) {
return;
}
Node * dummy = new Node(-1);
Node * temp = dummy;
while (root != nullptr) {
if (root -> left != nullptr) {
temp -> next = root -> left;
temp = temp -> next;
}
if (root -> right != nullptr) {
temp -> next = root -> right;
temp = temp -> next;
}
root = root -> next;
if (root == nullptr) {
root = dummy -> next;
dummy -> next = nullptr;
temp = dummy;
}
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(1)
---
### Problem 4 Check if Root to Leaf Path Sum Equals to K
Given a binary tree and an integer k, determine if there exists a root-to-leaf path in the tree such that adding up all the node values along the path equals k.
Example:
```cpp
Input:
Binary Tree:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
k = 22
Output: true
```
**Explanation**:
In the given binary tree, there exists a root-to-leaf path 5 -> 4 -> 11 -> 2 with a sum of 5 + 4 + 11 + 2 = 22, which equals k. Therefore, the function should return true.
---
### Question
Tell if there exists a root to leaf path with sum value `k = 19`
```cpp
5
/ \
3 7
/ \
10 2
/ \ \
19 1 5
k = 20
```
**Choices**
- [x] true
- [ ] false
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Solution:**
* To solve this problem,we first check if the current node is a leaf node (having no left and right children) and if the current value equals k. If both conditions are met, it returns true, indicating that a valid path is found.
* If not, it recursively checks the left and right subtrees with a reduced sum (k - root->val).
* It returns true if there's a path in either the left or right subtree, indicating that a valid path is found.
#### Pseudocode
```cpp
bool hasPathSum(TreeNode * root, int k) {
if (!root) {
return false; // No path if the tree is empty
}
if (!root -> left && !root -> right) {
return (k == root -> val);
}
return hasPathSum(root -> left, k - root -> val) || hasPathSum(root -> right, k - root -> val);
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(H)
---
### Problem 5 Diameter of Binary Tree
Given a binary tree, find the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.
**Definition of Diameter**: The diameter of a binary tree is defined as the number of nodes along the longest path between any two leaf nodes in the tree. This path may or may not pass through the root.
---
### Question
How would you find the diameter of a binary tree?
**Choices**
- [ ] Add the height of the left and right subtrees.
- [ ] Count the number of nodes in the tree.
- [x] The maximum of the following three: Diameter of the left subtree, Diameter of the right subtree, Sum of the heights of the left and right subtrees plus one
- [ ] Divide the height of the tree by 2.
**Example**:
Example that illustrates that the diameter of the tree can pass through a root node.
```cpp
Input:
1
/ \
2 3
/ \
4 5
Output: 4
```
**Explanation**:
The diameter of the binary tree shown above is the path 4 -> 2 -> 1 -> 3, which contains four nodes.
**Example:**
Example that illustrates that the diameter of the tree can pass through a non-root node:
```cpp
Input:
1
/
2
/ \
4 5
/ \ \
6 7 3
Output: 5
```
**Explanation:**
The diameter of the binary tree shown above is the path 6 - 4 - 2 - 5 - 3, which includes 5 nodes.
---
### Question
What is the diameter of the Given Binary Tree.
```cpp
1
/
2
/ \
4 5
/ \
6 7
\
8
\
10
```
**Choices**
- [x] 6
- [ ] 5
- [ ] 7
- [ ] 4
**Explanation:**
The path 1 -> 2 -> 4 -> 7 -> 8 -> 10 has 6 nodes, which is the diameter of the given tree.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Solution:**
1. To solve this problem,we initialize a diameter variable to 0 to track the maximum diameter.
2. Define a helper function that recursively computes both the height of the tree and the diameter
3. In the helper function:
* If the node is null, we return -1 to signify no height.
* We recursively find left and right subtree heights.
* We update diameter with the maximum diameter found, including the current node and connecting path (2 units).
* The height of the current node is the max of left and right subtree heights, plus 1.
* Call the helper function with the root of the binary tree from the main function or method.
4. Retrieve and use the maximum diameter found during traversal as the result.
#### Pseudocode:
```cpp
int diameterOfBinaryTree(TreeNode * root) {
int diameter = 0;
// Helper function to calculate height and update diameter
std:: function < int(TreeNode * ) > calculateHeight = [ & ](TreeNode * node) {
if (!node) {
return -1; // Height of a null node is -1
}
int leftHeight = calculateHeight(node -> left);
int rightHeight = calculateHeight(node -> right);
// Update diameter with the current node's diameter
diameter = std::max(diameter, leftHeight + rightHeight + 2);
// Return the height of the current node
return std::max(leftHeight, rightHeight) + 1;
};
calculateHeight(root); // Start the recursive calculation
return diameter;
}
```
#### Complexity
**Time Complexity:** O(N)
**Space Complexity:** O(H)

View File

@@ -0,0 +1,645 @@
# Two Pointers
---
## Problem 1 Pairs with given sum 2
*Given an integer sorted array `A` and an integer `k`, find any pair (i, j) such that `A[i] + A[j] = k`, `i != j`.*
**Example**:
A = [-5, -2, 1, 8, 10, 12, 15]
k = 11
Ans: (2, 4) as A[2] + A[4] = 1 + 10 = 11 = k
---
### Question
Check if there exists a pair with sum k
`A [ ] = { -3, 0, 1, 3, 6, 8, 11, 14, 18, 25 }`
`k = 12`
**Choices**
- [x] Yes
- [ ] No
**Explanation:**
Yes. Because there are 2 pairs with sum as 11, They are
- (1, 11)
- (3, 8)
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Pairs with given sum 2 Approaches
#### Brute Force Apporach:
*Run two for loops and for every indices: i, j, check if sum is k.*
- **Time Complexity:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/949/original/Screenshot_2023-10-03_014739.png?1696277868" width=50/>, as we need to use two for loops.
- **Space Complexity:**
O(1), as no additional space is required.
#### Binary Search Apporach
**Observation**:
- We need to find two elements whose sum is `k`, i.e., `A[i] + A[j] == k`.
- So, `A[j] = k - A[i]`. Essentially, for an element, `A[i]`, we need to find an element `k - A[i]`.
- Since, array `A` is sorted, we can use binary search to find the element `k - A[i]`. (make sure, we are not choosing the same index again)
**Approach**: *For all `i`, binary search and find `k - A[i]`.*
- **Time Complexity:**
O(N * log(N)), as we need to apply binary search for every element in the worst case.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Pairs with given sum 2 Two Pointers Approach
Let's keep two pointers, `i` and `j` and we put them at 0 and 1st idx.
We have, A = {-5, -2, 1, 8, 10, 12, 15} and k = 11
If A[0] = A[i] = -5 and A[1] = A[j] = -2
A[i] + A[j] = -5 + (-2) = -7
So, **A[i] + A[j] < k**
To achieve the sum as `k`, we have to either increase i or j as the array is sorted.
Now, if A[5] = A[i] = 12 and A[6] = A[j] = 15
A[i] + A[j] = 12 + 15 = 27
So, **A[i] + A[j] > k**
In this case, to achieve `k`, we have to either decrease i or j. *Why?*
> Essentially, we want to decrease the sum. The sum can be decreased by decreasing A[i] or A[j]. Since array is sorted, decrease the pointers will decrease the value as well.
*Where should we place the pointers initially?*
Initially, the pointers should be place at the beginning and end of the array as this way, we will have only one pointer in option to move in order to increase / decrease the sum.
**Step 1:**
So, if we take A[i] = A[0] and A[j] = A[6] then,
A[i] + A[j] = A[0] + A[6] = -5 + 15 = 10 < k. So, we need to increase the sum. Which pointer should we move?
Observations:
- This implies `-5 + largest element` is less than `k`. Therefore, `-5 + any element of A` will always be less than `k`. So, we do not need to check `-5` with any other number as the array is sorted.
- Hence, we should increase the `i` pointer to increase the sum.
> **Note:** Our motive here is to eliminate the elements one by one till we reach towards the elements who can build the required sum. Since, `-5 + largset element < k`, we can safely eliminate `-5`.
**Step 2:**
Now, taking A[i] = A[1] = -2 and A[j] = A[6] = 15
A[i] + A[j] = -2 + 15 = 13
Here, **A[i] + A[j] > k**
Following the same approach, we should decrease the index of j to decrease the sum. As decreasing the `i` would take us to the Step 1.
**Step 3:**
Now, taking A[i] = A[1] = -2 and A[j] = A[5] = 12
A[i] + A[j] = -2 + 12 = 10
Here **A[i] + A[j] < k**
Following the same approach, we should increase the index of i to increase the sum.
**Step 4:**
Similary, taking A[i] = A[2] = 1 and A[j] = A[5] = 10
A[i] + A[j] = 1 + 10
Here, **A[i] + A[j] = k**.
#### Pseudocode:
```java
while (i < j) {
if (A[i] + A[j] == k) {
return (i, j);
} else if (A[i] + A[j] < k) {
i++;
} else {
j--;
}
}
```
- **Time Complexity:**
O(N), as we need to traverse the complete array once in the worst case.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Problem 2 Count Pair Sum K
Find all the pairs in a sorted array whose sum is k.
**Example:**
A = {1, 2, 3, 4, 5, 6, 8}
k = 10
**Ans:** (2, 8), (4, 6)
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Two Pointer Approach:
**`Case 1: When elements are distinct`**
- Use two pointer approach to find the first pair whose sum is 10.
- For array `A`, it will be (2, 8).
- As the elements are distinct, neither 2 nor 8 can make pair with any other pair whose sum is 10. So, increase the pointer `i` and decrease the pointer `j` and continue finding the pair whose sum is 10.
- The next pair with this approach would be (4, 6). Similary, move the pointers in required direction to find another pairs.
- Since, there aren't any more pairs. The final result would be: (2, 8) and (4, 6).
**`Pseudocode:`**
```java
count = 0;
while (i < j) {
if (A[i] + A[j] == k) {
count++;
i++, j--;
} else if (A[i] + A[j] < k) {
i++;
} else {
j--;
}
}
return count;
```
**`Case 2: When elements are repeating (duplicates)`**
- **Using Frequency Array:**
- Consider the array, ( A = {2, 3, 3, 10, 10, 10, 15} ) with a target sum ( k = 13 ).
- Let's create the frequency map for the above. It would be - map ={[2 => 1], [3 => 2], [10 => 3], [15 => 1]}
- Now, create an array (A' = {2, 3, 10, 15}) by taking only the unique elements from array (A).
- Find the pair that contributes to the sum (13) in array (A'). The pair in this case would be (3, 10).
- The frequency of (3) is (2) and the frequency of (10) is (3) in the original array. So, the total number of such pairs in the original array would be ( 2 * 3 = 6).
- The key idea here is to transform the array with duplicate elements into an array of unique elements, find all the unique pairs that sum up to the target sum, and then use the frequencies of the elements in the original array to determine the count of all such pairs.
- **Without using frequency array:**
- Consider array, A = {2, 3, 3, 5, 5, 7, 7, 10, 10, 10, 15} and k = 13
- Find the pair whose sum is equal to k. In this case, (3, 10).
- Now, count the number of 3s and 10s and multiply them to find the effective number of pairs, i.e., 2 * 3 = 6.
- Change the position of i and j to next of last occurred 3 and 10, and continue the process.
- Final result would be 6.
**`Pseudocode:`**
```javascript
count = 0;
while (i < j) {
if (A[i] + A[j] == k) {
counti = 1, countj = 1;
while (i < j && A[i] == A[i + 1]) {
counti++;
i++;
}
while (i < j && A[j] == A[j - 1]) {
countj++;
j--;
}
count = counti * countj;
i++, j--;
} else if (A[i] + A[j] < k) {
i++;
} else {
j--;
}
}
print(count)
```
---
### Problem 3 Pair Difference K
Given a sorted integer array A and an integer k. Find any pair (i, j) such that A[j] - A[i] = k, i != j and k > 0.
Note: 0-based indexing
**Example:**
A[] =
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|-------|---|---|---|---|---|---|---|
| Value | -5 | -2 | 1 | 8 | 10 | 12 | 15 |
k = 11
Ans: (2, 5) as A[5] - A[2] = 12 - 1 = 11 = k.
#### Brute Force Apporach:
*Run two for loops and for every indices: i, j, check if difference is k.*
- **Time Complexity:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/949/original/Screenshot_2023-10-03_014739.png?1696277868" width=50 />, as we need to use two for loops.
- **Space Complexity:**
O(1), as no additional space is required.
#### Binary Search Apporach
*For all `i`, binary search and find `k + A[i]`.*
- **Time Complexity:**
O(N * log(N)), as we need to apply binary search for every element in the worst case.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Question
Given an array A is **[5, 4, 2, 12, 1, 6]** and K is 10.
Find any pair `(i, j)` such that
* A[j] - A[i] = k
* i != j
Note: 0-based indexing
**Choices**
- [x] (2, 3)
- [ ] (5, 5)
- [ ] (0, 0)
- [ ] (3, 2)
**Explanation:**
The answer is (2, 3).
Since (2, 3) satisfies both the condition:
* A[3] - A[2] = 10
* 3 != 2
---
### Pair Difference K Two Pointers Apporach
We have, A[] =
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|-------|---|---|---|---|---|---|---|
| Value | -5 | -2 | 1 | 8 | 10 | 12 | 15 |
and k = 11
*Where should we keep the pointers?*
**Option 1:**
Let's start with keeping the pointers, `i` and `j` at the beginning and end of the array respectively, i.e., `i` = 0 and `j` = `N - 1` = 6.
Observations:
- A[j] - A[i] = 15 - (-5) = 20 > k(11). So, to decrease the difference we need to either decrease A[j] or increase A[i].
- We know that, either we can increase pointer `i` or decrease pointer `j`. Increasing pointer `i` will increase the `A[i]` and similarly, decreasing pointer `j` will decrease the `A[j]`.
- Since we do not have a single direction to move, we cannot eliminate any element. Therefore, placing the pointers at the beginning and the end isn't helpful.
**Option 2:**
Let's now place the pointers at (N - 2) and (N - 1) indices, i.e., i = N - 2 = 5 and j = N - 1 = 6.
Observations:
- A[i] = A[5] = 12 and A[j] = A[6] = 15. A[j] - A[i] = A[6] - A[5] = 15 - 12 = 3. Therefore, **A[j] - A[i] < k**
- Here, we either need to increase A[j] or decrease A[i]. To increase A[j], j should be increased but it isn't possible as j is already pointing to the last element. So, we can decrease i.
- Doing so will eliminate the 12 to be possible second value of the pair. This is true because from here, we can conclude that the `largest element - A[i] < k`. So, `any element - A[i] < k` because the array is sorted.
- Thus, N - 2 and N - 1 are the correct possible initial values of pointers.
Similary result can be obtained by starting with index 0 and 1.
So, let's place the pointers at 0 and 1 indices, i.e., i = 0 and j = 1.
**Step 1: i = 0, j = 1**
- A[i] = A[0] = -5 and A[j] = A[1] = -2. A[j] - A[i] = A[1] - A[0] = -2 - (-5) = 3. Therefore, **A[j] - A[i] < k**
- Here, we either need to increase A[j] or decrease A[i]. To decrease A[i], i should be decreased but it isn't possible as i is already pointing to the first element. So, we can increase j.
**Step 2: i = 0, j = 2**
- A[i] = A[0] = -5 and A[j] = A[2] = 1. A[j] - A[i] = A[2] - A[0] = 1 - (-5) = 6. Therefore, **A[j] - A[i] < k**
- Similarly, increasing j.
**Step 3: i = 0, j = 3**
- A[i] = A[0] = -5 and A[j] = A[3] = 8. A[j] - A[i] = A[3] - A[0] = 8 - (-5) = 13. Therefore, **A[j] - A[i] > k**.
- Since difference is greater than k, we need to decrease A[j] or increase A[i]. Hence, increasing i to increase A[i].
**Step 4: i = 1, j = 3**
- A[i] = A[1] = -2 and A[j] = A[3] = 8. A[j] - A[i] = A[3] - A[0] = 8 - (-2) = 10. Therefore, **A[j] - A[i] < k**.
- Since difference is less than k, we need to increase A[j] or decrease A[i]. Hence, increasing j to increase A[j].
**Step 5: i = 1, j = 4**
- A[i] = A[1] = -2 and A[j] = A[4] = 10. A[j] - A[i] = A[4] - A[0] = 10 - (-2) = 12. Therefore, **A[j] - A[i] > k**.
- Since difference is greater than k, we need to decrease A[j] or increase A[i]. Hence, increasing i to increase A[i].
**Step 6: i = 2, j = 4**
- A[i] = A[2] = 1 and A[j] = A[4] = 10. A[j] - A[i] = A[4] - A[0] = 10 - 1 = 9. Therefore, **A[j] - A[i] < k**.
- Since difference is less than k, we need to increase A[j] or decrease A[i]. Hence, increasing j to increase A[j].
**Step 7: i = 2, j = 5**
- A[i] = A[2] = 1 and A[j] = A[5] = 12. A[j] - A[i] = A[5] - A[0] = 12 - 1 = 11. Finally, **A[j] - A[i] = k**.
- Required pair: (i, j) = (2, 5).
#### Pseudocode:
```java
i = 0, j = 1
while (j < n) {
diff = A[j] - A[i];
if (diff == k) {
return (i, j);
} else if (diff < k) {
j++;
} else {
i--;
}
}
```
*Why the `while` loop condition should be `j < n` and not `i < n`?*
It is based on assumption that `i` will always be <= `j`.
Proof:
Suppose we start with `i = 0`, `j = 1` and after some steps `j` reaches `x`.
To `i` cross `j`, `i` should first reach `j`. When `i` reaches `j`, then `diff = 0`. It is given that `k > 0`, so in order to achieve this, `j` should be increased, and hence `i` can never exceed `j`.
- **Time Complexity:**
O(N), as we need to traverse the complete array once in the worst case.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Problem 4 Check subarray with sum k
Given an integer array `A` and an integer `k`. Check if there exists a subarray with sum `k`
**Example:**
A = {1, 3, 15, 10, 20, 3, 23}; k = 33
**Ans:** True, because {10, 20, 3} sums upto 33.
A = {1, 3, 15, 10, 20, 3, 23}; k = 43
**Ans:** False, because no subarray exists that sums upto 43
> Number of subarrays in an array of length n is `n * (n + 1) / 2`.
#### Brute Force Apporach:
*Check every subarray sum (with carry forward approach)*
- **Time Complexity:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/949/original/Screenshot_2023-10-03_014739.png?1696277868" width=50 />, as we need to use two for loops.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Question
If the given array is [1, 2, 5, 4, 3] and k is 9, does there exist a subarray with sum k?
**Choices**
- [ ] Not Exist
- [x] Exist
**Explanation:**
Exist. The subarray is [5, 4].
---
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
### Check subarray with sum k Two Pointers Approach
Given A = {1, 3, 15, 10, 20, 3, 23}, k = 33. Let's create prefix sum array for this: Pf = {1, 4, 19, 29, 49, 52, 75}.
> `sum(i, j)` =
> `Pf[j] - Pf[i - 1]`, if `i > 0`
> `Pf[j]`, if `i = 0`
- To find the subarray with sum `k`, we can utilize the prefix sum array.
- For all `j`, if we check `Pf[j]`, essentially, we have checked all the subarrays starting from 0. On the same line, if we check for `Pf[j] - Pf[i - 1]`, we checked for every other subarray which doesn't starts with 0 in the array.
- Hence, we need to find the values of `i` and `j` for which `Pf[j] - Pf[i - 1] = k`. This is equivalent to *finding a pair in a sorted array whose difference is `k`*.
> Prefix sum array is always sorted for positive integer array as the sum of every next subarray is increasing.
- **Time Complexity:** O(N)
- Creating prefix sum array takes O(N) time.
- Using two pointers approach to find the pair having diff as `k` also takes O(N).
- **Space Complexity:**
O(1), as no additional space is required if we use same array to create prefix sum array.
#### Dynamic Sliding Window Approach:
*We can maintain a running sum based on the pointers position and check if it is equal to `k`.*
Example:
A = {1, 3, 15, 10, 20, 3, 23, 33, 43}, k = 33
**Step 1:** i = 0, j = 0
- `sum(i, j) = sum(0, 0) = A[0] = 1 < k`. To increase the sum, we need to increase the length of subarray, so `j++`.
**Step 2:** i = 0, j = 1
- `sum(i, j) = sum(0, 1) = A[0] + A[1] = 1 + 3 = 4 < k`. To increase the sum, we need to increase the length of subarray, so `j++`.
**Step 3:** i = 0, j = 2
- `sum(i, j) = sum(0, 2) = A[0] + A[1] + A[2] = 1 + 3 + 15 = 19 < k`. To increase the sum, we need to increase the length of subarray, so `j++`.
**Step 4:** i = 0, j = 3
- `sum(i, j) = sum(0, 3) = A[0] + A[1] + A[2] + A[3] = 1 + 3 + 15 + 10 = 29 < k`. To increase the sum, we need to increase the length of subarray, so `j++`.
**Step 5:** i = 0, j = 4
- `sum(i, j) = sum(0, 4) = A[0] + A[1] + A[2] + A[3] + A[4] = 1 + 3 + 15 + 10 + 20 = 49 > k`. To decrease the sum, we need to decrease the length of subarray. This can either be done by `i++` or `j--`. If we do `j--`, we will be at the same stage at step 4, which isn't helpful. So, we need to do `i++` to decrease the length and effectively the sum.
**Step 6:** i = 1, j = 4
- `sum(i, j) = sum(1, 4) = A[1] + A[2] + A[3] + A[4] = 3 + 15 + 10 + 20 = 48 > k`. Again, we need to decrease the length to decrease the sum.
*What shall we do here: `i++` or `j--`?*
We know that, sum (0, 3) < k. Therefore, sum(1, 3) will definitely be less than k. Therefore, `i++` is correct way out here.
**Step 7:** i = 2, j = 4
- `sum(i, j) = sum(2, 4) = A[2] + A[3] + A[4] = 15 + 10 + 20 = 45 > k`. Again, we need to decrease the length to decrease the sum. As discussed above, do `i++`.
**Step 8:** i = 3, j = 4
- `sum(i, j) = sum(3, 4) = A[3] + A[4] = 10 + 20 = 30 < k`. To increase the array length, do `j++`.
**Step 9:** i = 3, j = 5
- `sum(i, j) = sum(3, 5) = A[3] + A[4] + A[5] = 10 + 20 + 3 = 33 = k`. We have found the required subarray.
#### Pseudocode
```java
i = 0, j = 0, sum = A[0]
while (j < n) {
if (sum == k) {
return true;
} else if (sum < k) {
j++;
if (j == n) { // To make sure index is not out of bounds
break;
}
sum += A[j];
} else {
sum -= A[i];
i++;
if (i > j) { // To make sure i never exceeds j
break;
}
}
}
return false;
```
- **Time Complexity:**
O(N), as in the worst case, complete array will be traversed.
- **Space Complexity:**
O(1), as no additional space is required if we use same array to create prefix array.
---
### Problem 5 Container with most Water
Given an integer array `A` where array elements represent the height of the wall. Find any two walls that can form a container to store the maximum amount of water.
**Example:**
A = {4, 2, 10, 6, 8, 2, 6, 2}
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/951/original/upload_1a07a9117e364327980824142fcb99c2.png?1696278947" width=600 />
**Ans:** 24. (Maximum amount of water stored between walls at idx (1 and 7) or between idx (3 and 7))
Since `area = height * width`, therefore
Amount of water stored between any two walls `A[i]` and `A[j]` = `min(A[i], A[j]) * (j - i)`, where height = `min(A[i], A[j])` and width = `(j - i)`.
> **Note:** height = `min(A[i], A[j])`, as water can be stored upto minimum height of the wall, and width = `(j - i)`, i.e., the difference between the position of walls.
#### Brute Force Apporach:
*Choose all the pair of walls, calculate the amount of water stored between them and find the maximum.*
- **Time Complexity:**
O(N$^2$), as we need to use two for loops.
- **Space Complexity:**
O(1), as no additional space is required.
---
### Question
What is the water trapped between 2 walls at index L and R.
Array A gives the heights of buildings
Chose the correct answer
**Choices**
- [x] (R - L) * min(A[L], A[r])
- [ ] (R - L)* max(A[L], A[r])
- [ ] (R - L + 1) * min(A[L], A[r])
- [ ] (R - L + 1) * max(A[L], A[r])
**Explanation:**
The answer is **(R - L) * min(A[L], A[r])**.
* Amount of water stored between any two walls A[L] and A[R] = min(A[L], A[R]) * (R - L)
where height = min(A[L], A[R])
width = (R - L).
---
:::warning
Please take some time to think about the optimised approach on your own before reading further.....
:::
### Container with most Water Two Pointer Approach
- Since `area = height * width`. To achieve the maximum area, we should find the maximum values for height and width.
- Let's start with maximum width, so keep i = 0 and j = n - 1.
- `height = min(A[i], A[j])`. So, in order to increase the height, we should move in the direction of increasing the minimum height.
**Example:**
A[] =
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|-------|---|---|---|---|---|---|---|---|
| Value | 4 | 2 | 10 | 6 | 8 | 2 | 6 | 2 |
**Step 1:** i = 0, j = 7, max_area = -1 (Initially)
- `height = min(A[0], A[7]) = min(4, 2) = 2`.
`width = j - i = 7 - 0 = 7`.
`area = height * width = 2 * 7 = 14`.
`max_area = max(max_area, area) = max(-1, 14) = 14`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 2, this can be increased by doing `j--`.
**Step 2:** i = 0, j = 6, max_area = 14
- `height = min(A[0], A[6]) = min(4, 6) = 4`.
`width = j - i = 6 - 0 = 6`.
`area = height * width = 4 * 6 = 24`.
`max_area = max(max_area, area) = max(14, 24) = 24`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 4, this can be increased by doing `i++`.
**Step 3:** i = 1, j = 6, max_area = 24
- `height = min(A[1], A[6]) = min(2, 6) = 2`.
`width = j - i = 6 - 1 = 5`.
`area = height * width = 2 * 5 = 10`.
`max_area = max(max_area, area) = max(24, 10) = 24`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 2, this can be increased by doing `i++`.
**Step 4:** i = 2, j = 6, max_area = 24
- `height = min(A[2], A[6]) = min(10, 6) = 6`.
`width = j - i = 6 - 2 = 4`.
`area = height * width = 6 * 4 = 24`.
`max_area = max(max_area, area) = max(24, 24) = 24`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 6, this can be increased by doing `j--`.
**Step 5:** i = 2, j = 5, max_area = 24
- `height = min(A[2], A[5]) = min(10, 2) = 2`.
`width = j - i = 5 - 2 = 3`.
`area = height * width = 2 * 3 = 6`.
`max_area = max(max_area, area) = max(24, 6) = 24`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 2, this can be increased by doing `j--`.
**Step 6:** i = 2, j = 4, max_area = 24
- `height = min(A[2], A[4]) = min(10, 8) = 8`.
`width = j - i = 4 - 2 = 2`.
`area = height * width = 8 * 2 = 16`.
`max_area = max(max_area, area) = max(24, 16) = 24`.
To increase the area, we need to move in direction of increasing the minimum height. Since min height is 2, this can be increased by doing `j--`.
**Step 7:** i = 2, j = 3, max_area = 24
- `height = min(A[2], A[3]) = min(10, 6) = 6`.
`width = j - i = 3 - 2 = 1`.
`area = height * width = 6 * 1 = 6`.
`max_area = max(max_area, area) = max(24, 6) = 6`.
After this, moving any of i or j will yield width as 0. Hence, we stop the execution and final ans is 24.
#### Pseudocode:
```java
i = 0, j = n - 1;
while (i < j) {
area = min(A[i], A[j]) * (j - 1);
if (A[i] < A[j]) {
i++;
} else if (A[i] > A[j]) {
j--;
} else {
i++, j--; // Doesn't matter if we move only i or j or both
}
}
return area;
```
- **Time Complexity:**
O(N), as we are traversing the complete array only once.
- **Space Complexity:**
O(1), as no additional space is required.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,722 @@
# Beginner: Data Types
---
# Agenda
* Quizes to revise the previous session
* Rules of Naming a variable
* Different categories of Data
* Why we need multiple datatype under one category
* Int Vs Long
* TypeCasting
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
# Question
What will be output for this ?
```
System.out.print(12 + 4 + "try" + 3 * 4);
```
# Choices
- [ ] Error
- [ ] 124try34
- [ ] 16try34
- [x] 16try12
---
# Question
```
Declare a int variable with name x and intialize with value 10
```
# Choices
- [ ] x int = 10;
- [ ] int x = 20
- [x] int x = 10;
- [ ] None of them
---
# Question
```
int x = 10;
int y = 20;
System.out.print(x + y);
```
# Choices
- [ ] Error
- [ ] x + y
- [x] 30
- [ ] 1020
---
# Question
```
int x = 10;
int y = 20;
System.out.print(x + " " + y);
```
# Choices
- [ ] 1020
- [ ] Error
- [x] 10 20
- [ ] 30
---
# Question
```
int try = 10;
System.out.print(Try);
```
# Choices
- [ ] 10
- [ ] Try
- [x] Error
---
# Question
```
System.out.print(x);
int x = 10;
```
# Choices
- [ ] x
- [ ] 10
- [x] Error
- [ ] None of the above
---
**Rule:** In order to use a variable we need to declare and initialise it first.
---
# Question
```
int x = 10;
System.out.print(x + y);
int y = 20;
```
# Choices
- [ ] 30
- [ ] 10y
- [x] Error
- [ ] None of them
---
# Question
```
int x = 10;
int x = 20;
System.out.print(x);
```
# Choices
- [ ] 10
- [ ] 20
- [x] Error
- [ ] None of them
---
**Explanation:**
Here, when we write `int x = 10;`, we are declaring and initialising a variable "x".
Now when we write this statement, `int x = 20;`, again a variable is created of type int, and name x with value 20.
But this is not possible, we cannot have 2 variables with same name.
## **Rule:** We cannot have 2 variables with same name.
---
# Question
```
int x = 20;
System.out.println(x);
x = 40;
System.out.print(x);
```
# Choices
- [ ] 2040
- [ ] Error
- [x] 20 40
---
**Explanation:**
Here, when we write `int x = 20;` , a variable is created of type int and name x.
But `x= 40` means we are not creating the variable, instead changing the value of the variable. This line will change the value of x to 40.
---
# Question
```
int x = 20;
int y = 40;
x = y + 10;
System.out.print(x);
```
# Choices
- [ ] 70
- [ ] 60
- [x] 50
---
**Explanation:**
With very first line, <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/248/original/Screenshot_2023-09-23_104216.png?1695445969" height = "40" width = "120"> ;, we are creating a variable of type int and name x. Again <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/249/original/Screenshot_2023-09-23_104341.png?1695446029" height = "25" width = "120">; another variable is created of type int and name y. Then <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/250/original/Screenshot_2023-09-23_104437.png?1695446089" height = "25" width = "120">; means update the value of x to 50.
---
# Question
```
int x = 20,y = 40;
System.out.print(x + y);
```
# Choices
- [ ] Error
- [ ] x + y
- [x] 60
---
**Explanation:**
Everytime in Java a statement ends with semicolon.
In this line there is a comma so we are trying to create a variable x and y of type int.
**Rule:** We can create two multiple variables of same type in a single line seperated by comma.
---
# Question
```
int x = 20;y = 40;
System.out.print(x + y);
```
# Choices
- [x] Error
- [ ] x + y
- [ ] 60
---
**Explanation:**
Here semicolon is present after 20. That means with <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/251/original/Screenshot_2023-09-23_104216.png?1695446171" height = "45" width = "120" style="margin: -10px 0px 0px 0px;" >; we are creating a variable and <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/252/original/Screenshot_2023-09-23_104656.png?1695446243" height = "25" width = "70" style="margin: 0px 0px 0px 0px;" >; we are not declaring a variable.
---
# Question
```
int x = 20,y = 40,z = 80;
System.out.print(x + y + z);
```
# Choices
- [ ] Error
- [ ] 150
- [x] 140
- [ ] None of them
---
**Explanation:**
Here we are creating 3 variables which are seperated by commas which is possible.
---
## Rules of Naming a variable:
1. Name can only contain lowercase[a - z], uppercase alphabets[A - Z], digits(0 - 9), '\$'{Dollar} or '_' {Underscore}, nothing else
2. Name cannot start with a digit
3. Cannot use reserve keywords as variable name :
Reserve keywords : Words which already have a predefined
meaning in java, they have a predefined use for them
Ex : public, static, void, int, etc :
4. Variable name is also case senstive.
---
# Question
```
How many of them are correct variable names?
int x = 10;
int 1y = 20;
int x@a = 20;
```
# Choices
- [x] 1
- [ ] 2
- [ ] 3
- [ ] 0
---
**Explanation:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/253/original/Screenshot_2023-09-23_104835.png?1695446325" height = "25" width = "120" style="margin: 0px 0px 0px 0px;" >; here second rule is not followed, we are starting a variable name with a digit. This is a invalid variable name.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/254/original/Screenshot_2023-09-23_105017.png?1695446427" height = "30" width = "130" style="margin: 0px 0px 0px 0px;" >; this is also invalid because here we are having @ in variable name which is not allowed.
---
# Question
```
How many of them are correct variable names?
int _y = 10;
int xxy = 20;
int x a = 20;
int y$z = 45;
```
# Choices
- [ ] 1
- [ ] 2
- [x] 3
- [ ] 4
- [ ] 0
---
**Explanation:**
_y -> valid,
xxy -> valid
x a -> cannot have space in name, therefore invalid.
y\$z -> valid.
---
# Question
```
int n = 20;
int N = 30;
System.out.print(n + N);
```
# Choices
- [x] 50
- [ ] 2030
- [ ] Error
---
**Explanation:**
Variables 'n' and 'N' are completely different, Java is case sensitive.
---
# Question
```
int static = 40;
System.out.print(static);
```
# Choices
- [ ] 40
- [ ] static
- [x] Error
---
**Explanation:**
"static" is reserve keyword.
---
## Different categories of Data:
There are 3 categories of Data:
1. Text:
* String: words/sentences.
* char: 1 character
2. Numbers:
a. Decimal:
* float
* double
b. Non-Decimal(Integers):
* byte: almost never used.
* short: almost never used.
* int
* long
3. Boolean:
* boolean
* True/False
### Why We Need Multiple Datatype Under One Category:
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/244/original/upload_bdc30e4d28acbd24dcec0e8e57749503.png?1695445499"
height = "350" width = "700" >
All of them store water.
Difference lies in their storage capacity.
| category | small | medium | large |
|:--------:|:----------:|:------:|:-----:|
| 500ml | yes [ideal] | yes | yes |
| 15L | no | no | yes |
---
### Int Vs Long:
They both have different range.
**int:** <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/245/original/Screenshot_2023-09-23_103645.png?1695445684"
height = "50" width = "200">
**approx:** <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/246/original/Screenshot_2023-09-23_103749.png?1695445719"
height = "55" width = "200">
**long:**<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/247/original/Screenshot_2023-09-23_104014.png?1695445828"
height = "60" width = "200">
**approx:** <img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/255/original/Screenshot_2023-09-23_105318.png?1695446607"
height = "30" width = "200">
---
# Question
Predict the output:
```
int num = 100000; // 10^5
System.out.print(num);
```
# Choices
- [x] 100000
- [ ] Error
- [ ] No clue!
---
**Explanation:**
Here we are creating a variable of type int, name num and value: 100000.
It is in the range if int.
Ans = 100000.
---
# Question
What will be the output?
```
int x = 10000000000; //10^10
System.out.print(x);
```
# Choices
- [ ] 10000000000
- [x] Error
- [ ] Too many zeroes!
---
**Explanation:**
Error, Integer number too large.
Because 10^10 is out of range of int.
---
# Question
Predict the output:
```
long n = 10000000000; // 10^10
System.out.print(n);
```
# Choices
- [x] Error
- [ ] 10000000000
- [ ] Choose me. I am best!
---
**Explanation:**
Error: Integer number too large.
**Rule:** whenever the compiler see a non decimal number it considers it as int.
Now here, We are storing the value 10000000000 into long, But as soon as compiler see the non decimal digit it consider it as int and which is out of range of int. Therefore we get error.
---
# Question
Predict the output:
```
long a = 10000000000L; //10^10
System.out.print(a);
```
# Choices
- [ ] Error
- [ ] a
- [x] 10000000000
- [ ] 10000000000L
---
**Explanation:**
When we write "L" in front of the number it is telling the compiler that consider this number as long, not int.
---
# Question
Predict the output:
```
long a = 10000000000l; //10^10
System.out.print(a);
```
# Choices
- [ ] Error
- [ ] 10000000000l
- [x] 10000000000
- [ ] Too tired to count zeroes!
---
**Explanation:**
Either use "L" or "l", both will work.
----
## TypeCasting:
Typecasting means converting one datatype to another.
Basically, Tranfering data from one container to another.
**Anology:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/256/original/upload_c9d475a202262c1a5c542216c6589737.png?1695446752" height = "280" width = "700" >
1. We can easily transfer water from 5L bucket to 20; bucket.
From smaller storage to higher storage, we can easily do it.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/257/original/upload_56a679ca68e84294e7fa9897f30e6f94.png?1695446782" height = "280" width = "700" >
2. We can again transfer water from 20L bucket to 5L bucket, if the water level is less than 5L.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/258/original/upload_6a3bb23eb0715c66bbe4ea20ebe87e2c.png?1695446814" height = "280" width = "700" >
3. We have 8L of water in 20l bucket, now this time when we try to transfer it to 5L bucket, overflow will happen. Water will flow outside of the bucket as well. It will spill.
**Replicate the example with data types:**
5L bucket: int
20L bucket: long.
4. Easily transfer data from int(smaller) to long(bigger).
---
# Question
```
int a = 1000;
long b = a;
System.out.print(b);
```
# Choices
- [x] 1000
- [ ] Error
---
**Explanation:**
Here,`int a = 1000;` we are trying to create a int type variable of name a, value 1000.
Now `long b = a;` with this we create a long type variable, name b.
b = 1000.
And we can easily store 1000 in long.
**It is Implicit/Widening TypeCasting(automatic).**
---
# Question
```
long x = 10000;
System.out.print(x);
```
# Choices
- [x] 1000
- [ ] Error
---
**Explanation:**
Java considers non decimal number as int.
Therefore, the value 10000 is considered as int and we are trying to store int value into long which is possible.
Int to Long is implicit typecasting.
---
# Question
```
long x = 10000;
int y = x;
System.out.print(y);
```
# Choices
- [ ] 1000
- [x] Error
---
**Explanation:**
`long x = 10000` It is implicit typecasting.
But, `int y = x;` Here we are trying to store long value into int container.
Error: Possible lossy conversion.
---
# Question
```
long x = 1000;
int y = (int)x;
System.out.print(y);
```
# Choices
- [x] 1000
- [ ] Error
---
**Explanation:**
Here we are doing Explicit/Narrowing Typecasting from long to int.
---
# Question
```
long a = 10^10;
int b = (int)a;
System.out.print(b);
```
# Choices
- [ ] 10^10
- [ ] 10^10L
- [x] Error
- [ ] Some random value
---
**Explanation:**
Here, value 10^10 is too large for int.
Ans = Error, Integer number too large.
---
# Question
```
long a = 10^10L;
int b = (int)a;
System.out.print(b);
```
# Choices
- [ ] 10^10
- [ ] 10^10L
- [ ] Error
- [x] Some random value
---
**Explanation:**
Here, We are specifying L so compiler considers 10^10 as long only and then we are trying to store in a long container only which is possible.
After that in next line we are doing explicit typecasting, but then also we know that this number is out of range of int.
We are actually forcing the compiler to do it, data loss will happen.
---
Some quizzes to revise
---
# Question
```
int a = (int)10000000000L;
System.out.print(a);
```
# Choices
- [x] Some Random Value
- [ ] Error
- [ ] Very Complicated
---
# Question
```
int a = (int)10000000000;
System.out.print(a);
```
# Choices
- [ ] Some Random Value
- [x] Error
- [ ] 10000000000

View File

@@ -0,0 +1,597 @@
# Patterns Introduction
---
## Agenda
**Some abbreviations that will be used in this class:**
* System.out.print - SOP
* System.out.println - SOPln
We will work with patterns today. After this class, the students will feel very comfortable with loops.
1. Print stars in a single row
2. Print a square
3. Print a rectangle
4. Print staircase
5. Print reverse staircase
6. Print special pattern
---
# Question
Loop to print " * " N times in a single row?
Ex: N = 5, print *****
N = 9, print *********
# Choices
- [x] for(int i = 1; i <= N; i++) {
SOP(" * ");
}
- [ ] for(int i = 1; i < N; i++) {
SOP(" * ");
}
- [ ] for(int i = 0; i <= N; i++) {
SOP(" * ");
}
---
## Explanation
```java
for(int i = 1; i <= N; i++) {
SOP(" * ");
}
```
This choice is correct. The code uses a loop to iterate from `i = 1` to `i = N` (both inclusive). In each iteration, it prints the "*" character using the `SOP("*");` statement. This loop will print "*" N times in a single row, as desired.
Certainly, let's take a look at why the other two choices are incorrect:
1. **Incorrect Choice 2:**
```java
for (int i = 1; i < N; i++) {
SOP(" * ");
}
```
**Explanation:** This code uses a loop that starts from `i = 1` and continues until `i` is less than `N`. In each iteration, it prints an asterisk. However, this loop only iterates `N - 1` times, which means it will print one less asterisk than the desired value. For example, if `N` is 5, this loop will print `****` (4 asterisks) instead of `*****`.
2. **Incorrect Choice 3:**
```java
for (int i = 0; i <= N; i++) {
SOP(" * ");
}
```
**Explanation:** This code uses a loop that starts from `i = 0` and continues until `i` is less than or equal to `N`. In each iteration, it prints an asterisk. However, this loop iterates `N + 1` times, which means it will print one more asterisk than the desired value. For example, if `N` is 5, this loop will print `******` (6 asterisks) instead of `*****`.
---
### Example 1
This is the quiz question.
Print N starts " * " in a single row.
N = 5, *****
N = 4, ****
N = 2, **
**Q.** What should be the number of iterations?
**A.** "N"
**Code:**
```
public static void main() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.print(" * ");
}
}
```
Dry run the codes and justify why Option 1 is correct for some values of N.
---
### Example 2
Print a square (N * N) of stars.
For example,
N = 4
```plaintext
****
****
****
****
```
N = 5
```plaintext
*****
*****
*****
*****
*****
```
**Q.** If you have to repeat a single task N number of tasks, how to do that?
**A.** We can write a loop.
Now, this questions is similar to repeating 1st task N number of times.
So, the code can be:
```
for (int i = 1; i <= N; i++) {
for (int i = 1; i <= N; i++) {
SOP(" * ");
}
SOPln();
}
```
Ask students if this code is correct. It's not, because we cannot repeat variable 'i' in java.
So, the final correct code is:
```
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
SOP(" * ");
}
SOPln();
}
```
Explain why we need `SOPln()` after the 2nd for loop.
**Explanation:**
Without the `SOPln()` statement after the inner loop, all the asterisks would be printed in a single continuous line, and the pattern would not be formed with rows and columns. The `SOPln()` call ensures that each row of asterisks is printed on a new line, creating the desired pattern.
Dry run the above code for N = 3.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/810/original/upload_f645c770eeb92640a9f8cc6db03c3cc4.png?1693755503"
height = "350" width = "450">
---
### Example 3
Print rectangle of N * M having stars.
N rows having M stars in each row.
For example,
N = 4, M = 3
```plaintext
***
***
***
***
```
N = 2, M = 4
```plaintext
****
****
```
Outer loop -> N times
Inner loop -> M times
The correct code is:
```
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
SOP(" * ");
}
SOPln();
}
```
**Note:** Mention that the starting values does not matter. Just that the number of iterations should be N.
Dry run for N = 2, M = 3.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/812/original/upload_a445fa2609ea3cf56e1734ba8f432818.png?1693755542"
height = "300" width = "6000">
**Observation Table:**
| Row | Stars |
|:---:|:-----:|
| 1 | 3 |
| 2 | 3 |
ith row => M stars
and a total N rows
---
### Example 4
Print staircase pattern.
For example,
N = 4
```plaintext
*
**
***
****
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
Observe for each row number i, we have i stars in that row.
Outer Loop -> N times
Inner Loop -> i times
Inner loop does not work for constant number of times.
**Observation Table:**
| Row | Stars |
|:---:|:-----:|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
ith row => i stars
The correct code is:
```
for (int i = 1; i <= N; i++) {
// Loop to print i stars.
for (int j = 1; j <= i; j++) {
SOP(" * ");
}
SOPln();
}
```
Dry run this code for N = 4 (Given image is incomplete).
You may complete the dry run or stop in-between according to the batch.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/813/original/upload_210e5f09585ebf945b8091effbbc4957.png?1693755626"
height = "350" width = "600">
---
### Example 5
> **Note for instructor:** Give some context of why we are learning this approach. Like, as similar approach will work in majority of pattern questions
Print reverse staircase pattern.
For example,
N = 4
```plaintext
****
***
**
*
```
N = 5
```plaintext
*****
****
***
**
*
```
For N = 5, we are printing stars in the following manner.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/814/original/upload_603a3fffb7a60cb436ec6c3f9cd701d8.png?1693755658"
height = "300" width = "450">
Row + star = N + 1
So, star = N + 1 - Row
Observe for each row number i, we have N - i + 1 stars in that row.
Outer Loop -> N times
Inner Loop -> N - i + 1 times
Inner loop does not work for constant number of times.
The correct code is:
```java
for (int i = 1; i <= N; i++) {
// Loop to print N - i + 1 stars.
for (int j = 1; j <= N - i + 1; j++) {
SOP(" * ");
}
SOPln();
}
```
Dry run the code for N = 3.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/815/original/upload_36fc6fad1038306dbbea3e096487fb78.png?1693755708"
height = "300" width = "500">
---
#### Another Approach
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/816/original/upload_9e6e30919023e0f930c7d6a77dbfc12d.png?1693756190"
height = "250" width = "500">
In this approach, we will change the starting value of i itself.
The correct code is:
```
for (int i = N; i >= 1; i--) {
// Loop to print i stars.
for (int j = 1; j <= i; j++) {
SOP(" * ");
}
SOPln();
}
```
---
### Example 6
Print the diamond pattern.
For example,
N = 5
```plaintext
**********
****--****
***----***
**------**
*--------*
*--------*
**------**
***----***
****--****
**********
```
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/817/original/upload_52ad209dbb64e8caaea062a196388d88.png?1693756234"
height = "300" width = "550">
You are only supposed to print star " * ", but not underscores (they should be spaces).
If N = 5, so 10 rows are needed.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
The pattern can be broken into two halves.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/820/original/upload_308e046a7c9a3d5a090c91f4bdbeb45c.png?1693756293"
height = "400" width = "250">
Again, we can break this pattern into halves again.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/821/original/upload_7f1f949912f01d8526b41b664739fcbe.png?1693756327"
height = "200" width = "550">
For the right quarter, we need to print some spaces first and then stars.
The table shows for each row, how many spaces and stars need to be printed.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/822/original/upload_f12e19981999da489adddc4e0116fb84.png?1693756365"
height = "300" width = "500">
Combining everything for the first half, we have the following table.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/823/original/upload_2eab4eb6d8be0559bd3c33a7aaa316c3.png?1693756386"
height = "300" width = "500">
In one single row,
print (N + 1 - i) stars + (i - 1) spaces + (i - 1) spaces + (N + 1 - i) stars
So, print (N + 1 - i) stars + 2 * (i - 1) spaces + (N + 1 - i) stars
So, let's write the code for the upper half using the above facts.
```
for (int i = 1; i <= N; i++) {
// In each row, print N + 1 - i stars.
for (int j = 1; j <= N + 1 - i; j++) {
SOP(" * ");
}
// In each row, (i - 1) spaces.
for (int j = 1; j <= 2 * (i - 1); j++) {
SOP(" _ ");
}
// In each row, print N + 1 - i stars.
for (int j = 1; j <= N + 1 - i; j++) {
SOP(" * ");
}
SOPln();
}
```
**Lower Half:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/824/original/upload_de9788a8310b94486706ebd6b69671bb.png?1693756417"
height = "200" width = "300">
For lower part, we can directly write the following table:
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/825/original/upload_17ef3ebc6ea5203765bad9eca9915b17.png?1693756437"
height = "310" width = "700">
In one single row,
print i stars + print (N - i) spaces + print (N - i) spaces + i stars
So, print i stars + print 2 * (N - i) spaces + i stars
So, let's write the code for the upper half using the above facts.
```
for (int i = 1; i <= N; i++) {
// In each row, print N + 1 - i stars.
for (int j = 1; j <= i; j++) {
SOP(" * ");
}
// In each row, (i - 1) spaces.
for (int j = 1; j <= 2 * (N - i); j++) {
SOP(" _ ");
}
// In each row, print N + 1 - i stars.
for (int j = 1; j <= i; j++) {
SOP(" * ");
}
SOPln();
}
```
Combining these 2 codes we get, the diamond pattern.
---
### Example 7
Print the following pattern:
For example,
N = 5
```plaintext
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
```
N = 4
```plaintext
1
2 3
4 5 6
7 8 9 10
```
We will create a variable and print that variable. After printing, we increment it.
```
int val = 1;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= i; j++) {
SOP(val);
val++;
}
SOPln();
}
```
**Explanation:**
In the given approach we have initialized a variable `val` to 1. It employs an outer loop that iterates from 1 to N, governing the rows. Within this loop, an inner loop runs from 1 to the current value of the outer loop index, controlling the values within each row. It prints the value of `val`, increments it, and then proceeds with the next iteration of the inner loop. This structure creates a pattern where each row holds an increasing sequence of numbers. The `SOPln()` statement at the end of the outer loop iteration ensures a new line for the subsequent row. By iteratively printing values and managing rows through nested loops, the code systematically generates the desired pattern of numbers.
---
### Example 8
Print the following pattern:
For example,
N = 5
```plaintext
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach 1:**
```
for (int i = 1; i <= N; i++) {
int val = 1;
for (int j = 1; j <= i; j++) {
SOP(val);
val++;
}
SOPln();
}
```
**Approach 2:**
In this approach instead of taking an extra variable we can directly print j.
```
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= i; j++) {
SOP(j);
}
SOPln();
}
```
---
### Example 9
Print the following pattern.
For example,
N = 5
```plaintext
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
```
The pattern now starts at each row with that row number. So, only 1 change is required i.e, in the initial value of val.
The correct code for this pattern is:
```
for (int i = 1; i <= N; i++) {
int val = i;
for (int j = 1; j <= i; j++) {
SOP(val);
val++;
}
SOPln();
}
```
---

View File

@@ -0,0 +1,550 @@
# Beginner: Patterns 2 & Introduction to Strings
---
### Agenda
1. Print reverse triangle V
2. Print numeric triangle /\
3. Strings
4. next() vs nextLine()
5. How to deal with different type of inputs
6. Character Pattern
---
### Problem Statement
Print the following pattern:
For example,
N = 5
```
* * * * *
* * * *
* * *
* *
*
```
N = 4
```
* * * *
* * *
* *
*
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Observation
Lets consider the spaces as "_"
```
* _ * _ * _ * _ * _
_ * _ * _ * _ * _
_ _ * _ * _ * _
_ _ _ * _ * _
_ _ _ _ * _
```
Now lets assume we are removing the spaces after every '*', then
```
* * * * *
_ * * * *
_ _ * * *
_ _ _ * *
_ _ _ _ *
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/588/original/observation.jpg?1706503692" width=600/>
While printing stars, remember to print a space after every star, to get the our required reverse triangle pattern.
### Code
```java
for (int i = 0; i < N; i++) {
//loop to print i spaces
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//loop to print n-i stars
for (int j = 1; j <= n - i; j++) {
System.out.print("* ");
}
System.out.println();
}
```
---
### Problem Statement
Print the following pattern:
For example,
N = 5
```
0 0 0 0 1 0 0 0 0
0 0 0 2 3 2 0 0 0
0 0 3 4 5 4 3 0 0
0 4 5 6 7 6 5 4 0
5 6 7 8 9 8 7 6 5
```
N = 4
```
0 0 0 1 0 0 0
0 0 2 3 2 0 0
0 3 4 5 4 3 0
4 5 6 7 6 5 4
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Approach
Lets divide the pattern into two halfs,
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/594/original/patter.png?1706505291" width=500/>
Lets consider the 2 halves separately,
### First Half
| **0** | **0** | **0** | **0** | **1** |
|-------|-------|-------|-------|-------|
| **0** | **0** | **0** | **2** | **3** |
| **0** | **0** | **3** | **4** | **5** |
| **0** | **4** | **5** | **6** | **7** |
| **5** | **6** | **7** | **8** | **9** |
Lets create a table, on observing the pattern.
| row | zeros | start | end |
|-----|---------|-------|-----------|
| 1 | 4 [5-1] | 1 | 1 [2\*1-1] |
| 2 | 3 [5-2] | 2 | 3 [2\*2-1] |
| 3 | 2 [5-3] | 3 | 5 [2\*3-1] |
| 4 | 1 [5-4] | 4 | 7 [2\*4-1] |
| 5 | 0 [5-5] | 5    | 9 [2\*5-1] |
We can come up with an generalized pattern on observing the values of the table based on the value i.
| ith row | (n - i) zeros | starts with i | ends with 2 * i - 1 |
|---|---|---|---|
### Psuedo code for First Half
```java
// Printing (n - i) zeros
for (int j = 1; j <= n - i; j++){
System.out.print(0 + " ");
}
int lim = 2 *i - 1;
// Printing the increasing numbers from i to 2*i-1
for (int j = i; j <= lim; j++){
System.out.print(j + " ");
}
```
### Second Half
| **0** | **0** | **0** | **0** |
|-------|-------|-------|-------|
| **2** | **0** | **0** | **0** |
| **4** | **3** | **0** | **0** |
| **6** | **5** | **4** | **0** |
| **8** | **7** | **6** | **5** |
Lets create a table, on observing the pattern.
| row | start | end | zeros |
|-----|-----------|-----|-------|
| 1 | | | 4 |
| 2 | 2 [2\*2-2] | 2 | 3 |
| 3 | 4 [2\*3-2] | 3 | 2 |
| 4 | 6 [2\*4-2] | 4 | 1 |
| 5 | 8 [2\*5-2] | 5   | 0     |
We can come up with an generalized pattern on observing the values of the table based on the value i.
| ith row | starts with (i * 2 - 2) | ends with i | (n i) zeros |
|---|---|---|---|
Here **starts with (i * 2 - 2)** can be even simplified, by using the end value of the previous calculation as **end - 1**.
### Psuedo code for Second Half
```java
// For the Second Half
// Printing the decreasing numbers
int lim = 2 *i - 1;
for (int j = lim - 1; j >= i; j--){
System.out.print(j + " ");
}
//loop to print n - i zeros
for (int j = 1; j <= n - i; j++){
System.out.print(0 + " ");
}
```
### Overall Code
``` java
for (int i = 1; i <= n; i++){
// For the First Half
//loop to print n - i zeros
for (int j = 1; j <= n - i; j++){
System.out.print(0 + " ");
}
int lim = 2 *i - 1;
// Printing the increasing numbers from i to 2*i-1
for (int j = i; j <= lim; j++){
System.out.print(j + " ");
}
// For the Second Half
// Printing the decreasing numbers
for (int j = lim - 1; j >= i; j--){
System.out.print(j + " ");
}
//loop to print n - i zeros
for (int j = 1; j <= n - i; j++){
System.out.print(0 + " ");
}
System.out.println();
}
```
---
### Reading Inputs for Strings
**1. sc.next()-> cannot take spaces as input**
Ques1:
```java
Input: "Hello World"
String s1 = sc.next();
System.out.println(s1);
String s2 = sc.next();
System.out.println(s2);
```
Output:
```plaintext
Hello
World
```
Explanation:
s1 will have first word, Hello
s2 will have next word, World
**2. sc.nextLine() -> can take spaces as well, until next line is encountered.**
Ques1:
```java
Input: Hello World
String s3 = sc.nextLine();
System.out.println(s3);
```
Output:
```plaintext
Hello World
```
---
# Question
Input :
```
Hello World
```
```
Scanner scn = new Scanner(System.in);
String str1 = scn.next();
String str2 = scn.next();
System.out.println(str1);
System.out.println(str2);
```
# Choices
- [x] Hello <br> World
- [ ] Hello
- [ ] World
- [ ] None of the above
---
Output:
```plaintext
Hello
World
```
Explanation:
str1 will have, Hello
str2 will have next word, World
---
# Question
Input:
```
Hello Welcome in Scaler
```
```
Scanner scn = new Scanner(System.in);
String str1 = scn.next();
String str2 = scn.nextLine();
System.out.println(str1);
System.out.println(str2);
```
# Choices
- [ ] Hello
- [ ] Error
- [x] Hello <br> Welcome in Scaler
- [ ] None of the above
---
Output:
```plaintext
Hello
Welcome in Scaler
```
Explanation:
str1 will have first word, Hello
str2 will have complete line after hello, Welcome in scaler(including space before welcome).
---
**Rule:** When the inputs are given in separate lines, and we take a String input using nextLine() after taking number input[nextInt(), nextLong(), nextFloat(), nextDouble()] or a single word [next()] then we get a empty String.
### Example
### Input
```
45
Hello World!
```
``` java
Scanner sc = new Scanner(System.in);
int x = sc.nextInt(); // x[45]
String st = sc.nextLine(); // st -> Empty String
String st2 = sc.nextLine(); // st2 -> "Hello World!"
System.out.println(st);
System.out.println(s2);
```
### Output
```
Hello World!
```
---
# Question
Predict the output :
```
Input-
11
Super Excited!
```
```
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
String str = scn.nextLine();
System.out.println(x);
System.out.println(str);
```
# Choices
- [ ] 11 Super Excited!
- [ ] Error
- [ ] 11 <br> Super Excited!
- [x] 11
---
# Question
Predict the output :
```
Input-
11
Super Excited!
```
```
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
String str = scn.nextLine();
System.out.println(x);
System.out.println(str);
System.out.println("The End");
```
# Choices
- [ ] 11 Super Excited! The End
- [x] 11 <br> <br> The End
- [ ] Error
- [ ] 11 <br> Super Excited! <br> The End
---
### Character:
A character represent a single symbol.
There are different types of characters:
* Uppercase characters : ['A' - 'Z']
* Lowercase characters : ['a' - 'z']
* Numeric characters: ['0' - '9']
* Special characters: ['@', '#', '\$', '%', '&'...]
There are a total of 128 characters.
### Syntax
**Example 1:**
```java
char ch = 'a';
System.out.println(ch);
```
**Output:**
```plaintext
a
```
**Example 2:**
```java
char ch = 'ab';
System.out.println(ch);
```
**Output:**
```plaintext
Error: Only a single symbol is a character.
```
---
### Problem Statement
Write a program to print all characters from A to Z.
### Code
```java
public static void printCharacters(String str) {
for(char i = 'A'; i <= 'Z'; i++) {
System.out.println(i);
}
}
```
---
### Character Stairacase Pattern
N = 5
```
A
A B
A B C
A B C D
A B C D E
```
N = 3
```
A
A B
A B C
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Approach
Consider the spaces as underscores (for better visualization).
Lets take N = 5,
```
A _
A _ B _
A _ B _ C _
A _ B _ C _ D _
A _ B _ C _ D _ E _
```
Lets assume we are printing the standard stair case pattern,
```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
```
Now both the patterns is similar. So, instead of printing numbers, we just create a new variable, which starts with **A**, then increment inside the innerloop.
### Code
``` java
for (int i = 1; i <= N; ++i) {
char ch = 'A';
for (char j = 1; j <= i; j++) {
System.out.print(ch + " ");
ch++;
}
System.out.println();
}
```
---

View File

@@ -0,0 +1,688 @@
# 1D Arrays 1
---
## Agenda
1. Introduction to Arrays
2. Reading Input
3. Indexing and Properties
4. Sum of all elements
5. Frequency of k in array
6. Max of all elements
---
### Example
Let's say we need to read four inputs for our programme. We can use the below approach.
#### Code
```java
public static void main(String[] args) {
int a, b, c, d;
Scanner scanner = new Scanner(System.in);
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
d = scanner.nextInt();
}
```
Some one can suggest that we should use loop to get all four values like :-
#### Code
```cpp
public static void main(){
for(int i = 1; i <= 4;i ++ ){
int a = sc.nextInt();
}
}
```
The above provided approach is wrong because what we are doing is updating the value of variable `a` in each iteration due this a would be set to the last input value provided.
---
### Concept of Arrays
* In above example what is instead of four there are hundreds of value to store. It would be manually infeasible to declare and set hundreds of variables.
* Therefore to overcome above problem we use **arrays**
#### Array
It is a data structure that can hold fixed number of values of same data type.
#### Syntax
```cpp
datatype name[] = new datatype[size]
// example
float f[] = new float[10]
int arr[] = new int[10]
// Various ways
datatype[] name = new datatype[size]
datatype []name = new datatype[size]
```
---
# Question
Correct way to create an Array containing 5 int values in Java?
# Choices
- [x] int[] ar = new int[5]
- [ ] int[] ar = new int[4]
- [ ] int[] ar = int new[5]
---
## Explanation
Since size is 5 and datatype is int using above provided syntax rules:
int[] ar = new int[5]
---
### Indexing and Properties
* Indexing in array starts from **0**.
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
* Accessing an element at **i<sup>th</sup>** index in an array can be done as follows:-
```cpp
nameOfArray[i]
```
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/869/original/upload_7feaa615de84a0773827cd5f5904fc43.png?1693761847"
height = "290" width = "500">
---
# Question
`int[] ar = new int[6];`
How can we access last position element ?
# Choices
- [x] ar[5]
- [ ] ar[6]
- [ ] ar[4]
- [ ] ar[7]
---
## Explanation
Since size is 6 indexing would be like :-
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|
| arr | 0 | 0 | 3 | 0 | 0 | 0 |
last element would be at index 5
---
# Question
`int[] ar = new int[10];`
How can we access last position element ?
# Choices
- [x] ar[9]
- [ ] ar[10]
- [ ] ar[7]
- [ ] ar[8]
---
## Explanation
Since size is 10 indexing would be like :-
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| ar | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
last element would be at index 9
---
# Question
Say int[] ar = new int[N]
How to access first element and last element ?
# Choices
- [x] ar[0] ar[N-1]
- [ ] ar[0] ar[N]
- [ ] ar[1] ar[N]
---
## Explanation
By observing previous questions we can generalize the idea that :-
* Last element in array 'arr' of size 'N' is accessed as `arr[N-1]`.
* First element in array 'arr' of size 'N' is accessed as `arr[0]`.
---
# Question
What is the Output of
```java
public static void main(String args[]) {
int[] arr = new int[10];
int n = arr.length;
System.out.println(n);
}
```
# Choices
- [x] 10
- [ ] 9
- [ ] 8
---
* By default values in an array of type `int` are intialized with **'0'**
---
# Question
What will be the output?
```java
public static void main(String args[]) {
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
int sum = 0;
for(int i = 0; i < 5;i ++ ) {
sum += arr[i];
}
System.out.println(sum);
}
```
# Choices
- [x] 30
- [ ] error
- [ ] 20
- [ ] 43
---
## Explanation
By observing previous questions we can generalize the idea that :-
* Last element in array 'arr' of size 'N' is accessed as `arr[N-1]`.
* First element in array 'arr' of size 'N' is accessed as `arr[0]`.
#### Solution
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/871/original/p17.png?1693762040"
height = "290" width = "500">
---
# Question
```java
public static void main(String args[]) {
int[] arr = new int[5];
System.out.println(arr[0]);
}
```
# Choices
- [x] 0
- [ ] error
- [ ] random number
- [ ] 43
---
# Question
```java
public static void main(String args[]) {
int[] ar = new int[3];
ar[0] = 10;
ar[1] = 20;
ar[2] = 30;
System.out.print(ar[0] + ar[3]);
}
```
# Choices
- [x] error
- [ ] 0
- [ ] 40
- [ ] 60
---
# Question
```java
public static void main(String args[]) {
int[] ar = new int[3];
ar[0] = 10;
ar[1] = 20;
ar[2] = 30;
System.out.print(ar[0] + ar[2]);
}
```
# Choices
- [x] 40
- [ ] 0
- [ ] error
- [ ] 60
---
# Question
```java
public static void main(String args[]) {
int[] ar = new int[3];
ar[0] = 10;
ar[1] = 20;
ar[2] = 30;
System.out.print(ar[-1] + ar[3]);
}
```
# Choices
- [x] error
- [ ] 0
- [ ] 40
- [ ] 60
---
We can reassign an array to replace the previous value it was referencing.
**Code:**
```java
public static void main(){
int[] ar = new int[6];
ar= new int[2];
S.O.Pln(arr.length);
}
```
**Output:**
```plaintext
2
```
---
* We can directly store elements into an array
**Code:**
```java
int ar[] = {10,20,30};
```
---
### Creating and Reading an array
#### Create an array of size 4 and print sum of all it's element :-
* Let's create an array of size 4 and take input.
```java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
arr[0] = sc.nextInt();
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();
arr[3] = sc.nextInt();
}
```
* In above approach we have to take input for each index manually which is not a good idea.
* So **How can we take inputs efficiently ?**
* **Solution** :- We use a loop.
* But **how to apply loop to take array input ?**
* On observing above approach we will find that only index changes each time we take an input.
* **In each iteration we change the index number.**
* We iterate starting from 0 till last index i.e. array size -1.
```java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
for (int i = 0; i < 4; i ++ ) {
arr[i] = sc.nextInt();
}
}
```
---
### Passing Array to Functions
#### Create a Function Which Takes arr[] as A Parameter and Print the Array
* We need to declare a function which takes array as parameter to function.
* It can be done like :-
`Function nameOfFunction(dataType anyName[]){}`
* '`[]`' are important for distinguishing array type parameter from other variable type parameters.
* **How can we access the length of array from function ?**
* We use `array.length` for this purpose.
* We can pass array parameter to function call like:
`functionName(arrayName)`
* **We only need to pass array name.**
```java
static void printArray(int[] ar) {
int n = ar.length;
for (int i = 0; i < n; i ++ ) {
System.out.print(ar[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
for (int i = 0; i < 4; i ++ ) {
arr[i] = sc.nextInt();
}
printArray(arr);
}
```
We take the sum of all elements of array as follows :-
```java
public static void main(String[] args) {
int[] arr = new int[4]; // creates an array of size 4
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 4; i ++ ) {
arr[i] = scanner.nextInt();
}
int sum = 0;
for (int i = 0; i < 4; i ++ ) {
sum += arr[i]; // add element at ith index to sum variable
}
System.out.println(sum);
}
```
---
### Problem 1
Given an array and k. Write a function to return the frequency of k in array?
#### Testcase
```java
arr[7] = [3,6,7,6,11,6,14]
k = 6
```
#### solution
```plaintext
ans = 4
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
* We need to create a function and pass array and k as parameters to the function.
* Inside the function :-
* Maintain a count variable which is intialised to 0.
* Iterate over the array:-
* If element at current index equals k increament count by 1.
* Return count.
#### Trace
![]()
#### Solution
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/873/original/p22.png?1693762207"
height = "200" width = "500">
#### Pseudeocode
```cpp
static int frequencyK(int[] ar, int k) {
int n = ar.length;
int count = 0;
for (int i = 0; i < n; i ++ ) {
if (ar[i] == k) {
count ++ ;
}
}
return count;
}
```
---
### Problem 2
Given an array . Write a function to return the maximum element present in array?
#### Testcase 1
```cpp
arr[6] = [3,1,7,6,9,11]
```
#### solution
```plaintext
ans = 11
```
#### Testcase 2
```plaintext
arr[6] = [4,2,7,9,12,3]
```
#### solution
```plaintext
ans = 12
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach 1
* We need to create a function and pass array as parameters to the function.
* Inside the function :-
* Maintain a max variable which is intialised to 0.
* Iterate over the array:-
* If element at current index is greater than max then set max to current element.
* Return max.
#### Trace 1
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/957/original/p23.png?1683759983"
height = "150" width = "500">
![]()
#### Trace 2
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/958/original/p24.png?1683760023" height = "150" width = "500">
#### Code
```java
static int maxElement(int array[]) {
int n = array.length;
int max = Integer.MIN_VALUE; // Initialize max with the smallest possible integer value
for (int i = 0; i < n; i ++ ) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
```
**There is a flaw in above code.** Let's see it with help of an testcase.
#### Testcase 3
```cpp
arr[4] = [ - 8, - 4, - 3, - 5]
```
#### solution
```cpp
ans = - 3
```
* Let' apply approach 1 to testcase 3
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/959/original/p25.png?1683760451" height = "150" width = "500" >
* In trace we get the answer as 0 whereas the correact answer is -3. **Why ?**
#### Issue
**Since max/ans variable is intialised to 0 which is already greater than all elements in array therefore max/ans is not updated.**
---
# Question
For taking sum of N numbers we initialise our sum variable with =
# Choices
- [x] 0
- [ ] 9
- [ ] 1
---
title: Quiz 13
description:
duration: 30
card_type : quiz_card
---
# Question
For taking product of N numbers we initialise our product variable with `=`
# Choices
- [ ] 0
- [ ] 9
- [x] 1
---
* Based upon observations from above questions we need to intialize max/ans in such a manner that it won't affect the answer.
* We intialize the ans/max variable to **- &#8734;**(negative infinity) so that it does not affect the final answer.
* We do this by **Integer.MIN_VALUE**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/961/original/p27.png?1683761781" height = "350" width = "500">
#### Code
```java
static int maxElement(int[] ar) {
int n = ar.length;
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i ++ ) {
if (ar[i] > max) {
max = ar[i];
}
}
return max;
}
```

View File

@@ -0,0 +1,606 @@
# 1D Array - 2
# Agenda
1. Revision
2. Implement Function
3. Increasing Order [increasing and non-decreasing]
4. Drawbacks of Array
5. Right shift of the array
6. Array List introduction
7. Functions [add, get, set, remove, size, sort]
8. ArrayList functions via code
9. Write a function which takes arrayList as input and update all values by 1
10. Return an arraylist with all even numbers
---
## Revision
Let us revise what we discussed in the last class wit the help of quizzes.
---
# Question
What will be output for this program ?
```java
int[] myArray = {1, 2, 3, 4, 5};
System.out.println(myArray[2]);
```
# Choices
- [ ] 2
- [x] 3
- [ ] 4
---
# Question
What will be output for this program ?
```java
int[] myArray = new int[3];
System.out.println(myArray[1]);
```
# Choices
- [x] 0
- [ ] Null
- [ ] Error
---
# Question
What will be output for this program ?
```java
int[] myArray = {1, 2, 3, 4, 5};
System.out.println(myArray.length);
```
# Choices
- [ ] 4
- [ ] 0
- [x] 5
---
# Question
What will be output for this program ?
```java
int[] myArray = {1, 2, 3, 4, 5};
myArray[2] = 6;
System.out.println(myArray[2]);
```
# Choices
- [x] 6
- [ ] 3
- [ ] 3
- [ ] Error
---
## Return arr[] Syntax
### Implement Function
Given N, create an array of size N, which should contain all elements in increasing order from 1 to N.
## Example
```plaintext
N = 3
arr[3] = { 1, 2, 3 }
N = 5
arr[5] = { 1, 2, 3, 4, 5 }
```
---
# Question
Given N = 6, create an array of size N containing all elements in increasing order from 1 to N.
# Choices
- [ ] 0 1 2 3 4 5 6
- [x] 1 2 3 4 5 6
- [ ] 6 5 4 3 2 1
---
# Implement Function Code
## Pseudocode
```java
static int[] num(int N){
int arr = new int[N];
for(int i = 0; i < N; i++){
arr[i] = i + 1;
}
return arr;
}
```
---
## Increasing Order
Numbers arranged from smallest to largest.
**Note:** If elements are equal then no issues
## Scritly Increasing Order
Arrangement of numbers such that the next number is always greater than the previous number.
---
# Question
Check whether the given numbers are in increasing order?
`3, 4, 4, 4, 4, 5, 5, 7, 9, 18, 18, 26`
# Choices
- [x] yes
- [ ] no
- [ ] maybe
---
# Question
Check whether the given numbers are in increasing order?
`-1, -2, -3, -4, -5`
# Choices
- [ ] Yes
- [x] No
- [ ] Maybe
---
# Question
Check whether the given numbers are in strictly increasing order?
`3, 9, 16, 24, 29, 29, 34, 50`
# Choices
- [ ] Yes
- [x] No
- [ ] Maybe
---
### Checking Strictly Increasing Array
Given an integer N, create an array of size N containing elements in increasing order from 1 to N. Check if the created array is strictly increasing (each element is greater than the previous element).
#### Example
For N = 5, the array `arr` will be `{1, 2, 3, 4, 5}`, and it is strictly increasing.
For N = 5, the array `arr` will be `{1, 2, 2, 4, 5}`, and it is not strictly increasing.
---
# Question
Check whether the given numbers are in strictly increasing order?
`21, 39, 46, 97, 105`
# Choices
- [x] Yes
- [ ] No
- [ ] Maybe
---
## If Array Is Strictly Increasing Code
**Note to instructor:** Explain logic of implementing this in code format here
### Pseudocode
```java
static boolean isStrictlyIncreasing(int N) {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = i + 1;
}
for (int i = 1; i < N; i++) {
if (arr[i] < arr[i - 1]) {
return false; // Array is not strictly increasing
}
}
return true; // Array is strictly increasing
}
```
---
## Right Shift of An Array
Given an array of size N, shift all the elements to the right by 1 and move the last element to the beginning of array
## Example 1
```plaintext
N = 10
arr[10] = { 7, 4, 9, 11, 2, 24, -5, 17, 1, 8 }
Ans =
arr[10] = { 8, 7, 4, 9, 11, 2, 24, -5, 17, 1}
```
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/237/original/upload_011e736ec97da2de5bb921eb120f38d3.png?1695917062)
---
# Question
Right shift the given array
arr[] = {10, 20, 30, 40, 50, 60}
# Choices
- [ ] 60, 50, 40, 30, 20, 10
- [ ] 0, 10, 20, 30, 40, 50, 60
- [x] 60, 10, 20, 30, 40, 50
---
## Right Shift of An Array Idea and Code
## Idea
1. Store last element of original array in a temp variable for future use (`temp = arr[n - 1]`)
2. Traverse from end to first index and do
`arr[i] = arr[i - 1]`
3. Till here all indexes are updated with their new value except 0th index. Finally do
`arr[0] = temp`
## Pseudocode
```java
static int[] rotateByone(int arr[]){
int n = arr.length
int temp = arr[n - 1]
for(int i = n - 1; i >= 1; i--){
arr[i] = arr[i - 1]
}
arr[0] = temp;
return ans;
}
```
---
## Drawbacks of Arrays
Once array size is fixed, it cannot be changed.
If we want to change, we need to create a new array.
int[] ar=new int[4];
This can only store 4 elements, if we want to store 1 more element we cannot update the size. We have to create a new array only.
---
### Arraylist
#### Definition
ArrayList is a class that provides a resizable array implementation that is similar to an ordinary array, but with the added benefit of being able to resize dynamically as elements are added or removed. An ArrayList can store objects of any type, including primitives.
#### Syntax
The general syntax for creating an ArrayList in Java is as follows:
```java
ArrayList<DataType> listName = new ArrayList<DataType>();
```
where -
* **DataType** is the data type of the elements that will be stored in the list (e.g. Integer, String, Object).
* **listName** is the name given to the ArrayList object.
**Note:** There is no need to mention size in Arraylist, an empty Arraylist is created.
#### Example
Here's an example that creates an ArrayList of integers and adds the values 10, 20, 30, and 50 to it:
```java
// Create an ArrayList of integers
ArrayList<Integer> al = new ArrayList<>(); // size = 0
// Add integers to the list
al.add(10); // size = 1
al.add(20); // size = 2
al.add(30); // size = 3
al.add(50); // size = 4
```
#### Some Methods in Arraylist
* **Adding an element at the end** -
We can add an element at the end of Arraylist using the add(value) method:
```java
al.add(10)
```
**Task:** Find out how to add a new value at a particluar index in an ArrayList.
* **Total elements** -
We can get the size of the Arraylist using the size() method:
```java
int n = al.size(); // Returns the number of elements in the list
```
* **Access ith index element of an Arraylist** -
We can access ith index element of an Arraylist using the get(index) method:
```java
int element = al.get(2); // Returns the element at second index
```
---
# Question
```java
ArrayList<Integer> al = new ArrayList<>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
System.out.print(al.get(2));
```
# Choices
- [ ] 10
- [ ] 20
- [x] 30
- [ ] 40
- [ ] Error
---
### Explanation:
We first created an empty arraylist al. We then added 10, 20, 30 & 40 to it, the list becomes al = [10, 20, 30, 40]. The element at 2nd index is 30. Hence, answer is 30.
---
# Question
```java
ArrayList<Integer> al = new ArrayList<>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
System.out.print(al.get(4));
```
# Choices
- [ ] 40
- [ ] 20
- [x] Error
- [ ] 10
---
### Explanation:
We first created an empty arraylist al. We then added 10, 20, 30 & 40 to it, the list becomes al = [10, 20, 30, 40]. The size of the array is 4 with indexes from 0 - 3. There is no index 4. Hence, the code gives an error.
---
## ArrayList
* **Update existing element** -
We can update the existing element of an Arraylist using the set(index, value) method:
```java
// myList = [10, 20, 30, 50]
myList.set(2, 40); // Updates the element at second index with value 40
// updated myList = [10, 20, 40, 50]
myList.set(6, 60); // Gives error because index 6 does not exist
```
* **Remove an element** -
We can remove an element from the Arraylist using the remove(index) method:
```java
// myList = [10, 20, 40, 50]
myList.remove(2); // Removes the element at 2nd index from array
// updated myList = [10, 40, 50]
```
* **Sort the arraylist** -
We can sort the Arraylist using the Collections.sort(arraylist_name) method:
```java
// myList = [10, 20, 40, 50]
myList.remove(2); // Removes the element at 2nd index from array
// updated myList = [10, 40, 50]
```
**Note:** Here is the [link](https://www.interviewbit.com/snippet/aadadab483cbc4a05b04/) to example code snippet for practice.
---
# Question
What will be the output of the following code?
```java
public static void main(String[] args) {
ArrayList<Integer> ar = new ArrayList<>();
ar.add(1);
ar.add(2);
ar.add(3);
ar.set(1, 5);
ar.set(2, ar.get(0) + ar.get(1));
System.out.println(ar);
}
```
# Choices
- [ ] [1, 5, 3]
- [x] [1, 7, 3]
- [ ] [1, 5, 6]
- [ ] [1, 6, 3]
---
# Question
Predict the output
```java
public static void main(String[] args) {
ArrayList<Integer> ar = new ArrayList<>();
ar.add(-5);
ar.add(20);
ar.add(19);
ar.add(50)
ar.remove(1);
System.out.println(ar);
}
```
# Choices
- [x] [-5, 19, 20]
- [ ] [20, 19, 50]
- [ ] [-5, 20, 50]
- [ ] [-5, 20, 19, 50]
---
# Question
What will be the output?
```java
public static void main(String[] args) {
ArrayList<Integer> ar = new ArrayList<>();
ar.add(5);
ar.add(2);
ar.add(9);
ar.add(1);
Collections.sort(ar);
System.out.println(ar);
}
```
# Choices
- [ ] [5, 2, 9, 1]
- [ ] [9, 5, 2, 1]
- [x] [1, 2, 5, 9]
- [ ] [2, 1, 5, 9]
---
#### Problem Statement
Write a function which takes arrayList as input and update all values by 1
#### Example 1
```java
temp : [20, 15, 8, 25, 21]
ans : [21, 16, 9, 26, 22]
```
#### Pseudo Code:
```java
static ArrayList<Integer> increaseByOne(ArrayList<Integer> al){
//iterate over the ArrayList
int n = al.size();
for(int i = 0; i < n; i++){
//access ith index element : al.get(i)
int num = al.get(i);
al.set(i, num + 1);
}
return al;
}
```
---
#### Problem Statement
Given an ArrayList of integers, return all the even numbers in the ArrayList.
#### Example 1
```java
Input = 10 13 7 14 16 19 22 9 11
Output = 10 14 16 22
```
#### Example 2
```java
Input = 4 9 1 10 22 21 45
Output = 4 10 22
```
#### Solution
Iterate on the arrayList and check if element is even. If yes add it to ans arrayList.
#### Pseudocode
```java
public static ArrayList<Integer> getEvenNumbers(ArrayList<Integer> list) {
ArrayList<Integer> evenNumbers = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
if (num % 2 == 0) {
evenNumbers.add(num);
}
}
return evenNumbers;
}
```

View File

@@ -0,0 +1,663 @@
# 2D Array-1
---
## Agenda
1. Intro to 2D Arrays
2. Indexing and taking Input
3. Print matrix row by row and column by column
4. print matrix in wave form
5. Max of matrix.
6. Max of every row
---
### Introduction
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/238/original/upload_0da90fb446b2ffb5aa02c30693708136.png?1695918134)
Two-dimensional arrays can be defined as arrays within an array. 2D arrays is a collection of 1d Arrays.
#### Syntax:
```java
datatype name[][] = new datatype[rows][cols]
```
>**Note:** When we create 2D matrix by int default all values are equal to 0.
---
# Question
What is N representing in the line given below?
int[][] mat = new int[N][M];
# Choices
- [ ] Number of Column
- [x] Number of Row
- [ ] Total Element
---
# Question
What is M representing in the line given below?
int[][] mat = new int[N][M];
# Choices
- [x] Number of Column
- [ ] Number of Row
- [ ] Total Element
---
# Question
How to create a matrix with 2 rows and 5 columns?
# Choices
- [x] int[][] mat = new int[2] [5];
- [ ] int[] mat = new int[2] [5];
- [ ] int[][] mat = new int[5] [2];
---
# Question
How to create a matrix with 5 columns and 7 rows?
# Choices
- [x] int mat[ ] [ ] = new int[7] [5];
- [ ] int mat[ ] = new int[5] [7];
- [ ] int mat[ ] [ ] = new int[5] [7];
---
# Question
How to create a matrix with size M * N having M = 5 and N = 7
# Choices
- [ ] int mat[ ] [ ] = new int[7] [5];
- [ ] int mat[ ] = new int[5] [7];
- [x] int mat[ ] [ ] = new int[5] [7];
---
### Indexing and Properties:
* We can access ith row and jth column of matrix `mat[][]` by:
mat[i][j]
![reference link](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/252/original/example.jpeg?1682880236)
* If we iterate on a row, column changes and if we iterate on a column, row changes. For example, in above figure we can see that if we iterate on ith row, column number changes from `[0,M - 1]`.
* Similarly, in above figure we can see that if we iterate on jth row, row number changes from `[0,N - 1]`.
* In a matrix `mat[][]`, mat.length will be equal to total number of rows in a matrix and `mat[0].length` will be equal to total number of columns.
**Number of rows =** array.length
**Number of columns =** array[0].length
![reference link](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/254/original/example.jpeg?1682880551)
---
# Question
What will be the index of top left cell in a given matrix, mat of size N * M?
# Choices
- [ ] mat[0][M]
- [x] mat[0][0]
- [ ] mat[top][left]
- [ ] mat[N][0]
---
# Question
What will be the index of top right cell in a given matrix, mat of size N * M?
# Choices
- [x] mat[0][M-1]
- [ ] mat[N - 1][0]
- [ ] mat[N][0]
- [ ] mat[bottom][left]
---
# Question
What will be the index of bottom right cell in a given matrix, mat of size N * M?
# Choices
- [ ] mat[N - 1][0]
- [x] mat[N - 1][M - 1]
- [ ] mat[N][M]
- [ ] mat[bottom][right]
---
# Question
What will be the index of bottom left cell in a given matrix, mat of size N * M?
# Choices
- [x] mat[N - 1][0]
- [ ] mat[N - 1][M - 1]
- [ ] mat[N][M]
- [ ] mat[bottom][right]
---
### Taking input from user
Create a matrix having N rows and M columns fill the
matrix by taking input from the user
**Input**: rows = 3, columns = 4
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/239/original/upload_d4a27e7308a98fb1cc45a21dccceb859.png?1695918646)
**Code:**
```java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Enter the number of rows
int N = scanner.nextInt();
// Enter the number of columns
int M = scanner.nextInt();
int[][] matrix = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}
```
---
# Question
Print the 0th index row of the given matrix.
```plaintext
1 2 3 4
5 6 7 8
9 10 11 12
```
# Choices
- [x] 1 2 3 4
- [ ] 1 5 9
- [ ] 1 2 3 4 5 6 7 8 9 10 11 12
---
### Printing 0th Row
Given a matrix, you are required to print its 0th row.
#### Observation
To print the 0th row of the matrix, we can directly access the elements in the 0th row and print them.
#### Example
**mat :**
| index | 0 | 1 | 2 | 3 |
| ----- | --- | --- | --- | --- |
| 0 | 1 | 2 | 3 | 4 |
| 1 | 5 | 6 | 7 | 8 |
| 2 | 9 | 10 | 11 | 12 |
The 0th row of the matrix would be: **1 2 3 4**
#### Pseudocode
```java
void printZeroRow(int mat[][]) {
int n = mat.length;
for (int c = 0; c < n; c++) // columns
{
System.out.print(mat[0][c] + " ");
}
}
```
---
### Print Matrix Row by Row and Column by Column
Given a matrix, print every row in new line.
#### Example
**mat :**
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
| 0 | 1 | 2 | 3 | 4 |
| 1 | 5 | 6 | 7 | 8 |
| 2 | 9 | 10 | 11 | 12 |
**Output :**
```plaintext
1 2 3 4
5 6 7 8
9 10 11 12
```
#### Code
```java
void printmat(int mat[][]){
int n = mat.length;
int m = mat[0].length;
for(int r = 0; r < n; r++)//rows
{
for(int c = 0; c < m; c++) //columns
{
System.out.print(mat[r][c] + " ");
}
System.out.println();
}
}
```
---
### Printing Row in wave form
Given a matrix, print rows and column in wave form.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/240/original/upload_fc79bae5e81f6eb0d3634e7a65bb87a3.png?1695918883)
#### Observation
First we will rum loop for rows from index 0 to n-1 where n is the number of rows. Inside this loop we will run another loop for columns from 0 to m-1, where m is total number of columns. Inside this loop we will print the value at row i and column j.
#### Example 1
**mat :**
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
| 0 | 21 | 41 | 17 | 9 |
| 1 | 11 | 14 | 24 | 30 |
| 2 | 29 | 7 | 35 | 16 |
| 3 | 32 | 50 | 6 | 10 |
| 4 | 15 | 18 | 49 | 4 |
**Output :**
```plaintext
21 41 17 30 24 14 11 29 7 35 16 10 6 50 32 15 18 49 4
```
#### Observation
* For even rows we will traverse columns from 0 to m - 1 index.
* For odd rows we will traverse columns from m - 1 to 0 index.
#### Pseudocode
```java
void printWaveArray(int mat[][]){
int n = mat.length;
int m = mat[0].length;
for(int r = 0; r < n; r++)//rows
{
if(r % 2 == 0){
for(int c = 0; c < m; c++) //columns
{
System.out.print(mat[r][c] + " ");
}
}
else{
for(int c = m - 1; c >= 0; c--) //columns
{
System.out.print(mat[r][c] + " ");
}
}
}
}
```
---
# Question
Print the 0th index column of the given matrix.
```plaintext
1 2 3 4
5 6 7 8
9 10 11 12
```
# Choices
- [ ] 1 2 3 4
- [x] 1 5 9
- [ ] 1 2 3 4 5 6 7 8 9 10 11 12
---
### Print 0th column
Given a matrix, print 0th column.
#### Example
**mat :**
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
| 0 | 1 | 2 | 3 | 4 |
| 1 | 5 | 6 | 7 | 8 |
| 2 | 9 | 10 | 11 | 12 |
The 0th col of the matrix would be: **1 5 9**
#### Observation
We will run a single loop for i for rows from index 0 to n-1, where n is total number of rows and will print `matrix[i][0]`.
#### Pseudocode
```java
void printZeroCol(int mat[][]){
int n = mat.length;
int m = mat[0].length;
for(int r = 0; r < n; r++)//rows
{
System.out.print(mat[r][0] + " ");
}
}
```
---
### Print every column
Given a matrix, print every column in new line.
#### Exmaple 1
```java
mat[4][3] = {
{21,16,17,14},rows
{7,8,10,1},
{6,11,13,21}
}
Ans = {
{21, 7, 6}
{16, 8, 11}
{17, 10, 13}
{14, 1, 21}
}
```
| 21 | 16 | 17 | 14 |
|:---:|:---:|:---:|:---:|
| 7 | 8 | 10 | 1 |
| 6 | 11 | 13 | 21 |
#### Observation
First we will rum loop for columns from index 0 to m - 1 where m is the number of columns. Inside this loop we will run another loop for rows from 0 to n - 1, where n is thw total number of columns. Inside this loop we will print the value at row i and column j.
#### Pseudocode
```java
void printmat(int mat[][]){
int n = mat.length;
int m = mat[0].length;
for(int c = 0; c < m; c++)//rows
{
for(int r = 0; c < n; c++) //columns
{
System.out.print(mat[r][c] + " ");
}
System.out.println();
}
}
```
---
### Printing Column in Wave Form
Given a matrix, you are required to print its elements in wave form by columns.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/242/original/upload_8373f3d396acc9e8c1a50c98dd893f15.png?1695919265)
#### Observation
To print the matrix in wave form by columns, we can iterate through the columns of the matrix. For even columns, we start from the top and move downward; for odd columns, we start from the bottom and move upward. This way, we print the elements in a zigzag pattern along the columns.
#### Example
Consider the following matrix:
**mat :**
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
| 0 | 21 | 16 | 17 | 14 |
| 1 | 7 | 8 | 10 | 1 |
| 2 | 6 | 11 | 13 | 21 |
| 3 | 32 | 50 | 6 | 10 |
| 4 | 15 | 18 | 49 | 4 |
The elements in wave form by columns would be: `21 7 6 32 15 18 50 11 8 16 17 10 13 6 49`.
#### Pseudocode
```java
void printWaveArrayByColumn(int mat[][]) {
int n = mat.length;
int m = mat[0].length;
for (int c = 0; c < m; c++){ // columns
if (c % 2 == 0) {
for (int r = 0; r < n; r++){ // rows
print(mat[r][c] + " ");
}
} else {
for (int r = n - 1; r >= 0; r--){ // rows
print(mat[r][c] + " ");
}
}
}
}
```
---
### Max of matrix
Given a 2D Array A[][], return max element from this matrix.
### Example:
**mat :**
| index | 0 | 1 | 2 | 3 |
|:-----:|:---:|:---:|:---:|:---:|
| 0 | 12 | 65 | 89 | 74 |
| 1 | 22 | 44 | 12 | 30 |
| 2 | 10 | 12 | 97 | 19 |
**Output:**
Max element of matrix is 97
### Idea:
1. Iterate on every element of row and column.
2. compare mat[i][j] with max element.
3. return max element.
### Psuedo Code:
```java
public class Solution {
public int solve(int[][] A) {
int max = Integer.MIN_VALUE;
for(int i = 0; i < A.length; i++) {
for(int j = 0; j < A[0].length; j++) {
if(max < A[i][j]) {
max = A[i][j];
}
}
}
return max;
}
}
```
---
### Max of Every Row
Given a matrix and row number, return an array containing max of all elements in that row.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/243/original/upload_72f24410dd46ecfdc448d4bb76ca56bf.png?1695919503)
#### Example 1
**mat :**
| index | 0 | 1 | 2 | 3 | max |
|:-----:|:---:|:---:|:---:|:---:|:---:|
| 0 | 21 | 16 | 17 | 14 | 21 |
| 1 | 7 | 8 | 10 | 1 | 10 |
| 2 | 6 | 11 | 13 | 21 | 21 |
| 3 | 32 | 50 | 6 | 10 | 50 |
| 4 | 15 | 18 | 49 | 4 | 49 |
**ans :**
| index | 0 | 1 | 2 | 3 | 4 |
|:-----:|:---:|:---:|:---:|:---:|:---:|
| ans | 21 | 10 | 21 | 50 | 49 |
---
# Question
What will be the max of every row for the given matrix?
```plaintext
1 2 3 13 4
5 6 17 8 9
19 0 1 2 21
```
# Choices
- [ ] 15 19
- [ ] 4 9 21
- [x] 13 17 21
---
# Question
What should be the size of array to store max in every row for a matrix of size N * m
# Choices
- [ ] N + M
- [x] N
- [ ] M
- [ ] N * M
---
#### Observation
Size of ans array = total no of Rows
1. Create ans array
2. Iterate on every row and find max
3. Store the max of ith row at ans[i]
Dry Run wrt Above Example:
| i | Initial MAX | Iterate on ith row: j -> 0 to m-1 | Max in Row | ans[i] = max |
|:---:|:-----------:|:---------------------------------:|:----------:|:------------:|
| 0 | - INF | Iterate on 0th row: j -> 0 to m-1 | 21 | ans[0] = 21 |
| 1 | -INF | Iterate on 1st row: j -> 0 to m-1 | 10 | ans[1] = 10 |
| 2 | -INF | Iterate on 2nd row: j -> 0 to m-1 | 21 | ans[2] = 21 |
| 3 | -INF | Iterate on 3rd row: j -> 0 to m-1 | 50 | ans[3] = 50 |
| 4 | -INF | Iterate on 4th row: j -> 0 to m-1 | 49 | ans[4] = 49 |
#### Pseudocode
```java
int prinRowMax(int mat[][], int r){
int n = mat.length;
int m = mat[0].length;
int[] ans = new int[n];
int sum = 0;
for(int i = 0; i < n; i++)//rows
{
int max = Integer.MIN_VALUE;
for(int j = 0; j < m; j++){
if(mat[i][j] > max)
{
max = mat[i][j];
}
}
ans[i] = max;
}
return ans;
}
```

View File

@@ -0,0 +1,745 @@
# 2D arrays 2
---
# Agenda
- Revision
- Transpose
- Reverse every row in the given matrix
- Rotate by 90
- Intro to 2D ArrayList
- Syntax
- Functions
- Return even elements from everyrow.
---
# Question
How do you declare an int 2D array in Java?
# Choices
- [x] int[][] mat = new int[rows][cols]
- [ ] int[][] mat = new int[cols][rows]
- [ ] int[][] mat = new int[rows][rows]
- [ ] int[][] mat = new int[cols][cols]
---
# Question
How do you get the no. of rows in a 2D matrix mat?
# Choices
- [x] mat.length
- [ ] mat.length()
- [ ] mat.size
- [ ] mat.size()
---
# Question
How do you get the number of columns in a 2D matrix for row index x?
# Choices
- [ ] mat[x].length()
- [x] mat[x].length
- [ ] mat[x].size
- [ ] mat[x].size()
---
# Question
```java
int[][] nums = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
1 2 3
4 5 6
7 8 9
System.out.println(nums[1][2]);
```
# Choices
- [ ] 4
- [ ] 5
- [x] 6
- [ ] ArrayIndexOutOfBoundsException
---
### Transpose
#### Given an rectangular matrix return the transpose of the matrix
> Rectangular matrix is matrix having number of rows not equal to number of columns
> Transpose of the matrix is new matrix in which the row of certain number in old matrix is converted to column of that particular number in new matrix like -
> >Row 1 of old matrix ---> column 1 of new matrix
> > Row 2 of old matrix ---> column 2 of new matrix
> > and so on...
#### Example 1
`mat[3][5]`
| 1 | 2 | 3 | 4 | 5 |
|:---:|:---:|:---:|:---:|:---:|
| 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 |
#### Explaination and solution
Intial matrix :-
`mat[3][5]`
| 1 | 2 | 3 | 4 | 5 |
|:---:|:---:|:---:|:---:|:---:|
| 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 |
Step 1 :- convert row 1 of intial to column 1
| 1 |
|:---:|
| 2 |
| 3 |
| 4 |
| 5 |
Step 2:- convert row 2 of intial to column 2
| 1 | 6 |
|:---:|:---:|
| 2 | 7 |
| 3 | 8 |
| 4 | 9 |
| 5 | 10 |
Step 3 :- convert row 3 of intial to column 3
| 1 | 6 | 11 |
|:---:|:---:|:---:|
| 2 | 7 | 12 |
| 3 | 8 | 13 |
| 4 | 9 | 14 |
| 5 | 10 | 15 |
Transpose of matrix is :-
| 1 | 6 | 11 |
|:---:|:---:|:---:|
| 2 | 7 | 12 |
| 3 | 8 | 13 |
| 4 | 9 | 14 |
| 5 | 10 | 15 |
#### Example 2
`mat[3][4]`
| 1 | 2 | 3 | 4 |
|:---:|:---:|:---:|:---:|
| 6 | 7 | 8 | 9 |
| 11 | 12 | 13 | 14 |
#### Explanation and solution
Transpose of matrix is :-
| 1 | 6 | 11 |
|:---:|:---:|:---:|
| 2 | 7 | 12 |
| 3 | 8 | 13 |
| 4 | 9 | 14 |
---
# Question
For a rectangular matrix, can we have the transpose in the same matrix?
# Choices
- [ ] Yes
- [x] No we need new matrix
- [ ] Maybe
---
# Question
If dimensions of a matrix A is ( N x M ), and it is declared as int mat[][] = new int[N][M];
How will the transpose be declared?
# Choices
- [ ] int transpose[] = new int[N][M];
- [ ] int transpose[][] = new int[N][M];
- [x] int transpose[][] = new int[M][N];
---
# Question
What will be the transpose of this matrix?
```java
10, 20, 30
14, 15, 18
```
# Choices
- [x] 10,14<br>20,15<br>30,18
- [ ] 10,20<br>30,14<br>15,18
- [ ] I am confused about what is transpose :(
---
#### Observations :-
* if we observe example 1
* Element at row 0 and column 1 in matrix mat becomes Element at column 0 and row 1 in transpose.
* similarly mat[2][3] ---> newMat[3][2]
* mat[1][4] ---> newMat[4][1]
* Is there any pattern between the position of element in intial matrix and tranpose matrix ?
* On observing we can say that :-
<div class="alert alert-block alert-warning">
Transpose[i][j] = Mat[j][i]
</div>
<div class="alert alert-block alert-warning">
**If dimensions of Mat are MxN then dimensions of transpose would be NxM**
</div>
#### Code
```java
static int[][] transposeMatrix(int[][] Mat) {
int m = Mat.length;
int n = Mat[0].length;
int[][] ans = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans[j][i] = Mat[i][j];
}
}
return ans;
}
```
---
### Reverse every row
Given a matrix reverse every row of matrix and return the same matrix
#### Example 1
`mat[3][5]`
| 3 | 2 | 6 | 1 | 9 |
|:---:|:---:|:---:|:---:|:---:|
| 14 | 18 | 2 | 4 | 10 |
| 5 | 6 | 3 | 9 | 8 |
#### Explanation and solution
Initial matrix :-
`mat[3][5]`
| 3 | 2 | 6 | 1 | 9 |
|:---:|:---:|:---:|:---:|:---:|
| 14 | 18 | 2 | 4 | 10 |
| 5 | 6 | 3 | 9 | 8 |
Step 1 :- Reverse row 1 of matrix
| 9 | 1 | 6 | 2 | 3 |
|:---:|:---:|:---:|:---:|:---:|
| 14 | 18 | 2 | 4 | 10 |
| 5 | 6 | 3 | 9 | 8 |
Step 2 :- Reverse row 2 of matrix
| 9 | 1 | 6 | 2 | 3 |
|:---:|:---:|:---:|:---:|:---:|
| 10 | 4 | 2 | 18 | 14 |
| 5 | 6 | 3 | 9 | 8 |
Step 4 :- Reverse row 3 of matrix
| 9 | 1 | 6 | 2 | 3 |
|:---:|:---:|:---:|:---:|:---:|
| 10 | 4 | 2 | 18 | 14 |
| 8 | 9 | 3 | 6 | 5 |
#### Example 2
`mat[3][4]`
| 1 | 2 | 3 | 4 |
|:---:|:---:|:---:|:---:|
| 6 | 7 | 8 | 9 |
| 11 | 12 | 13 | 14 |
#### Explanation and solution
| 4 | 3 | 2 | 1 |
|:---:|:---:|:---:|:---:|
| 9 | 8 | 7 | 6 |
| 14 | 13 | 12 | 11 |
---
# Question
What will be result if we reverse each row of this matrix?
```java
10, 20, 30
14, 15, 18
```
# Choices
- [ ] 10, 20, 30<br>14, 15, 18
- [ ] 20, 10, 30<br>14, 15, 18
- [ ] 10, 20, 30<br>18, 15, 14
- [x] 30, 20, 10<br>18, 15, 14
---
#### Approach
* Our approach should be to traverse each row reverse it.
* But how to reverse a row ?
**Reversing a single row:-**
* First element of the row is swapped with the last element of the row. Similarly, the second element of the array is swapped with the second last element of the array and so on.
* ![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/143/original/ex12.png?1681962057)
* But if keep on swapping we would end up with intial configuartion again
* So **we swap till e>s**
This way at the end of traversal, we will have the entire row reversed.
### Code
```java
static int[][] reverseEachRow(int[][] Mat) {
int m = Mat[0].length;
int n = Mat.length;
for (int i = 0; i < n; i++) {
int s = 0;
int e = m - 1;
while (e > s) {
// Swap elements in the current row
int temp = Mat[i][s];
Mat[i][s] = Mat[i][e];
Mat[i][e] = temp;
e--;
s++;
}
}
return Mat;
}
```
---
### Rotate by 90
Given a matrix rotate it by 90<sup>o</sup> in clockwise direction ?
#### Testcase
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/144/original/dvfm.png?1681962700)
#### Solution
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/145/original/dvfm1.png?1681962816)
#### Example
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/146/original/tescl.png?1681962988)
#### Approach
* **First we take transpose of matrix. On taking transpose:-**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/147/original/rtt.png?1681963164)
* **Reverse each row of transpose to get the solution**.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/148/original/kldklf.png?1681963261)
**Code**
```java
import java.util.*;
public class Main {
static int[][] transposeMatrix(int Mat[][]) {
int m = Mat.length;
int n = Mat[0].length;
int transposeMat[][] = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transposeMat[j][i] = Mat[i][j];
}
}
return transposeMat;
}
static int[][] reverseEachRow(int Mat[][]) {
int m = Mat[0].length;
int n = Mat.length;
for (int i = 0; i < n; i++) {
int s = 0;
int e = m - 1;
while (e > s) {
int temp = Mat[i][s];
Mat[i][s] = Mat[i][e];
Mat[i][e] = temp;
e--;
s++;
}
}
return Mat;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Mat[][] = new int[3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
Mat[i][j] = sc.nextInt();
}
}
int transpose[][] = transposeMatrix(Mat);
int matRotatedClockwise90Degree[][] = reverseEachRow(transpose);
}
}
```
---
### Syntax
```java
ArrayList<Integer> l = new ArrayList<>();
```
Here each element in l is an integer.
### Properties
#### 1. add(element)
It is used to insert elements in ArrayList.
```java
l.add(20);
l.add(30);
l.add(40);
l.add(35);
```
ArrayList :-
| 20 | 30 | 40 | 35 |
|:---:|:---:|:---:|:---:|
#### 2. set(element)
It is used to update values at particular index in ArrayList.
```java
l.set(1, 80);
l.set(0, 90);
```
ArrayList :-
| 90 | 80 | 40 | 35 |
|:---:|:---:|:---:|:---:|
#### 3. get(index)
It is used to get values at particular index in ArrayList.
```java
print(l.get(2));
print(l.get(3));
```
Output :
```plaintext
40
50
```
#### 4. remove(index)
It is used to remove value at particular index in ArrayList.
```plaintext
l.remove(2);
```
ArrayList :-
| 90 | 80 | 35 |
|:---:|:---:|:---:|
**Note:**
```java
ArrayList<Integer> l = new ArrayList<>();
```
Each element in this ArrayList is of **Integer** type.
---
### 2D ArrayList
ArrayList of ArrayLists
### Syntax for 2D ArrayList
```java
ArrayList<ArrayList< Datatype>> a = new ArrayList<>();
```
Each element in this 2D ArrayList is of **ArrayList< Datatype>**
### How to add elememts in 2D ArrayList
```java
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
```
Here each Arraylist in arr is of type **ArrayList<Integer>**.
#### Pseudocode
```java
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
ArrayList<Integer> d1 = new ArrayList<>();
d1.add(10);
d1.add(20);
d1.add(30);
d1.add(40);
ArrayList<Integer> d2 = new ArrayList<>();
d2.add(-1);
d2.add(4);
d2.add(8);
ArrayList<Integer> d3 = new ArrayList<>();
d1.add(50);
d1.add(60);
d1.add(70);
d1.add(80);
```
Output:
```plaintext
{
{10,20,30,40},
arr : {-1,4,8},
{50,60,70,80}
}
```
### How to get elememts in 2D ArrayList
>Note: arr.get(i) = element at ith index.
#### Pseudocode
```java
System.out.println(arr.get(1));
System.out.println(arr.get(2));
```
Output:
```plaintext
{-1,4,8}
{50,60,70,80}
```
### How to access element from ith ArrayList at jth index
>Note: arr.get(i).get(j) = element at ith ArrayList and jth index.
#### Pseudocode
```java
System.out.println(arr.get(0).get(0));
System.out.println(arr.get(1).get(2));
System.out.println(arr.get(2).get(1));
```
Output:
```plaintext
10
8
60
```
### How to return no. of elements in ArrayList
#### Pseudocode
```java
System.out.println(arr.size());
System.out.println(arr.get(0).size());
System.out.println(arr.get(1).size());
```
Output:
```plaintext
3
4
3
```
### How to modify elements in ArrayList
#### Pseudocode
```java
System.out.println(arr.get(0).set(0,14));
System.out.println(arr.get(1).set(2,-9));
System.out.println(arr.get(2).set(0,20));
```
Output:
```plaintext
{
{14,20,30,40},
arr : {-1,4,-9},
{20,60,70,80}
}
```
---
### Problem 1
Print 2D ArrayList.
#### Pseudocode
```java
void print(ArrayList< ArrayList< Integer>> arr) {
int n = arr.size(); // Get the number of rows in the ArrayList
// Iterate through each row
for (int i = 0; i < n; i++) {
// Get the number of columns in the current row
int m = arr.get(i).size();
// Iterate through each element in the current row
for (int j = 0; j < m; j++) {
System.out.print(arr.get(i).get(j) + " ");
}
System.out.println();
}
}
```
#### Dry run
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/618/original/upload_4c380c72302ab5955366f07e171e5d34.png?1695231151)
---
### Even numbers
Given a 2D ArrayList, return a 2D ArrayList which contains even number from every row.
#### Example 1
```java
arr = {
{3,10,2},
{2,7,6,9,4},
{18,20,11,6}
}
Ans = {
{10, 2}
{2,6,4}
{18,20,6}
}
```
#### Example 2
```java
arr = {
{3,6,2,9},
{2,4,8,10},
{3,9,7,15},
8,3,2,14,19},
}
Ans = {
{6,2}
{2,4,8,10}
{}
{8,2,14}
}
```
#### Observation
We will traverse every element in ArrayList and insert even numbers in output.
#### Pseudocode
```java
ArrayList<ArrayList<Integer>> even(ArrayList<>> arr){
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
int n = arr.size();
for(int i = 0; i < n; i++) {
ArrayList<Integer> l = new ArrayList<>();
int m = arr[i].get(i).size();
for(int j = 0; j < m; j++){
if( arr.get(i).get(j) % 2 == 0){
l.add(arr.get(i).get(j));
}
}
ans.add(l);
}
return ans;
}
```
---

View File

@@ -0,0 +1,720 @@
# If Else 1
---
## Agenda
* Contest Details
* Introduction to If
* If Examples
* If / Else examples
* If / Else if examples
**Some abbreviations that will be used in this class:**
* System.out.print - SOP
* System.out.println - SOPln
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
The following questions serve as an introduction to the topic.
**Q1.** Sravan loves drinking tea. But he is out of sugar. Sravan is asking his neighbour Karthik?
**A1.** Look at the following diagram:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/259/original/Screenshot_2023-10-04_at_2.25.30_PM.png?1696409763" alt= “” width ="500" height="200">
**Q2.** Eligibility criteria for voting.
---
# Question
Correct logic to check whether you are eligible to vote.
# Choices
- [ ] age > 180
- [ ] age != 17
- [ ] age == 18
- [x] age >= 18
---
# Explanation
Look at the following diagram.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/260/original/Screenshot_2023-10-04_at_2.27.12_PM.png?1696409843" alt= “” width ="400" height="200">
**Note:** Some students may ask why are we drawing diagrams. Just mention that it's easy to visualize.
---
**Q3.** Check person is senior citizen or not.
If age >= 65, then they can collect pension.
**A.** Look at the following diagram.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/261/original/Screenshot_2023-10-04_at_2.31.03_PM.png?1696410084" alt= “” width ="400" height="200">
**Q4.** Check whether person is suffering from fever or not.
**A.**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/262/original/Screenshot_2023-10-04_at_2.32.31_PM.png?1696410182" alt= “” width ="400" height="200">
### Syntax of If
**Idea:** When we want to do something when condition is True.
**Syntax:**
```
if (condition) {
// Statements we want to be executed
// if above condition is True.
}
```
**Imp point:** `condition` should be a boolean expression. A boolean expression is an expression whose value can only be true or false.
---
# Question
Which of the following is NOT a boolean expression?
# Choices
- [ ] true
- [ ] 4 == 5
- [x] 4 + 5
- [ ] 4 < 5
- [ ] false
---
1. Read a number and If person is eligible, print "eligible to vote".
Run the below code on IDE and explain.
```
public static void main() {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
if (age >= 18) {
System.out.print("Eligible to vote");
}
}
```
---
# Question
Which data type should be used to store temperature of a patient?
# Choices
- [ ] int
- [x] double
- [ ] boolean
- [ ] String
---
# Explanation
Explain with the following code:
```
psv main() {
Scanner sc = new Scanner(System.in);
double temp = sc.nextDouble();
if (temp >= 98.6) {
System.out.print("Go to doctor!");
}
}
```
---
# Question
Predict the output:
```
int a = 10;
if(a >= 10){
System.out.println("Yo");
}
System.out.println("Yo");
```
# Choices
- [ ] YoYo
- [x] Yo<br>Yo
- [ ] Error
---
# Question
Predict the output:
```
int a = 18,b = 16;
if(a >= 18){
System.out.println("a is major");
}
if(b >= 18){
System.out.println("b is major");
}
System.out.println("Blab");
```
# Choices
- [ ] a is major<br>b is major<br>Blab
- [ ] a is major<br>b is major
- [ ] b is major<br>Blab
- [x] a is major<br>Blab
---
# Question
Predict the output:
```
int a = 50,b = 50;
if(a >= 50){
System.out.println("a scored half");
a = a + 1;
}
if(b >= 50){
System.out.println("b scored half");
b = b + 1;
}
System.out.print(a + b);
```
# Choices
- [ ] a scored half<br>101
- [ ] a scored half<br>b scored half<br>101
- [ ] b scored half<br>102
- [x] a scored half<br>b scored half<br>102
---
# Question
Predict the output:
```
if(5 > 4) {
System.out.println("First if");
}
if(10 >= 6) {
System.out.println("Second if");
}
```
# Choices
- [x] First if<br>Second if
- [ ] First if
- [ ] Second if
- [ ] Error
---
# Question
Predict the output:
```
if(5 > 10) {
System.out.println("First if");
}
if(10 >= 16) {
System.out.println("Second if");
}
System.out.println("Oops!! Nothing will get printed..");
```
# Choices
- [ ] First if
- [ ] Second if
- [ ] First if<br>Second if<br>Oops!! Nothing will get printed..
- [x] Oops!! Nothing will get printed..
---
# Question
Predict the output:
```
if(true) {
System.out.println("1");
}
if(true) {
System.out.println("2");
}
if(true) {
System.out.println("3");
}
```
# Choices
- [x] 1<br>2<br>3
- [ ] 1
- [ ] 2
- [ ] Error
---
Check if someone has normal temperature: Normal temp = [98.0 to 98.9]
Ex:
* 98.1 -> Normal temperature
* 99 -> Not normal temperature
* 97.9 -> Not normal temperature
Explain -> _______98.0________98.9_______
* 96.8 -> Not normal temperature
* 98.5 -> Normal temperature
**Q.** What is the Java code for this?
```
Scanner sc = new Scanner(System.in);
double temp = sc.nextDouble();
if (temp >= 98.0 && temp >= 98.9) {
System.out.println("Normal temperature");
}
```
**Note:** Logical operators are used to combine conditions.
---
Now, we want to do something or the other accordingly when the condition is true or false.
### Syntax of If / Else
```
if (condition) {
// Statements to run, when above condition True
}
else {
// Statements to run, when above condition False
}
```
### Flow 1
```
if (condition) {
Statement 1
}else{
Statement 2
}
```
Q1: Condition True: Statement 1
Q2: Condition False: Statement 2
### Flow 2
```
Statement 1
if (condition) {
Statement 2
}else{
Statement 3
}
Statement 4
```
**Q.** What all statements will be executed?
**A.** Condition True: Statement 1, 2 4
Condition False: Statement 1, 3, 4
---
### Example 1
Read age of a person, check if person is at retirement age, or still have few years left to work. Retirement age is 65.
```
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
if (age > 65) {
System.out.println("Retired");
}else{
System.out.println("Few more years of service.");
}
```
---
# Question
Predict the output:
```
if(9 > 5){
System.out.println("If block");
}
else{
System.out.println("Else block");
}
```
# Choices
- [x] If block
- [ ] If block<br>Else block
- [ ] Error
---
# Question
Predict the output:
```
if(false){
System.out.println("Line 1");
} else {
System.out.println("Line 2");
}
```
# Choices
- [ ] Line 1
- [x] Line 2
- [ ] Line 1<br>Line 2
- [ ] Error
---
### Modulus Operator
Modulus operator (%) -> Gives remainder
```
System.out.println(17 % 4) -> Remainder = 1
System.out.println(24 % 2) -> Remainder = 0
System.out.println(97 % 2) -> Remainder = 1
System.out.println(82 % 2) -> Remainder = 0
```
Explain even and odd numbers.
**Even numbers:** Numbers which are divisible by 2.
Eg: 2, 4, 6, 8, 10, 12..
When we divide the number with 2, remainder = 0
**Odd numbers:** Numbers which are not divisible 2.
Eg: 1, 3, 5, 7, 9, 11..
When we divide the number with 2, remainder = 1
---
### Example 1
Read a number and check if number is odd or even.
```
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 2 == 0) {
System.out.println("Number is even");
}else{
System.out.println("Number is odd");
}
```
---
### Example 2
Check if a number is divisible by 5.
```
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 5 == 0) {
System.out.println("Number is divisible by 5");
}else{
System.out.println("Number is not divisible by 5");
}
```
---
### Example 3
Check if a number is divisible by 2 or 3.
```java
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 2 == 0 || a % 3 == 0) {
System.out.println("Number is divisible by 2 or 3");
}else{
System.out.println("Number is not divisible by 2 and 3 both");
}
```
# Question
Can we have if without an else block?
# Choices
- [x] Yup!!
- [ ] Nope!!
- [ ] Don't know
# Question
Can we have else without an if block?
# Choices
- [ ] Yup!!
- [x] Nooo!!
- [ ] Maybe
---
Read 2 numbers and print max of 2 numbers.
**Examples:**
```plaintext
a = 5 , b = 10
Max of a and b = 10
```
```plaintext
a = 15 , b = 10
Max of a and b = 15
```
```
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if (a > b) {
System.out.println(a);
}else{
System.out.println(b);
}
```
# Question
Predict the output:
For input: 45 45
```
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if(a > b){
System.out.print(a);
}
else{
System.out.print(b);
}
```
# Choices
- [ ] Error
- [ ] 45<br>45
- [x] 45
### Categorize Number
Given an integer n0, categorize it into positive, negative or zero.
Category:
n = 10: n > 0: print "positive number"
n = -27: n < 0: print "negative number"
n = 0: n == 0: print "zero"
Give some more examples.
Idea:
```
public static void main() {
Scanner sc = new Scanner(System.in);
int a = scn.nextInt();
if (a > 0) {
System.out.println("positive number");
}
if (a < 0) {
System.out.println("negative number");
}
if (a == 0) {
System.out.println("zero");
}
}
```
**Q.** Is the above logic correct?
**A.** Yes
Dry run the above code for some examples.
Explain the problem in the above approach.
It's the wastage of comparisions.
**Syntax:**
```
if (cond_1) {
// Statements if cond_1 is true
}
else if (cond_2) {
// Statements if cond_1 is false and cond_2 is true
}else{
// Statements if cond_1 is false and cond_2 is false
}
```
**Note:** "else" is optional.
### Flow
```
Statement 1
if (cond_1) {
Statement 2
}
else if (cond_2) {
Statement 3
}
else{
Statement 4
}
Statement 5
```
Explain the above flow according to below table.
| Conditions which are true | Statements executed |
|:-------------------------:|:-------------------:|
| 1 | 1 2 5 |
| 2 | 1 3 5 |
| All false | 1 4 5 |
| 1 2 | 1 2 4 |
**Note:** If a condition is true, it will execute and will come out of If/Else block and execute remaining statements.
**Note:** We can have multiple "else if()" blocks.
Back to Categorize number problem,
```
public static void main() {
Scanner sc = new Scanner(System.in);
int a = scn.nextInt();
if (a > 0) {
System.out.println("positive number");
}
else if (a < 0) {
System.out.println("negative number");
}
else{
System.out.println("zero");
}
}
```
### Example
Is the below code correct or not?
```
int a = 10;
else if (a > 5) {
System.out.println("Number is more than 5");
}
else{
System.out.println("Number is not more than 5");
}
```
Correct Answer: Compilation error.
We cannot write any `else if()` without `if()` block.
---
# Question
What will be the output of the following:
```
if(true) {
System.out.println("1");
}
else if(true) {
System.out.println("2");
}
else if(true) {
System.out.println("3");
}
```
# Choices
- [x] 1
- [ ] 1<br>2<br>3
- [ ] 2
- [ ] 3
---
# Question
Can there be an else if block without a if block
# Choices
- [ ] Yes
- [x] No
- [ ] Maybe
---
# Question
Can there be an else if block without an else block
# Choices
- [x] Yes
- [ ] No
- [ ] Maybe
---

View File

@@ -0,0 +1,666 @@
### If Else : 2
---
# Content
- Revision Quizzes
- Categorize triangle
- Max of three
- Fizz Buzz
- Nested If Else
- Categorize into positive, negative and zero
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
## Recap
**Some abbreviations that will be used in this class:**
* System.out.print - SOP
* System.out.println - SOPln
---
# Question
What will be the output of the following code?
```java
int a = 10,b = 10;
if(a >= 10 && b >= 10){
System.out.print(a+b);
}
```
# Choices
- [ ] 10
- [x] 20
- [ ] 30
- [ ] None
---
# Question
What will be the output of the following code?
```java
int a = 10;
int b = 10;
if( ++ a >= 12 && ++ b >= 12 ){
System.out.println("Hello");
}
System.out.println(a + b);
```
# Choices
- [ ] Hello<br>10
- [ ] 22
- [x] 21
- [ ] None
---
# Question
What will be the output of the following code?
```java
int a = 10;
int b = 10;
if( ++ a >= 11 || ++ b >= 12 ){
System.out.println("Hello");
}
System.out.println(a + b)
```
# Choices
- [ ] 20
- [ ] 22
- [x] Hello<br>21
- [ ] None
---
# Question
What will be the output of the following code?
```java
int a = 10;
int b = 10;
if( ++ a >= 12 || ++ b >= 12 ){
System.out.println("Hello");
}
System.out.println(a + b);
```
# Choices
- [ ] 20
- [ ] 21
- [x] 22
- [ ] None
---
# Question
What will be the output of the following code?
```java
int N = 5;
if(N > 2)
System.out.println("Yayay");
else
System.out.println("Blahblah!!");
```
# Choices
- [x] Yayay
- [ ] Blahblah!!
---
# Question
What will be the output of the following code?
```java
int N = 5;
if(N > 2)
System.out.println("Yayay");
System.out.println("Hmmmm");
else
System.out.println("Blahblah!!");
System.out.println("Blahblah!!");
```
# Choices
- [x] Error :(
- [ ] No Error, this code rocks! :D
- [ ] Yayay Hmmmm
- [ ] Blahblah!!
---
# Question
What will be the output of the following code?
```java
int marks = 80;
if(marks > 70) {
System.out.print("Distinction ");
System.out.print("Congrats ");
} else if(marks > 35) {
System.out.print("Pass ");
} else
System.out.print("Fail ");
System.out.print("Good luck");
```
# Choices
- [x] Distinction Congrats Good luck
- [ ] Good luck
- [ ] Error
- [ ] Distinction Congrats
---
# Categorize Triangles
Categorize triangle on the basis of the length of the sides
**Equilateral:** When the length of the all the sides are equal.
**Isosceles:** When the length of any two sides are equal.
**Scalene:** When the length of all sides are different.
Let `a`, `b`, `c` be the length of the three sides of a triangle. Given in each case they take some values, tell the category of the triangle. It is the given that the input values for a, b, c are positive integer values.
```plaintext
a = 20, b = 20, c = 20
-- Output = Equilaterial
```
```plaintext
a = 7, b = 12, c = 9
-- Output = Scalene
```
```plaintext
a = 5, b = 13, c = 5
-- Output = Isosceles
```
```plaintext
a = 12, b = 7, c = 7
-- Output = Isosceles
```
The equivalent code for implementing the above logic is as follows:
```java
if(a == b && b == c){
SOPln("Equilateral");
}
else if(a == b || b == c || a == c){
SOPln("Isosceles");
}
else{
SOPln("Scalene");
}
```
---
# Max of three
**Ques:** Given three numbers, print the maximum among them.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/724/original/upload_a249488f4da0204e8671e22d85267672.png?1693733958" alt= “” width ="700" height="600">
Note that `a`, `b`, `c` can take any integer values.
Stress on the point that `a`, `b`, `c` can also take equal values. The three test case demonstrates this point.
For example,
* a = 7, b = 20, c = 50 ==> max = 50
* a = 10, b = 9, c = 10 ==> max = 10
* a = 3, b = 3, c = 3 ==> max = 3
The equivalent code for implementing the above logic is as follows:
```java
if(a >= b && a >= c){
SOPln("a");
}
else if(b >= c){
SOPln("b");
}
else{
SOPln("c");
}
```
---
# Fizz-Buzz
**Ques:** Given a number,
* print "Fizz" if the number is divisible by 3.
* print "Buzz" if the number is divisible by 5.
* print "Fizz-Buzz" if the number is divisble by both 3 and 5.
For example,
* n = 39, O/p = Fizz
* n = 25, O/p = Buzz
* n = 15, O/p = Fizz-Buzz
* n = 13, O/p = `No output`
**How to implement this? **
The following code shows a **wrong implementation** of the above logic:
```java
if(n % 3 == 0){
SOPln("Fizz");
}
else if(n % 5 == 0){
SOPln("Buzz");
}
else{
SOPln("Fizz-Buzz");
}
```
The above code prints "Fizz-Buzz" for n = 11, but this is wrong as n is neither divisble by 3 nor 5. So there should have no output for this number.
**Another wrong implementation is as follows:**
```java
if(n % 3 == 0){
SOPln("Fizz");
}
else if(n % 5 == 0){
SOPln("Buzz");
}
else if(n % 3 == 0 && n % 5 == 0){
SOPln("Fizz-Buzz");
}
```
The above code prints "Fizz" for n = 15, but this is wrong as n is divisble by 3 and 5 both. So the correct output should be "Fizz-Buzz".
So finally, the **correct implementation** of this logic is as follows:
```java
if(n % 3 == 0 && n % 5 == 0){
SOPln("Fizz-Buzz");
}
else if(n % 3 == 0){
SOPln("Fizz");
}
else if(n % 5 == 0){
SOPln("Buzz");
}
```
---
# Nested If Else
**Syntax:**
```java
Statement 1
if(cond1){
Statement 2
if(cond2){
Statement 3
}
else{
Statement 4
}
Statement 5
}
else{
Statement 6
if(cond3){
Statement 7
}
else{
Statement 8
}
Statement 9
}
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/725/original/upload_a7f4d3e8fb808f6475963859c4aed00c.png?1693734037" alt= “” width ="400" height="400">
---
# Question
Predict the output of the following code?
```java
int a = 10, b = 15;
if(a > 8) {
if(a < b || b == 9) {
System.out.println("Hi");
}
else {
System.out.println("Bye");
}
}
else {
System.out.println("Good Bye");
}
```
# Choices
- [x] Hi
- [ ] Bye
- [ ] Good Bye
- [ ] None
---
# Question
Predict the output of the following code?
```java
int a = 10, b = 15;
if(a > 8) {
if(a == b || b < a) {
System.out.println("Hi");
}
else {
System.out.println("Bye");
}
}
else {
System.out.println("Got it");
}
```
# Choices
- [ ] Hi
- [x] Bye
- [ ] Got it
- [ ] None
---
# Question
Predict the output of the following code?
```java
if(true) {
if(true) {
if(false) {
System.out.println("Hey there");
}
}
else {
System.out.println("Hello");
}
}
else {
System.out.println(10 / 0);
}
```
# Choices
- [ ] Hey there
- [ ] Hello
- [x] No output
- [ ] Error
---
**Explanation:**
We are not getting an error because the inner if statement with the false condition is not executed due to the if condition being false. Therefore, the else block following it is also not executed. The program simply moves on to the next line, which is outside of any control structures and executes the statement `System.out.println("Hello");` as expected.
The else block following the outer if statement is also not executed since the condition of the outer if statement is true, and the program again moves to the next line and executes the statement `System.out.println("Hello");`
---
## Categorise the number
**Ques:** Given a number, classify it as follows:
* +ve and even
* +ve and odd
* -ve and even
* -ve and odd
## Example :
**Input:**
```java
public static void main(){
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
if(num > 0){
if(num % 2 == 0){
SOPln("Positive and even");
}
else{
SOPln("Positive and odd");
}
}
else{
if(num % 2 == 0){
SOPln("Negative and even");
}
else{
SOPln("Negative and odd");
}
}
}
```
---
## Scope of a Variable
It defines the point till where you can use the variable. You can only use a variable till the closing bracket of the block in which it was created.
**Example 1:**
```java=
public static void main(){
int x;
x = 5;
int y;
y = 20
}
```
Scope of variable `x`: Line 4 to 10
Scope of variable `y`: Line 7 to 10
**Example 2:**
```java=
public static void main(){
int x = 10;
if(x == 10){
int y = 5;
SOP(y);
}
int z = 9;
}
```
Scope of variable `x`: Line 3 to 10
Scope of variable `y`: Line 5 to 7
Scope of variable `z`: Line 8 to 10
**Example 3:**
```java=
public static void main(){
int a = 10;
{
a = 20;
}
SOP(a);
}
```
Scope of variable `a`: Line 2 to 8
Also the code will print 20 as the changes done in the variable values are not restricted to that block in which the change is done. But the life of the variable is restricted to the block in which it was created.
**Example 4:**
```java=
public static void main(){
int x = 10;
{
int y = 20;
SOP(x + " " + y);
}
{
SOP(x + " " + y); // This line will give error as y is not present in its scope
}
}
```
**Example 5:** Redefining variable error
```java=
public static void main(){
int a = 90;
{
int a = 7; // This line will give error as variable a is already defined in this scope
SOPln(a);
}
}
```
---
# Question
Predict the output of the following code:
```java
public static void main(String args[]) {
int x = 10;
{
int y = 20;
System.out.println(x + " " + y);
}
{
System.out.println(x + " " + y);
}
System.out.println(x + " " + y);
}
```
# Choices
- [x] Error
- [ ] 10 20<br>10 20<br>10 20
- [ ] 10 20 10 20 10 20
---
# Question
Predict the output of the following code:
```java
public static void main(){
int x = 10, y = 20;
{
SOP(x + " " + y);
}
{
x = 15;
SOPln(x + " " + y);
}
SOPln(x + " " + y);
}
```
# Choices
- [ ] 10 20<br>15 20<br>10 20
- [ ] Error
- [x] 10 20<br>15 20<br>15 20
- [ ] inky pinky ponky
---
# Question
Predict the output of the following code:
```java
if(true){
int x = 10;
SOPln("Value of x is " + x);
x ++ ;
}
SOPln("Value of x is " + x);
```
# Choices
- [ ] Value of x is 10<br>Value of x is 11
- [ ] Value of x is 10<br>Value of x is 0
- [ ] Value of x is 10<br>Value of x is 10
- [x] Error
---
# Question
Predict the output of the following code:
```java
int a = 0;
{
int b = 10;
SOPln("b = " + b);
int c = a + b;
SOPln("c = " + c);
}
a = c + b;
SOPln("a = " + a);
```
# Choices
- [ ] a = 20<br>b = 10<br>c = 10
- [ ] b = 10<br>c = 10<br>a = 20
- [x] Error
---
**Explanation:** Error b and c are out of the scope
---
# Question
Predict the output of the following code:
```java
int a = 10, b = 5;
if(true){
int c = a * b;
}
SOPln(c);
```
# Choices
- [ ] 50
- [x] Error
- [ ] Need Coffee!!
---
**Explanation:** Error the variable c is out of the scope

View File

@@ -0,0 +1,628 @@
# While Loop
---
## Agenda
- Intro of Loops
- Print numbers from 1 to 5
- Structure and Syntax of while loop
- Even numbers from 1 to n
- Print multiples of 4
- Print numbers from n to 1
- Find last digit
- Remove last digit
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
**Ques:** Print natural numbers from 1 to 5.
**Method 1:**
```
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
```
**Method 2:**
```
int i = 1;
System.out.println(i);
i ++ ;
System.out.println(i);
i ++ ;
System.out.println(i);
i ++ ;
System.out.println(i);
i ++ ;
System.out.println(i);
```
**Comparison of Method 1 and Method 2:**
Both **Method 1** and **Method 2** output the numbers 1, 2, 3, 4, and 5 in order. The only difference between the two methods is the way the code is written.
* Issues In **Method 1** : Since we are updating the values as well along with copy pasting the lines.
Possibility of Human Error
* Issues In **Method 2** : We are repeating the same lines again and again.
## Loops
Repeat a task multiple times
- For Loop
- While Loop
- Do while Loop
**Method 3:**
```
int i = 1;
while(i <= 5){
SOPln(i);
i = i + 1;
}
```
| i | i<=5 | Output | i + 1 |
|:---:|:-----:|:------:|:---------:|
| 1 | true | 1 | 2 |
| 2 | true | 2 | 3 |
| 3 | true | 3 | 4 |
| 4 | true | 4 | 5 |
| 5 | true | 5 | 6 |
| 6 | false | | **Break** |
---
## Structure of While loop
**Step 1:** Initialization of a loop variable.
**Step 2:** Write while with condition.
**Step 3:** Write the task you want to repeat.
**Step 4:** Updation of loop variable.
## Syntax of while loop
```
initialize
while(condition){
// task to be repeated
// updation
}
```
**Flow chart of while loop:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/265/original/Screenshot_2023-10-04_at_3.00.22_PM.png?1696411919" alt= “” width ="400" height="300">
---
# Question
What is the output of the following code?
```
int i = 5;
while(i <= 10){
System.out.println(i);
i = i * 2;
}
```
# Choices
- [x] 5<br>10
- [ ] 0
- [ ] Error
---
# Question
What is the output of the following code?
```
int i = 1;
while(i < 5){
System.out.print(i + " ");
i = i + 1;
}
```
# Choices
- [ ] 1 2 3 4 5
- [x] 1 2 3 4
- [ ] 5 4 3 2 1
---
# Question
What is the output of the following code?
```
int i = 0;
while(i <= 10){
System.out.print(i + " ");
i++;
}
```
# Choices
- [x] 0 1 2 3 4 5 6 7 8 9 10
- [ ] 1 2 3 4 5 6 7 8 9 10
- [ ] Error
---
# Question
What is the output of the following code?
```
int i = 1;
while(i >= 10){
System.out.print(i + " ");
i = i + 1;
}
```
# Choices
- [ ] Error
- [ ] 1 2 3 4 5 6 7 8 9 10
- [x] Nothing will get printed
- [ ] 10 9 8 7 6 5 4 3 2 1
---
# Question
What is the output of the following code?
```
int i = 1;
while(i <= 10){
System.out.print(i + " ");
}
```
# Choices
- [ ] 1 2 3 4 5 6 7 8 9 10
- [x] 1 1 1 1 1 1 ... Infinite times
---
# Question
What is the output of the following code?
```
int i = 0;
while(i <= 10){
System.out.print(i + " ");
i = i * 2;
}
```
# Choices
- [ ] 5 10
- [ ] 0
- [x] Infinite loop
- [ ] 0 2 4
---
# Question
What is the output of the following code?
```
int i = 1;
while(i <= 5){
System.out.print(i + " ");
i = i - 1;
}
```
# Choices
- [ ] 1 2 3 4 5
- [ ] 5 4 3 2 1
- [x] Infinite loop
- [ ] Inki pinky ponky
---
# Question
How many times `Hi` will be printed in the output?
```
int i = 0;
while(i <= 5){
System.out.println("Hi");
i = i + 1;
}
```
# Choices
- [ ] 5
- [x] 6
- [ ] 4
- [ ] Infinite times
---
# Question
How many times `Inki Pinki Ponki` will be printed in the output?
```
int i = 1;
while(i <= n){
System.out.println("Inki Pinki Ponki");
i = i + 1;
}
```
# Choices
- [x] n
- [ ] (n+1)
- [ ] Only once
- [ ] Too many times
---
**Ques:** Print even numbers from 1 to n
```
int n = scn.nextInt();
int i = 1;
while(i <= n){
if(i % 2 == 0){
System.out.println(i);
}
i = i + 1;
}
```
> Explain dry run of the above code for more clarity
> Example of how to dry run the above code:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/266/original/Screenshot_2023-10-04_at_3.26.15_PM.png?1696413386" alt= “” width ="500" height="300">
Another way to implement the above task is as follows:
```
int i = 2;
while(i <= n){
System.out.println(i);
i = i + 2;
}
```
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/267/original/Screenshot_2023-10-04_at_3.27.52_PM.png?1696413482
" alt= “” width ="500" height="300">
Note that the number of iterations are reduced from 6 to 3.
Let us take some test cases to test our code.
Consider `n = 17`
The output should be `2 4 6 8 10 12 14 16`
> **Instruction for Instructor:** Run the code on editor to verify the same and show to the students.
In the range 1 - 17, the total number of even numbers are 8.
In the range 1 - 10, the total number of even numbers are 5.
> Based on the above observation, ask the following question to the students?
**How to calculate the total number of multiples of x between 1 and n?**
**Ans:** `n/x`
Total number of multiples of 2 from 1 to 40 is = ![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/485/original/Screenshot_2023-09-14_232954.png?1694714463)
Total number of multiples of 2 from 1 to 51 is = ![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/486/original/Screenshot_2023-09-14_233032.png?1694714627)
---
# Question
What will be the total number of iterations in the following code?
```
int i = 1;
while(i <= 20){
System.out.println(i);
i = i + 1;
}
```
# Choices
- [x] 20
- [ ] 10
- [ ] 15
- [ ] No clue
---
# Question
What will be the total number of iterations in the following code?
```
int i = 2;
while(i <= n){
System.out.println(i);
i = i + 2;
}
```
# Choices
- [ ] n
- [x] n/2
- [ ] n+1
- [ ] Infinite
---
# Question
What will be the total number of iterations in the following code?
```
int i = 3;
while(i <= n){
System.out.println(i);
i = i + 3;
}
```
# Choices
- [x] n / 3
- [ ] 3 * n
- [ ] n+3
- [ ] n
---
# Question
What are all the multiples of 4 between 1 to 18 ?
# Choices
- [ ] 4 8 12 16 20 24
- [ ] 4 6 8 10 12 14
- [x] 4 8 12 16
- [ ] 1 4 8 12 16
---
**Ques:** Print multiples of 4 till n.
**Approach 1:**
In this approach, the code takes an input from the user and stores it in the variable n. Then, it uses a `while` loop to iterate from 1 to n. During each iteration, if the value of i is divisible by 4, it prints the value of i using `System.out.println()`.
```
int n = scn.nextInt();
int i = 1;
while(i <= n){
if(i % 4 == 0){
System.out.println(i);
}
i++;
}
```
If n is taken as 10, the output of the above code would be: `4 8`
**Approach 2:** **Number of instructions executed are reduced**
In this approach, the code initializes the variable $i$ to $4$ and then uses a `while` loop to print the value of $i$ in each iteration. The value of $i$ is incremented by $4$ during each iteration until it becomes greater than $n$.
**Code:**
```
int i = 4;
while(i <= n){
System.out.println(i);
i = i + 4;
}
```
> Explain using dry run as follows:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/733/original/upload_908acb233760adf812b6c04b41b24ff1.png?1693736372" alt= “” width ="500" height="200">
> Contrast both the dry runs and stress on the fact that the number of iterations are reduced from 10 to 2.
---
# Question
What are the total number of iterations of the following code?
```
int i = 4;
while(i <= n){
System.out.println(i);
i = i + 4;
}
```
# Choices
- [ ] n
- [ ] n + 4
- [x] n / 4
- [ ] Easy Peesy
---
**Ques:** Print numbers from n to 1.
```
int n = 5;
while(i >= 1){
System.out.println(i);
i--;
}
```
> Explain using dry run as follows:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/734/original/upload_f0f8b93644bb7df8f81fe127ed7302cd.png?1693736416" alt= “” width ="600" height="300">
---
# Question
Predict the output:
```
int i = 10;
while(i >= 0){
System.out.print(i + " ");
i = i - 2;
}
```
# Choices
- [ ] 10 9 8 7 6 5 4 3 2 1 0
- [ ] 10 8 6 4 2
- [x] 10 8 6 4 2 0
- [ ] 0 2 4 6 8 10
---
**Dry Run:**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/735/original/upload_41d0c4493836a10e847050314b6fa548.png?1693736449" alt= “” width ="450" height="400">
---
## Modulus operator (%)
It is used to find the remainder. When we take modulus by 10, we get the last digit of that number.
---
# Question
Predict the output of the following code:
```
int x = 7185;
System.out.println(x % 10);
```
# Choices
- [ ] 8
- [ ] 578
- [ ] 718.5
- [x] 5
---
# Question
Predict the output of the following code:
```
int x = 4578;
System.out.println(x % 10);
```
# Choices
- [x] 8
- [ ] 578
- [ ] 78
- [ ] None
---
# Question
Predict the output of the following code:
```
int x = 99576;
System.out.println(x % 10);
```
# Choices
- [x] 6
- [ ] 576
- [ ] 995
- [ ] None
---
# Question
Predict the output of the following code:
```
int x = 7248;
System.out.println(x / 10);
```
# Choices
- [ ] 724.8
- [ ] 725
- [x] 724
- [ ] Inky pinky ponky
---
**Ques:** Given a positive integer, write code to find it's last digit.
**Code:**
```
int n = scn.nextInt();
System.out.println(n % 10);
```
---
**Ques:** Given a positive integer, write code to remove it's last digit.
**Code:**
```
int n = scn.nextInt();
n = n / 10;
System.out.println(n);
```
---

View File

@@ -0,0 +1,599 @@
# Loops 2
---
> Quick revision
**Step 1:** Initialization of a loop variable.
**Step 2:** Write while with condition.
**Step 3:** Write the task you want to repeat.
**Step 4:** Updation of loop variable.
## Syntax of while loop
```
initialize
while(condition){ // loop stops when the condition fails
// task to be repeated
// updation
}
```
**Flow chart of while loop:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/748/original/beginner-iterations-loop-2-image-1.png?1693749426" height = "350" width = "350">
**Question:**
How to find the last digit of a number N?
**Answer:** Use the modulus operator as `N%10`.
> Give an example
**Question:** How to delete the last digit of N?
**Answer:**
```
N = N / 10;
SOP(N);
```
---
title: Printing all digits
description: Print all the digits of that number from right to left
duration: 480
card_type: cue_card
---
**Ques:** Given a integer number, print all the digits of that number from right to left.
Example, if `n = 6397` the correct output should be `7 9 3 6`
> Give the students, an intuition to solve the problem as follows:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/746/original/upload_c997251ad272ffb9708ce7c8a5bf1411.png?1693748957" alt= “” width ="450" height="350">
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach:**
* Find the last digit.
* Print the digit.
* Remove last digit.
**Code:**
```
int n = scn.nextInt();
while(n > 0){
int digit = n % 10;
SOPln(digit);
n = n / 10;
}
```
> To figure out the condition in the while loop expression (i.e., `n > 0`), give the students an intuition as follows:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/747/original/upload_a7b3a344d33b1e78a66ba64c1ae9b4a0.png?1693748996" alt= “” width ="400" height="450">
**How to handle negative numbers?**
**Ans:** Convert negative numbers to positive numbers.
> Take an example of a negative number, dry run the code. Tell the students that the code exits from the while loop condition since `n < 0`. Then give the solution.
**The updated code is as follows:**
```
int n = scn.nextInt();
if(n < 0){
n = n * -1;
}
while(n > 0){
int digit = n % 10;
SOPln(digit);
n = n / 10;
}
```
**Next corner test case:** What if `n == 0`?
In this case, the output should be $0$, but according to the code this will print nothing. So we need to handle this case as well.
**The updated code is as follows:**
```
int n = scn.nextInt();
if(n < 0){
n = n * -1;
return;
}
else if(n == 0){
SOPln(0);
return;
}
while(n > 0){
int digit = n % 10;
SOPln(digit);
n = n / 10;
}
```
**Dry Run:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/749/original/beginner-iterations-loop-2-image-2.png?1693749460" height = "450" width = "450">
---
title: Find sum of digits of a given number
description: Take examples to explain how to use while loops
duration: 900
card_type: cue_card
---
## Find Sum of Digits of A Given Number
**Question:**
Find the sum of digits of a given number.
Give examples -> 1274, 1004, -512
```
1274 -> 1 + 2 + 7 + 4 = 14
1004 -> 1 + 0 + 0 + 4 = 5
-512 -> 5 + 1 + 2 = 8
```
Note: Negative sign (**-**) is not a digit.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach:**
To discuss the approach take an example.
```
// Initialization
n = 2748
s = 0
```
| n | n > 0 | d = n % 10 | s = s + d | n = n / 10 |
|:----:|:-----:|:----------:|:---------:|:----------:|
| 2748 | true | 8 | 8 | 274 |
| 274 | true | 4 | 12 | 27 |
| 27 | true | 7 | 19 | 2 |
| 2 | true | 2 | 21 | 0 |
| 0 | false | - | - | - |
```
int n = scn.nextInt();
if (n < 0) {
n = n * - 1;
}
int s = 0;
while (n > 0) {
int d = n % 10;
s = s + d;
n = n / 10;
}
SOPln(s);
```
---
title: Add a given digit to the back of a given number N.
description: Take examples to explain how to use while loops
duration: 800
card_type: cue_card
---
### Example 1
**Question:**
Given a positive integer N and a single digit d, add d to the back of N.
**Example:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/751/original/beginner-iterations-loop-2-image-3.png?1693749757" height = "350" width = "500">
Formula to add d to the back of N:
```
n = n * 10 + d;
```
---
title: Find the reverse of a given number
description: Take examples to explain how to use while loops
duration: 1100
card_type: cue_card
---
### Example 2
**Question:**
Given a number N, store it's reverse in another variable and print it.
**Examples:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/752/original/beginner-iterations-loop-2-image-4.png?1693749809" height = "350" width = "220">
**Idea/Approach:**
Initialize a variable rev = 0 and one by one take the last digit of N and add it to rev as shown below.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/754/original/beginner-iterations-loop-2-image-5.png?1693749853" height = "350" width = "350">
**Steps:**
* Get last digit
* Add last digit to the back of rev
* Remove last digit
* Repeat the above three steps till the number is greater than zero
**Dry run:**
| n | n > 0 | d = n % 10 | rev = rev * 10 + d | n = n / 10 |
|:----:|:-----:|:----------:|:------------------:|:----------:|
| 1456 | true | 6 | 6 | 145 |
| 145 | true | 5 | 65 | 14 |
| 14 | true | 4 | 654 | 1 |
| 1 | true | 1 | 6541 | 0 |
| 0 | false | - | - | - |
```
int n = scn.nextInt();
int copy = n;
if (n < 0) {
n = n * - 1;
}
int rev = 0;
while (n > 0) {
int d = n % 10;
rev = rev * 10 + d;
n = n / 10;
}
if (copy < 0) {
rev = rev * - 1;
}
SOPln(s);
```
> Dry run with n = 2400 and show that the output will be 42 and not 0042.
Tell them that if you want to print 0042, print the digits of n from right to left. It is not possible for an integer variable to store 0042.
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/755/original/beginner-iterations-loop-2-image-6.png?1693750025" height = "350" width = "650">
> Show dry run with - 417 as n.
---
title: Check if a given number is palindrome or not
description: Take examples to explain how to use while loops
duration: 720
card_type: cue_card
---
### Example 3
**Question:**
Given a number N, check if number if palindrome or not.
A number is said to a palindrome if it remains the same when its digits are reversed. Ex- 1221, 1551, 131, etc.
**Exercise for students:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/756/original/beginner-iterations-loop-2-image-7.png?1693750061" height = "400" width = "430">
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach:**
Find the reverse of the number using what we discussed in the last quiz and compare it with the original number. It it is the same, then the number is palindromic, otherwise not.
```
int n = scn.nextInt();
int copy = n;
if (n < 0) {
n = n * - 1;
}
int rev = 0;
while (n > 0) {
int d = n % 10;
rev = rev * 10 + d;
n = n / 10;
}
if (copy < 0) {
rev = rev * - 1;
}
if (rev == copy) {
SOPln("PALINDROME");
}
else {
SOPln("NOT PALINDROME")
}
```
---
title: For loop basics
description: Quick recap of the syntax and flow of for loops
duration: 120
card_type: cue_card
---
## For loop Basics
Every for loop question can be done using a while loop. The difference lies in the syntax.
**Syntax:**
```
for(Initialization; Condition; update) {
// Statements to be executed
}
```
> Explain the syntax.
**Flow:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/757/original/beginner-iterations-loop-2-image-8.png?1693750115" height = "400" width = "380">
---
title: Print numbers from 1 to 5 using for loops
description: Take examples to explain how to use for loops
duration: 180
card_type: cue_card
---
### Example 4
**Question:**
Print all numbers from 1 to 5.
```
for(int i = 1; i <= 5; i ++ ) {
SOPln(i);
}
```
> Explain the logic behind initialization, condition and update statements.
**Dry Run:**
| i | i <= 5 | print(i) | i++ |
|:---:|:------:|:--------:|:---:|
| 1 | true | 1 | 2 |
| 2 | true | 2 | 3 |
| 3 | true | 3 | 4 |
| 4 | true | 4 | 5 |
| 5 | true | 5 | 6 |
| 6 | false | - | - |
---
title: Quiz 1
description: Quiz 1
duration: 60
card_type: quiz_card
---
# Question
Expected output for following code :
```
for(int i = 1; i <= 10; i = i + 2) {
System.out.println(i);
}
```
# Choices
- [ ] All Numbers from 1 to 10
- [ ] All Even Numbers from 1 to 10
- [x] All Odd Numbers from 1 to 10
- [ ] All Numbers from 1 to 9
---
title: Explain the quiz answer
description: Perform a dry run to explain the quiz question
duration: 240
card_type: cue_card
---
### Explaination
**Dry Run:**
| i | i <= 10 | print(i) | i += 2 |
|:---:|:-------:|:--------:|:------:|
| 1 | true | 1 | 3 |
| 3 | true | 3 | 5 |
| 5 | true | 5 | 7 |
| 7 | true | 7 | 9 |
| 9 | true | 9 | 11 |
| 11 | false | - | - |
---
title: Print the count of digits of a number
description: Take examples to explain how to use for loops
duration: 600
card_type: cue_card
---
### Example 5
**Question:**
Given a positive number, print the count of digits.
> Give examples such as 5164, 121700, 9, etc.
**Approach/Intuition:**
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/767/original/beginner-iterations-loop-2-image-9.png?1693751819" height = "400" width = "380">
```
int count = 0;
for(int i = n; i > 0; i = i / 10) {
count += 1;
}
SOPln(count);
```
> Show that the above code does not work for n = 0 and make the following change.
```
int count = 0;
if (n == 0) count = 1;
for(int i = n; i > 0; i = i / 10) {
count += 1;
}
SOPln(count);
```
---
title: Read 5 numbers and for every number print last digit of the number.
description: Explain the need of for loops
duration: 780
card_type: cue_card
---
### Example 6
**Question:**
Read 5 numbers and for every number print last digit of the number.
**Example:**
Input:
34
45
378
980
456
**Output:**
4
5
8
0
6
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Approach 1:**
```
int a = scn.nextInt();
int b = scn.nextInt();
int c = scn.nextInt();
int d = scn.nextInt();
int e = scn.nextInt();
SOPln(a % 10);
SOPln(b % 10);
SOPln(c % 10);
SOPln(d % 10);
SOPln(e % 10);
```
**Approach 2:**
```
for(int i = 0; i < 5; i ++ ) {
int n = scn.nextInt();
SOPln(n % 10);
}
```
---
title: Read T numbers and for every number print last digit of the number.
description: Show examples to explain how to use for loops
duration: 360
card_type: cue_card
---
### Example 7
**Question:**
Read T numbers and for every number print the last digit.
**Input Format:**
1st Line: Contains T
Followed by T lines containing the T numbers
```
int T = scn.nextInt();
for(int i = 0; i < T; i ++ ) {
int n = scn.nextInt();
SOPln(n % 10);
}
```
---
title: Read T numbers and for every number print the sum of digits of the number.
description: Show examples to explain how to use for loops
duration: 420
card_type: cue_card
---
### Example 8
**Question:**
Read T numbers and for each number, print the sum of digits of the number.
**Input:**
3
566
4130
162
**Output:**
17
8
9
```
int T = scn.nextInt();
for(int i = 0; i < T; i ++ ) {
int n = scn.nextInt();
if (n < 0) {
n = n * - 1;
}
int s = 0;
while (n > 0) {
int d = n % 10;
s = s + d;
n = n / 10;
}
SOPln(s);
}
```
> Show dry run for the example above.
Same question using for loop -
```
int T = scn.nextInt();
for(int i = 0; i < T; i ++ ) {
int n = scn.nextInt();
if (n < 0) {
n = n * -1;
}
int s = 0;
for(int x = n; x > 0; x ++ ) {
int d = x % 10;
s = s + d;
}
SOPln(s);
}
```

View File

@@ -0,0 +1,958 @@
# Beginner: Operators
---
## Agenda
* Typecasting Revision
* Rules doing basic operations
* Integer Overflow
* Operators (Logical, Unary)
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
## Rules
1. While type casting, if no chance of data loss, then we get no error -> Implicit / Widening Typecasting (Happens automatically).
2. If there may be a data loss, then we will get some error. If we still want to typecast, we forcefully have to do it -> Explicit / Narrowing (forcefully).
**Note:** If students are not able to understand, run the corresponding quiz code in IDE, and then clarify any questions.
---
# Question
Predict the output:
```
int abc = 400;
long x = abc;
System.out.print(x);
```
# Choices
- [x] 400
- [ ] Error
- [ ] Random Value
- [ ] Good Morning!
---
# Explanation
When we store int into long, there is no data loss, hence 400 is the answer. Explain more if necessary.
---
# Question
Predict the output:
```
long a = 100000; // 10^5
System.out.print(a);
```
# Choices
- [ ] Error
- [x] 100000
- [ ] a
---
# Explanation
**Mistake:** Some students may think that we need a L after the number but its not necessary. Because implicity typecasting is going on. Explain more, if needed.
---
# Question
Predict the output:
```
long x = 500000;
int y = x;
System.out.print(y);
```
# Choices
- [x] Error
- [ ] 500000
- [ ] Some random value
---
# Explanation
```
long x = 500000; // This line is correct (Implcity typecasting)
int y = x; // Possible data loss.
System.out.print(y);
```
We cannot store a long into int, because of possible data loss. Hence, the error.
**Q.** Ask students on how to correct this?
**A.** Explicit typecasting
Move on to the next quiz which is based on this.
---
# Question
Predict the output:
```
long n = 60000;
int a = (int)n;
System.out.print(a);
```
# Choices
- [ ] Random Value
- [ ] Error
- [x] 60000
- [ ] How would I know?
---
# Explanation
The 2nd line is forcing the compiler to change the long to int which is correct.
**Mistake:** Some students may ask why we won't get any random value. Because, 60000 is within the range of int data type, and hence no loss.
Range of int -> -2 * 10^9 to 2 * 10^9
Give the following example:
long x = 100000000000 // 10^11
This number is too large and so we need to mention explicity that:
long x = 100000000000L.
---
# Question
Predict the output:
```
long a = 100000000000L; // 10^11
int b = (int)a;
System.out.println(b);
```
# Choices
- [ ] 100000000000
- [ ] Error
- [x] Random Value
- [ ] Too many zeroes
---
# Explanation
Since 10^11 cannot be stored in int, and we are forcing. So, data loss (Overflow) is happening, and some value is getting lost, we are getting random value.
---
title: Quiz 6
description: Quiz 6
duration: 30
card_type: quiz_card
---
# Question
Predict the output:
```
double x = 7.89;
System.out.print(x);
```
# Choices
- [ ] 7
- [x] 7.89
- [ ] Error
- [ ] Ex is not texting back.
---
# Explanation
Since the right value is of type double. We can store double into double without any issues.
---
# Question
Predict the output:
```
float val = 10.78;
System.out.print(val);
```
# Choices
- [ ] 10.78
- [ ] 10
- [x] Error
- [ ] I am sleeping
---
# Explanation
Any decimal number is of double type, while the type of val is float.
**Q.** Can we store double into float type?
**A.** No, as there can be possible data loss.
Hence, we get an error.
**Q.** Ask students into how to fix this?
**A.** Explicit typecasting to float.
---
# Question
Predict the output:
```
float x = 15.88f;
System.out.print(x);
```
# Choices
- [x] 15.88
- [ ] 15
- [ ] Error
---
# Explanation
Since, we explicitly typecasted to float, hence we will not get any error.
---
# Question
Predict the output:
```java
double y = 4.78;
float a = y;
System.out.println(a);
```
# Choices
- [ ] 4.78
- [x] Error
- [ ] Missed the lectures
---
# Explanation
Since, we are storing a double type into float, we have possible data loss. Hence, we get an error.
---
## Rules doing Basic Operations
## Rule 1
When we do operation between a decimal and a non-decimal number, the output is always decimal.
* int op double --> double
* long op float --> float
**Note:** Run each of the following example codes in the compiler, and show the output to students.
## Example 1
### Incorrect Code
Don't let the students know that the code is incorrect. Ask them if it's correct and if not, how is it violating the Rule 1.
```
class Scaler {
public static void main(String[] args) {
int x = 10;
double y = 10.25;
int z = x + y;
System.out.println(z);
}
}
```
### Output
```
error: incompatible types: possible lossy conversion from double to int
int z = x + y;
^
1 error
```
Explain why their is a possible lossy conversion if we store the sum in an integer.
A. (x + y) is of double type.
Ask students on how to remove the error?
### Correct Code
```
class Scaler {
public static void main(String[] args) {
int x = 10;
double y = 10.25;
double z = x + y;
System.out.println(z);
}
}
```
### Output
```
20.25
```
Q. Ask students on how to store the result into an integer i.e, we don't want to store into a double.
A. Typecasting
### Correct Code
```
class Scaler {
public static void main(String[] args) {
int x = 10;
double y = 10.25;
int z = (int)(x + y);
System.out.println(z);
}
}
```
## Rule 2
When we do operation between two operands of same category, the result is of bigger type.
* int op long --> long
* float op double --> double
* int op int --> int
* long op long --> long
**Note:** Run each of the following example codes in the compiler, and show the output to students.
## Example 1
### Incorrect Code
Don't let the students know that the code is incorrect. Ask them if it's correct and if not, how is it violating the Rule 2.
```
class Scaler {
public static void main(String[] args) {
int x = 20;
long y = 150L;
int z = x + y;
System.out.println(z);
}
}
```
### Output
```
/tmp/thqSRPUchr/Scaler.java:6: error: incompatible types: possible lossy conversion from long to int
int z = x + y;
^
1 error
```
Explain why their is a possible lossy conversion if we store the sum in an integer.
A. (x + y) is of long type.
Ask students on how to remove the error?
### Correct Code
```
class Scaler {
public static void main(String[] args) {
int x = 20;
long y = 150L;
long z = x + y;
System.out.println(z);
}
}
```
### Output
```
170
```
---
## Integer Overflow
**Note:** For better clarity of quizzes, please run the codes in the compiler as well.
Explain the integer overflow concept after giving the following quiz.
---
# Question
Predict the output:
```
int a = 100000;
int b = 400000;
int c = a * b;
System.out.print(c);
```
# Choices
- [ ] 40000000000
- [x] Some random Value
- [ ] Error
---
## CPU and its components
Before explaining the quiz's answer, we need to understand some more information.
**Q.** Where are these variables stored and where are these operations carried out?
We have two major components:
* Central Processing Unit (CPU)
* ALU - Arithmetic Logic Unit
* Control Unit
* Registers
* Random Access Memory (RAM)
Look at the following diagram.
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/460/original/upload_d26c363818f0ecae906193eac45751b9.png?1694708166"
width = "600" height = "300">
Explain the use of the two components using the code for the quiz.
int a = 100000;
int b = 400000;
Populate the RAM with these two variables.
int c = a * b;
We want to store c into RAM. But we need to compute a * b first.
**Q.** Where will the computation happen?
**A.** ALU
Values will be transferred to CPU's registers via buses, and then computation will be performed. The values are then written back to c's location in RAM.
The result would look something like this:
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/461/original/upload_84a6994f462551877ec0827f0a75b961.png?1694708288"
width = "700" height = "300">
If the inputs are integers, the ALU will assume that the output is also integer, which cannot be stored.
**Note:** The compiler has no control over this.
So, the output will be some random value.
Now, formally define what is **Integer Overflow**?
* When we attempt to store a value that cannot be represented correctly by a data type, an Integer Overflow.
* Integer Overflow occurs when the value is more than the maximum representable value
---
# Question
Predict the output:
```
int a = 100000;
int b = 400000;
long c = a * b;
System.out.print(c);
```
# Choices
- [ ] 40000000000
- [ ] 2147483647
- [x] Some random Value
- [ ] Error: product of integers can't be stored in long
# Explanation
Explain why this is the correct answer. If we store an integer in a long, we don't have any issues. So, according to the compiler, there's nothing wrong.
Explain it in the following way:
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/462/original/upload_6ee7d0a207336c303f89d6aab64cbaaa.png?1694708350"
width = "700" height = "250">
---
# Question
Predict the output:
```
long a = 100000;
long b = 400000;
int c = a * b;
System.out.print(c);
```
# Choices
- [ ] 40000000000
- [ ] Some random Value
- [x] Error
---
# Explanation
Explain why we are getting error in this case.
long * long --> long
Q. Can we store long into an integer?
A. No, we can't. So, there is a possible lossy conversion.
**Reminder:** Remind the students to focus on the two rules, and all the questions would be easy.
---
# Question
Predict the output:
```
long a = 100000;
int b = 400000;
long c = a * b;
System.out.print(c);
```
# Choices
- [x] 40000000000
- [ ] Compilation Error
- [ ] Some random Value
---
# Explanation
long * int --> long
Q. Can we store long into a long type?
A. Yes.
Explain this again in RAM and ALU in the following way:
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/463/original/upload_7581c0b9de5fd1dad5e7fc79cea74dd8.png?1694708442"
width = "700" height = "250">
---
# Question
Predict the output:
```
int a = 100000;
int b = 400000;
long c = (long)(a * b);
System.out.println(c);
```
# Choices
- [ ] 40000000000
- [ ] Compilation Error
- [x] Some random Value
---
# Explanation
int * int --> int
Q. Ask if we are typecasting individual variables or (a * b)?
A. We are typecasting (a * b) which is a random value to long.
Explain this again in RAM and ALU in the following way:
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/464/original/upload_aa2768e0525d6a8622f5133220bdcee4.png?1694708474" width = "700" height = "300">
Let the students know that this is not the correct way to multiply two integers.
---
# Question
What will be the output?
```
int a = 100000;
int b = 400000;
long c = (long)a * b;
System.out.println(c);
```
# Choices
- [x] 40000000000
- [ ] Compilation Error
- [ ] Some random Value
---
# Explanation
Typecast the value of a to long, and then multiply it with the integer b.
Q. What will be the output of the multiplication of a long and an integer?
A. According to Rule 2, it will be long.
We can store a long into a long variable.
Explain this again in RAM and ALU in the following way:
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/465/original/upload_ff5e95b19bb73ea5f469d0c89ba91411.png?1694708553" height = "250" width = "600">
**Clarification:**
Some students get confused between the following 2 things:
* long c = (long) (a * b)
* long c = (long)a * b
Explain that in the 1st case, we are typecasting the product of two integers to a long, and in the 2nd case, we are first typecasting a into long, and then multiplying it with an integer.
---
In this section, we will study different types of operators namely:
* Arithmetic Operators
* Relational Operators
* Logical Operators
* Unary Operators
* Assignment Operators
---
**Q.** What are Logical Operators?
**A.** Logical operators can be defined as a type of operators that help us to combine multiple conditional statements. There are three types of logical operators: **AND (&&), OR (||) and Logical NOT (!) operators**.
To better understand AND(&&) operator, give the students the following analogy.
1. Driver's License
* age >= 18
* Know how to drive
In which of the following 4 scenarios the person should get their driver's license.
$\begin{array}{|c:c:c:c:c:c|}
\hline
age >= 18 & Know\ how\ to\ drive & Driver's\ License\ received \\ \hline
True & True & True \\ \hline
True & False & False \\ \hline
False & True & False \\ \hline
False & False & False \\ \hline
\end{array}$
So, we get the drivers's license when both the conditions are true.
AND [&&] -> Both conditions need to be true to get true as answer.
To better understand Logical OR (||) operator, give the students the following analogy.
2. Eligibility Criterion for Exam
* Should have a diploma
* Should have a degree
If they have either diploma or degree, they will be allowed to sit in the exam.
In which of the following 4 scenarios the person should be allowed to sit in the exam.
$\begin{array}{|c:c:c:c:c:c|}
\hline
Have\ a\ diploma? & Have\ a\ degree? &Allowed\ to\ sit\ in\ exam \\ \hline
True & True & True \\ \hline
True & False & True \\ \hline
False & True & True \\ \hline
False & False & False \\ \hline
\end{array}$
OR [||] -> Even if one of the conditions is true, we get true as an answer.
### Important Observation of AND and OR Operator
* In case of AND, if the 1st condition is false, does the 2nd value have any effect? No, so the compiler would skip the 2nd check if the 1st condition is false.
* Similarly, if the 1st condition is true, does the 2nd value have any effect? No, so the compiler would skip the 2nd check if the 1st condition is true.
To better understand Logical Not (!) operator, let us look into following analogy.
3. To purchase milk, it shouldn't be raining outside. How to check for this condition?
If it's not raining outside, purchase milk.
$\begin{array}{|c:c:c:c:c:c|}
\hline
Raining\ outside & Can\ purchase\ Milk? \\ \hline
True & False \\ \hline
False & True \\ \hline
\end{array}$
Meaning, whatever is the case, just invert it.
### Examples
Discuss the following examples related to both arithmetic and logical operators.
1. Given two scores, check if they made a 50 partnership i.e, their combined score is 50 or not.
* a = 15, b = 30 -> False
* a = 25, b = 25 -> True
* a = 10, b = 60 -> False
How to write the code for it in java?
```
a + b == 50
```
Q. What type of operator are we using here?
A. Relational Operator
2. Read 2 scores, check if both of them passes. The passing score is 35.
* a = 35, b = 40 -> True
* a = 34, b = 40 -> False
* a = 50, b = 14 -> False
Q. How to check if a score is passed?
A. Use the >= operator.
Q. How to check if both the scores are passed?
A. Use the AND (&&) operator.
How to write the code for it in java?
```
a >= 35 && b >= 35
```
3. Read 2 scores and check if atleast one of them passed. The passing score is 35.
Ask students to do it themselves.
**Answer:**
```
a >= 35 || b >= 35
```
**Note:** If students ask about the Logical NOT (!) operator, let them know that this will be discussed in unary operators section.
---
# Assignment Operators
It is used to assign value.
They are : =, +=, -=, * =, /= etc.
```java
int a = 10;
a = a+5;
System.out.println(a);
```
>Explanation: This will increase the value of a by 5.
Same thing can be done using "+=".
```java
int b = 10;
b += 5; // increment the value of b by 5
System.out.println(b);
```
```java
int c = 20;
c -= 4; // decrement the value of c by 4
System.out.println(b);
```
Similarly, /= and * = works
---
Q. What are unary operators?
A. Unary operators work on a single operand only.
Give them a little bit idea of the following:
* What are Pre operators -> ++a, --a
* What are Post operators -> a++, a--
Run the following codes on IDE:
```
int a = 10;
a ++ ;
System.out.println(a);
```
```
int b = 10;
++ b;
System.out.println(b);
```
Both the codes give 11 as output.
Ask the students what is happening here, and why are we getting the same result.
Now, to show the difference, use the following codes.
```
int a = 10;
System.out.println(a ++ );
```
```
int b = 10;
System.out.println( ++ b);
```
The first code will give 10 as output, while the 2nd code gives 11 as output.
To explain the reason for this behaviour, show them the following table and ask them to focus on the first 4 rows.
$\begin{array}{|c:c:c:c:c:c|}
\hline
Operator & Name \\ \hline
a++ & Post-Increment\ Operator \\ \hline
++a & Pre-Increment\ Operator \\ \hline
a-- & Post-Decrement\ Operator \\ \hline
--a & Pre-Decrement\ Operator \\ \hline
! & Logical\ Not\ Operator \\ \hline
\end{array}$
Coming back to the original question,
**Post-Increment**
```
int a = 10;
System.out.println(a ++ );
```
The last line is broken down into the following two lines.
```
System.out.println(a);
a ++ ;
```
**Pre-Increment**
```
int a = 10;
System.out.println(++ a);
```
The last line is broken down into the following two lines.
```
++a;
System.out.println(a);
```
Now, ask students if they can figure out the reason why the 1st code is printing 10, while the 2nd code is printing 11.
Mention that similar is the case with pre-decrement and post-decrement operators.
# Examples
## Example 1
```
int a = 10;
int b = 20;
int c = a ++ + b ++ ;
System.out.println(a + b + c);
```
Ask the following questions along with explanation, wherever necessary.
**Q.** What is the value of c?
**A.** 30
**Q.** What is the current value of a after 3rd line?
**A.** 11
**Q.** What is the current value of b after 3rd line?
**A.** 21
**Q.** What will be the output?
**A.** 62
## Example 2
```
int a = 10;
int b = a ++ + a ++ ;
System.out.println(a);
System.out.println(b);
```
**Output:**
```
12
21
```
Explanation: First we will solve left "a++", that will give b = 10 + a++, and now a will be 11.
Then again, we solve 2nd "a++", b = 10 + 11, and now a will be 12 after this.
So, finally a = 12, b = 21.
Q. Suppose, we add the following statement in the above code, what would be the value of c?
```
int c = b ++ ;
```
A. There are 2 things happening -> Assignment and Post-Increment.
But since its post-increment, we will use the value of b first, and then increment the value of b.
So, value of c = 21.
Q. What if we add the following statement instead?
```
int c = ++ b;
```
A. There are 2 things happening -> Assignment and Pre-Increment.
But since its pre-increment, we will increment the value of b and then use the value of b.
So, value of c = 22.
## Example 3
```
int a = 10;
int b = a-- ;
System.out.println(a);
System.out.println(b);
```
**Output:**
```plaintext
9
10
```
Explain the reason for the above output accordingly if the students understood or not.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,412 @@
# Problems on Arrays:
---
## Agenda
1. Count of Pairs with sum = K
2. Elements having at least 1 element greater than it
3. Given a mat[][] and row num, return sum of that row
4. Given a mat[][] and col num, return sum of that col"
5. Given two matrices and return sum of mat[][]
6. Return an arraylist with all unique element
7. Return unique of elements from every row
---
#### Problem Statement
Given an array arr and a value k, find the count of pairs (i, j) such that `arr[i] + arr[j] == k` where i != j.
**Note 1:** i & j are indices of array.
**Note 2:** (i, j) is the same as (j, i).
#### Example 1
```cpp
Input: arr = [2, 4, 2, 5, 1, 3], k = 6
Output: 3
```
**Explanation:** Following pairs satisfy the condition-
(0, 1) -> arr[0] + arr[1] = 2 + 4 = 6
(1, 2) -> arr[1] + arr[2] = 4 + 2 = 6
(3, 4) -> arr[3] + arr[4] = 5 + 1 = 6
Hence, the answer is 3.
---
# Question
Given ar[5] = {5 3 2 3 6} k = 8
no of pairs (i , j) are there such that ar[i] + ar[j] = k ?
# Choices
- [x] 3
- [ ] 4
- [ ] 5
- [ ] 6
---
### Explanation
Following pairs satisfy the condition-
(0, 1) -> arr[0] + arr[1] = 5 + 3 = 8
(0, 3) -> arr[0] + arr[3] = 5 + 3 = 8
(2, 4) -> arr[2] + arr[4] = 2 + 6 = 8
Hence, the answer is 3.
---
#### Solution 1
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/609/original/upload_f198c3d66fb5a7439da1ba2b90fd6e27.png?1695226268)
One way to solve this problem is to use a brute force approach, which involves checking every possible pair of elements in the array to see if their sum is equal to k. Here are the steps involved in this approach:
* Initialize a variable count to 0 to keep track of the count of pairs.
* Traverse the array arr using two nested loops, comparing each pair of elements in the array to see if their sum is equal to k.
* Return count/2, since (i, j) & (j, i) are considered as same.
#### Pseudocode
```java
public static int countPairs(int[] arr, int k) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (i!=j && arr[i] + arr[j] == k) {
count++;
}
}
}
return count / 2;
}
```
#### Solution 2
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/610/original/upload_9369a6feb8f49627a24b2370d7852a31.png?1695228119)
If we notice, in the above solution we are counting (i, j) & (j, i) both. If we not consider one of the pair initially only, then it will not get added to the count. To achieve this, we will always start the inner loop from one index greater than the outer loop.
#### Pseudocode
```java
public static int countPairs(int[] arr, int k){
int count = 0;
for (int i = 0; i < arr.length; i++){
for (int j = i+1; j < arr.length; j++){
if (arr[i] + arr[j] == k){
count++;
}
}
}
return count;
}
```
---
### Problem:
Given a 2D array and a row index, return sum of that particular row.
| 0 | 1 | 2 | 3 |
|:--- | --- | --- | --- |
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
row index =1,
5 + 6 + 7 + 8, output=26
---
# Question
Given a matrix, row index =0, return sum of that particular row.
```plaintext
1 2 3 4
5 6 7 8
9 10 11 12
```
# Choices
- [x] 10
- [ ] 4
- [ ] 26
- [ ] 6
---
#### Pseudocode
```java
static int rowSum(int[] mat, int i){
int n = mat.length;
int m = mat[0].length;
int sum=0;
for (int j = 0; j < m; j++){
sum=sum+mar[i][j];
}
return sum;
}
```
---
### Problem:
Given a 2D array and a column index, return sum of that particular column.
| 0 | 1 | 2 | 3 |
|:--- | --- | --- | --- |
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
column index =2,
3 + 7 + 11, output=21
Ask the students to do it yourself.
---
### Add two matrices
Write a function to add two matrix of same dimension and return the resultant
#### Testcase 1
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/126/original/ex1.png?1681938556)
#### Solution with explaination
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/129/original/ex1sol.png?1681939055)
* Matrix are of same dimension i.e. they have same number of rows and columns.
* The values that are present at same row number and same column number in both matrix are to be added together inorder to get the resultant.
* In above solution number with same colors are present at same row number and same column number in both matrix.
* So inorder to get element at c[0][0] we add A[0][0] i.e 7 and B[0][0] i.e. 3 and so on.
#### Testcase 2
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/130/original/ex2.png?1681939395)
#### Solution
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/131/original/ex2sol.png?1681939423)
---
# Question
Can we add a 3x4 matrix with a 3x4 matrix?
# Choices
- [x] Yes
- [ ] No
- [ ] Maybe
---
# Question
Can we add a 3x4 matrix with a 3x3 matrix ?
# Choices
- [ ] Yes
- [x] No
- [ ] Maybe
---
#### Observation
* On oberserving both the cases we can give generalized formula for sum of matrix having same dimensions as:-
<div class="alert alert-block alert-warning">
SumMat[i][j] = Mat1[i][j] + Mat2[i][j]
</div>
#### Code
```java
static int[][] addMatrix(int[][] A, int[][] B) {
int m = A.length;
int n = A[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans[i][j] = A[i][j] + B[i][j];
}
}
return ans;
}
```
---
#### Problem Statement
Given an ArrayList of integers, return all the unique numbers in the ArrayList.
**Note:** An element with frequency 1 is known as unique element.
#### Example 1
```java
Input = 10 7 32 10 32 48 56 12 48 19 11 32
Output = 7 56 12 19 11
```
---
# Question
ar[] = {6 10 8 2 8 10 11}
Return all unique elements
# Choices
- [x] 6 2 11
- [ ] 6 2 10
- [ ] 10 8 11
- [ ] None of the above
---
#### Solution
Iterate on each element, check if frequency is 1 then add element to ans arrayList.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/611/original/upload_1e1be1522211dcb2b6df15193d4bc796.png?1695228300)
#### Pseudocode
```java
static ArrayList<Integer> getUniqueNumbers(ArrayList<Integer> list) {
ArrayList<Integer> ans = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int freq = 0;
for (int j = 0; j < list.size(); j++) {
if (num == list.get(j)) {
freq++;
}
}
if (freq == 1) {
ans.add(num);
}
}
return ans;
}
```
---
### Even numbers
Given a 2D ArrayList, return a 2D ArrayList which contains unique elements from every row.
#### Example 1
```java
A =[ [1, 2, 3, 4, 1],
[5, 8, 7, 8, 8],
[9, 4, 3, 2, 4] ]
ans= [ [2, 3, 4],
[5, 7],
[9, 3, 2] ]
```
#### Example 2
```java
A = [ [3, 2],
[2, 4] ]
ans= [ [3, 2],
[2, 4] ]
```
#### Observation
We will traverse every element in ArrayList and insert unique elements in output.
#### Pseudocode
```java
public int freq(ArrayList<Integer>list,int k) {
int count = 0;
for(int i=0; i < list.size();i++) {
if(list.get(i) == k) {
count++;
}
}
return count;
}
public ArrayList<ArrayList<Integer>> solve(ArrayList<ArrayList<Integer>> A) {
int n = A.size();
int m = A.get(0).size();
ArrayList<ArrayList<Integer>>ans = new ArrayList<>();
for(int i=0; i < n;i++) {
ArrayList<Integer>temp = new ArrayList<>();
for(int j=0; j < m;j++) {
int ele = A.get(i).get(j);
if(freq(A.get(i),ele) == 1) {
temp.add(ele);
}
}
ans.add(temp);
}
return ans;
}
```
---
### Problem:
Given an array A of N integers.
Count the number of elements that have at least 1 elements greater than itself.
### Example1:
```java
A = [3, 1, 2]
```
```java
Output:
2
```
### Example 2:
```java
A = [-17, 15, 6, 3, 15, 7, -19, 15]
```
```java
Output:
8-3 = 5
```
---
TODO:
1. Find the max in array using 1 loop.
2. Count the frequency of max in array using 1 loop.
3. ans= total no of elements(ar.length)- count
---

View File

@@ -0,0 +1,379 @@
# String Implementation
---
1. Introduction to Characters
2. ASCII Introduction
3. Sum of digits in the string with characters and digits
4. Replace all the characters 'x' with '$'
5. Count uppercase and lower case characters
6. Count number of characters of first string present in the second string
---
### Character:
A character represent a single symbol.
There are different types of characters:
* Uppercase characters : ['A' - 'Z']
* Lowercase characters : ['a' - 'z']
* Numeric characters: ['0' - '9']
* Special characters: ['@', '#', '\$', '%', '&'...]
There are a total of 128 characters.
## Syntax
**Example 1:**
```java
char ch = 'a';
System.out.println(ch);
```
**Output:**
```plaintext
a
```
**Example 2:**
```java
char ch = 'ab';
System.out.println(ch);
```
**Output:**
```plaintext
Error: Only a single symbol is a character.
```
---
## Why do we need ASCII Codes?
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/011/original/upload_af865cf73ed0c988a8d142644563fb18.png?1696309321)
---
## ASCII Codes
ASCII stands for **American Standard Code for Information Interchange.**
These codes are a standardized system of assigning a unique numeric value to each character in the English language and other common characters, such as punctuation marks and symbols.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/012/original/upload_ad03a8809c394ba2737d0231732978bc.png?1696309363)
## Show the ASCII table in the class
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/013/original/upload_dfd1115d24ab8bf9340a4fa91a8c644a.png?1696309407)
---
#### Definition
In programming, a string is a data type used to represent a sequence of characters.
#### Syntax
The syntax for declaring and initializing a string variable in Java is:
```java
String str = "Hello World!"; // Double quotes are used to define a string
```
#### Example -
```java
String str = "How are you?"
print(str) // How are you? will be printed
```
#### Indexing
String indexing starts from 0, where the first character is at index 0, the second character is at index 1, and so on.
**Example -**
```java
String str = "Hello, World!";
System.out.println(str.charAt(0)); // Output: 'H'
System.out.println(str.charAt(7)); // Output: 'W'
```
---
### Properties of a String
Some of the most commonly used properties of a string include:
* **Length:** The length() method of the String class returns the number of characters in a string. For example,
```java
String str = "Priyanshi";
int n = str1.length(); // assigns 9 to variable n as str has 9 characters.
System.out.println(str.length()); // 9
```
* **Access a character:** The charAt(index) method of the String class returns the character at that index in a string. Indexing in string is same as that in array and starts from 0. For example,
```java
String str = "Priyanshi";
System.out.println(str.charAt(5)); // output will be 'n'.
```
* **Iterate a string:** We can iterate over the characters of a string using a loop. One way to do this is to use a for loop that iterates over the index positions of the string, and then use the charAt() method to retrieve the character at each position. For example,
```java
String str = "Priyanshi";
for (int i = 0; i < str.length(); i++) {
System.out.println(i + " -> " + str.charAt(i));
}
```
* **Update a string:** In Java, strings are immutable, meaning that their contents cannot be changed after they are created.
* **Concatenating characters to String:** In Java, a character can be concatenated after a string by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
```java
// Concatentaion example
String s1 = "Hello";
String s2 = s1 + "Everyone";
System.out.println(s2); // Output will be "Hello Everyone"
String s3 = "Hi";
s3 = s3 + 'i';
System.out.println(s3); // Output will be "Hii"
s3 = 'e' + s3;
System.out.println(s3); // Output will be "eHii"
s3 = "Bye " + s3;
System.out.println(s3); // Output will be "Bye eHii"
```
---
#### Problem statement:
Given a string s, you have to find the length of the longest word in the input string.
### Exanple 1:
Input:
hi hello bye
Output:
5
Explanation:
In the sentence "hi hello bye", hello is the longest word, whose length is 5.
---
# Question
Given string A, "coding is awesome"
find the length of the longest word in the given string.
# Choices
- [x] 7
- [ ] 6
- [ ] 5
- [ ] I dont know
---
### Explanation
In the sentence "coding is awesome", awesome is the longest word, whose length is 7.
---
```java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
int maxLength = 0;
int currentLength = 0;
for (int i = 0; i < line.length(); i++) {
char currentChar = line.charAt(i);
if (currentChar != ' ') {
currentLength++;
} else {
if (currentLength > maxLength) {
maxLength = currentLength;
}
currentLength = 0;
}
}
if (currentLength > maxLength) {
maxLength = currentLength;
}
System.out.println(maxLength);
scanner.close();
}
```
---
### Problem
Given a string A of length N and a character B, replace all occurrences of B in string A with character '@'.
**Input Format**
First line is String A
Second line is Character B
**Example:**
abcad
a
**Output:**
@bc@d
---
# Question
Given string A,"interviewbit"
String B= "i"
replace all occurrences of B in string A with character '@'.
# Choices
- [x] @nterv@ewb@t
- [ ] i@terv@ewb@t
- [ ] @ntervewb@t
- [ ] I dont know
---
### Explanation
Modified string after Replacement of i at 1st, 7th, and 11th position is @nterv@ewb@t
---
### Idea:
1. Initialization: Create an empty string result.
2. Iterate: Loop through each character in the input string.
3. Check and Replace: If the current character matches the target character, append '@' to the result; otherwise, append the current character.
4. Final Result: Return the modified string (result).
### Psuedo code
```java
static String replaceCharacter(String str, char targetChar) {
String result = "";
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
if (currentChar == targetChar) {
result += '@';
} else {
result += currentChar;
}
}
return result;
}
```
---
### Problem:
Given a string, Count uppercase and lower case characters and print the values.
### Example:
String str="Hello World"
**Output:**
Uppercase: 2
Lowercase: 8
---
# Question
Given string ElePHant
Count number of Uppercase character first, then lowercase characters.
# Choices
- [ ] 3 lowercase<br>5 uppercase
- [x] 3 uppercase<br>5 lowercase
- [ ] 5 uppercase<br>9 lowercase
- [ ] I dont know
---
```java
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
String str = scn.next();
int c1 = 0;
int c2 = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
c1++;
} else if (ch >= 'a' && ch <= 'z') {
c2++;
}
}
System.out.println(c1);
System.out.println(c2);
}
```
---
### Problem:
Count number of characters of first string present in the second string.
### Example:
String A=abbd
String B=aabb
Output:
Number of common characters: 3(a,b,b)
### Pseudo Code
```java
static int countCommonCharacters(String str1, String str2) {
int count = 0;
for (int i = 0; i < str1.length(); i++) {
char currentChar = str1.charAt(i);
for (int j = 0; j < str2.length(); j++) {
if (currentChar == str2.charAt(j)) {
count++;
break; // Break the inner loop once a common character is found
}
}
}
return count;
}
```
------

View File

@@ -0,0 +1,480 @@
# 2D Matrices
### Definition
A 2D matrix is a specific type of 2D array that has a rectangular grid of numbers, where each number is called an element. It is a mathematical structure that consists of a set of numbers arranged in rows and columns.
2D matrix can be declared as:
```
int mat[N][M];
```
*int* is the datatype.
*mat* is the matrix name.
*N* is the number of rows in matrix.
*M* is the number of columns in matrix.
*mat[i][j]* represents the element present in the *i-th* row of *j-th* column.
Below is the pictorial representation of 2D matrix.
![](https://i.imgur.com/s1UeTtc.png)
**Note:** A matrix having *N* rows and *M* columns can store **N*M** elements.
### Question
Given a matrix of size NxM. What will be the index of the top right cell?
Choose the correct answer
**Choices**
- [ ] 0,0
- [ ] 0,M
- [ ] M-1,0
- [x] 0,M-1
### Question
Given a matrix of size NxM. What will be the index of the bottom right cell?
Choose the correct answer
**Choices**
- [ ] N,M
- [ ] M,N
- [x] N-1,M-1
- [ ] M-1,N-1
### Question 1 : Given a matrix print row-wise sum
**Problem Statement**
Given a 2D matrix mat[N][M], print the row-wise sum.
#### TestCase
**Input:**
```
mat[3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
```
**Output:**
```
10
26
42
```
### Approach
The approach is to traverse each row and while traversing take the sum of all the elements present in that row.
### Pseudocode:
```cpp
function SumRow(int mat[N][M]) {
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = 0; j < M; j++) {
sum = sum + mat[i][j];
}
print(sum);
}
}
```
### Question
What is the time and space complexity of to calculate row-wise sum for a matrix of size N*M?
Choose the correct answer
**Choices**
- [ ] TC: O(N^2), SC: O(n)
- [ ] TC: O(N^2), SC: O(1)
- [ ] TC: O(N^M), SC: O(n)
- [x] TC: O(N*M), SC: O(1)
Since we are iterating over all the elements just once, hence
Time Complexity: **O(N*M)**.
We are not using any extra space,
Space Complextiy: **O(1)**.
### Question 2 : Given a matrix print col-wise sum
Given a 2D matrix mat[N][M], print the column-wise sum.
**TestCase**
```
mat[3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
```
**Output**
```
15 18 21 24
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Approach
While traversing each column, we can calculate sum of all the elements present in that column.
### Pseudocode
```cpp
function SumColumn(int mat[N][M]) {
for (int j = 0; j < M; j++) {
int sum = 0;
for (int i = 0; i < N; i++) {
sum = sum + mat[i][j];
}
print(sum);
}
}
```
#### Complexity
Time Complexity: **O(N*M)**.
Space Complextiy: **O(1)**.
### Question 3 : Given a square matrix print diagonals
Given a matrix 2D square matrix mat[N][N], print diagonals.
How many main Diagonals are there in a square matrix?
$2.$
1. **Principal Diagonal:** From top left to bottom right.
3. **Anti Diagonal:** From top right to bottom left.
![](https://i.imgur.com/aJ4chji.png)
First, let's print **Principal Diagonal**
**TestCase**
```
mat[3][3] = {
{1,2,3},
{5,6,7},
{9,10,11}
}
```
**Output:**
```
1 6 11
```
### Question 3 Approach
#### Pseudocode:
```cpp
function PrintDiagonal(int mat[N][N]) {
int i = 0;
while (i < N) {
print(mat[i][i]);
i = i + 1;
}
}
```
### Question
Given a matrix of size NxN. What will be the time complexity to print the diagonal elements?
Chose the correct answer
**Choices**
- [ ] O(N*sqrt(N))
- [x] O(N)
- [ ] O(N^2)
- [ ] O(NlogN)
Since i starts at 0 and goes till N-1, hence there are total N iterations.
Time Complexity: **O(N)**.
Space Complextiy: **O(1)**.
### Given square matrix, print **Anti-diagonal**
**TestCase**
```
mat[3][3] = {
{1,2,3},
{5,6,7},
{9,10,11}
}
```
**Output:**
```
3 6 9
```
### Pseudocode:
```cpp
function PrintDiagonal(int mat[N][N]) {
int i = 0, j = N - 1;
while (i < N) {
print(mat[i][j]);
i++;
j--;
}
}
```
### Complexity
Time Complexity: **O(N)**.
Space Complextiy: **O(1)**.
### Question 4 Print diagonals in a matrix (right to left)
**Problem Statement**
Given a 2D matrix mat print all the elements diagonally from right to left
**TestCase**
```
mat[3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
```
**Output:**
```
1
2 5
3 6 9
4 7 10
8 11
12
```
### Question
Given a matrix of size N*M, how many Right to Left diagonals will be there?
Choose the correct Options
**Choices**
- [ ] N*M
- [ ] N+M
- [x] N+M-1
- [ ] N+M+1
1. M diagonals are starting from first row.
2. N diagonals start from last column.
3. There is a common diagonal at index 0, M-1.
So, total count = N+M-1 Let's take an example as shown below:
![](https://i.imgur.com/FLZq9TI.png)
### Question
Given a matrix of size 4x5, how many Right to Left diagonals will be there?
Choose the correct answer
**Choices**
- [x] 8
- [ ] 11
- [ ] 9
- [ ] 10
### Question 4 Approach
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
* For every start of the diagonal, how do the indices change when we iterate over it?
Row number increments by 1 and column number decrements by 1 as shown in the diagram.
![](https://i.imgur.com/2cR3BTh.png)
### Pseudocode
```cpp
function print_diagonal_elements(A[N][M]) {
//print all diagonals starting from 0th row
i = 0
for (j = 0; j < M; j++) {
s = i;
e = j;
while (s < N && e >= 0) {
print(A[s][e])
s++
e
}
print(“\n)
}
//print all diagonals starting from last column
j = M - 1
for (i = 1; i < N; i++) {
s = i;
e = j;
while (s < N && e >= 0) {
print(A[s][e])
s++
e
}
print(“\n)
}
}
```
### Question
Time Complexity of printing all the diagonals of a matrix of dimensions N X M?
Choose the correct answer
**Choices**
- [ ] O(N^2 * M^2)
- [ ] O(N^2 + M^2)
- [ ] O(N + M)
- [x] O(N * M)
### Question 5 : Transpose of a square matrix
**Problem Statement**
Given a square 2D matrix mat[N][N], find transpose.
**Transpose of matrix**
The transpose of a matrix is a new matrix obtained by interchanging the rows and columns of the original matrix.
**TestCase**
```
mat[3][3] = {
{1,2,3},
{5,6,7},
{9,10,11}
}
```
**Output:**
```
{
{1,5,9},
{2,6,10},
{3,7,11}
}
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Question 5 Approach
#### Observation
* After performing the transpose, what is same in the original matix and its transpose ?
The diagonal that starts from (0,0) is same.
![](https://i.imgur.com/9Xu3SYE.png)
* Along the diagonals, the elements have swapped their positions with corresponding elements.
#### PseudoCode
```cpp
function find_transpose(matrix[N][N]){
for(int i = 0; i < N; i++){
for(int j = i + 1; j < N; j++){
swap(matrix[i][j],matrix[j][i]);
}
}
}
```
**Note:** If we start j at 0, the matrix will come back to its original position.
### Question
What is the time and space complexity to find transpose of a square matrix?
Chose the correct answer
**Choices**
- [ ] TC: O(N), SC: O(n)
- [ ] TC: O(N^2), SC: O(n)
- [x] TC: O(N^2), SC: O(1)
- [ ] O(N), SC: O(1)
**Complexity**
Time Complexity: **O(N^2)**.
Space Complextiy: **O(1)**.
### Question 6 Rotate a matrix to 90 degree clockwise
**Problem Statement**
Given a matrix mat[N][N], rotate it to 90 degree clockwise.
**TestCase**
```
{
{1,2,3},
{4,5,6},
{7,8,9}
}
```
**Output**
```
{
{7,4,1},
{8,5,2},
{9,6,3}
}
```
### Question 6 Approach
### Hint:
* What if we first find the transpose of the matrix?
* Is there any relation between rotated matrix and transposed matrix ?
:::warning
Using the Hints, please take some time to think about the solution approach on your own before reading further.....
:::
### Observation:
Yes, if we reverse all the rows, then it will become rotated matrix.
The rotated matrix looks like:
![](https://i.imgur.com/B4p4avm.png)
**Transpose and rotated matrix:**
![](https://i.imgur.com/ZfdZaor.png)
#### PseudoCode
```cpp
Function rotate(int mat[N][N]) {
mat = transpose(mat);
for (int i = 0; i < N; i++) {
reverse(mat[i]);
}
return mat;
}
```
#### Complexity
Time Complexity: **O(N*N)**.
Space Complextiy: **O(1)**.

View File

@@ -0,0 +1,393 @@
# Sliding Window & Contribution Technique
## Problem 1 : Find the max sum out of all possible subarray of the array
### Problem Statement
Given an array of integers, find the total sum of all possible subarrays.
**#Note:** This question has been previously asked in *Google* and *Facebook*.
### Solution
* We can use the previous approach, where we calculated all sum subarray using Carry Forward technique.
* Instead of keeping track of maximum, we can simply add the sums in a variable.
### Pseudocode
```cpp
int sumOfAllSubarraySums(int arr[], int n) {
int total_sum = 0;
for (int i = 0; i < n; i++) {
int subarray_sum = 0;
for (int j = i; j < n; j++) {
subarray_sum += arr[j];
total_sum += subarray_sum;
}
}
return total_sum;
}
```
### Time and Space Complexity
* TC - O(n^2)
* SC - O(1)
## Problem 2 : Contribution Technique
We can optimize the above solution further by observing a pattern in the subarray sums.
Let's take the example array ``[1, 2, 3]``. The subarrays and their sums are:
```
[1] -> 1
[1, 2] -> 3
[1, 2, 3] -> 6
[2] -> 2
[2, 3] -> 5
[3] -> 3
Total Sum = 1+3+6+2+5+3 = 20
```
Instead of generating all subarrays, we can check that a particular element appears in how many subarrays and add its contribution that many times to the answer.
* the first element 1 appears in 3 subarrays: [1], [1, 2], and [1, 2, 3].
* the second element 2 appears in 4 subarrays: [2], [1, 2], [2, 3], and [1, 2, 3].
* the third element 3 appears in 3 subarrays: [3], [2, 3], and [1, 2, 3].
Total = $(1*3) + (2*4) + (3*3) = 20$
:::warning
Please take some time to think about "How to calculate the number of subarrays in which A[i] appears?" on your own before reading further.....
:::
### Question
In how many subarrays, the element at index 1 will be present?
A: [3, -2, 4, -1, 2, 6 ]
**Choices**
- [ ] 6
- [ ] 3
- [x] 10
- [ ] 8
**Explanation:** The subarrays in which the element at index 1 is present are -
[3, -2], [3, -2, 4], [3, -2, 4, -1], [3, -2, 4, -1, 2], [3, -2, 4, -1, 2, 6], [-2], [-2, 4], [-2, 4, -1], [-2, 4, -1, 2], [-2, 4, -1, 2, 6 ]. There are total 10 such subarrays.
### Question
In how many subarrays, the element at index 2 will be present?
A: [3, -2, 4, -1, 2, 6 ]
**Choices**
- [ ] 6
- [x] 12
- [ ] 10
- [ ] 8
**Explanation:** The subarrays in which the element at index 1 is present are -
[3, -2, 4], [3, -2, 4, -1], [3, -2, 4, -1, 2], [3, -2, 4, -1, 2, 6], [-2, 4], [-2, 4, -1], [-2, 4, -1, 2], [-2, 4, -1, 2, 6], [4], [4, -1], [4, -1, 2], [4, -1, 2, 6 ]. There are total 12 such subarrays.
### Find sum of all Subarrays sums continued
**Generalized Calculation -**
The start of such subarrays can be $0, 1, ..i$
The end of such subarrays can be $i, i+1, i+2, ...n-1$
Elements in range [0 i] = $i+1$
Elements in range [i n-1] = $n-1-i+1 = n-i$
Thus, the total number of subarrays containing arr[i] is i+1 multiplied by n-i.
This gives us the expression `(i+1) * (n-i)`.
We can use this pattern to compute the total sum of all subarrays in O(n) time complexity. The steps are as follows:
* Initialize a variable total_sum to zero.
* Iterate over all elements of the input array arr. For each element arr[i], compute `arr[i] * (i+1) * (n-i)` and add it to total_sum.
* Return total_sum as the output of the function.
#### Pseudocode
```cpp
int sumOfAllSubarraySums(arr[]) {
int n = arr.size();
int total_sum = 0;
// Iterate over all elements of the array and compute the sum of all subarrays containing that element
for (int i = 0; i < n; i++) {
total_sum += arr[i] * (i + 1) * (n - i);
}
return total_sum;
}
```
#### Time and Space Complexity
* TC - O(n)
* SC - O(1)
### Total number of subarrays of length K
Number of subarrays of length K = Total number of start indices of subarrays of length K.
| length (K) | start of first window | start of last window |
| -------- | -------- | -------- |
| 1 | 0 | N-1 |
| 2 | 0 | N-2 |
| 3 | 0 | N-3 |
| 4 | 0 | N-4 |
| K | 0 | N-K |
All start positions for length K, will be within range **[0 N-K]**. Therefore total is N-K+1.
Hence, total number of subarrays of length K = **N-K+1**.
### Question
Given N=7, K=4, what will be the total number of subarrays of len K?
**Choices**
- [ ] 3
- [x] 4
- [ ] 5
- [ ] 6
## Problem 3 Given an array, print start and end indices of subarrays of length K.
Given an array of size N, print start and end indices of subarrays of length K.
**Example**
If N=8, K=3
All start and end indices are
| start | end |
| ----- | ----- |
| 0 | 2 |
| 1 | 3 |
| 2 | 4 |
| 3 | 5 |
| 4 | 6 |
| 5 | 7 |
[start end] = K
end - start + 1 = K
end = K + start - 1
#### Pseudocode
```cpp=
//Iterate over all the start indices
for (int i = 0; i <= N - K; i++) {
int j = K + i - 1;
print(i, j);
}
```
> Note: Now we know how to iterate over windows of length K.
## Problem 4 : Given an array, print maximum subarray sum with length K
Given an array of N elements. Print maximum subarray sum for subarrays with length = K.
**Example**
```
N=10 K=5
```
| -3 | 4 | -2 | 5 | 3 | -2 | 8 | 2 | -1 | 4 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |:---:|
**Explanation**
| s | e | sum |
| -------- | -------- | -------- |
| 0 | 4 | 7 |
| 1 | 5 | 8 |
| 2 | 6 | 12 |
| 3 | 7 | 16 |
| 4 | 8 | 10 |
| 5 | 9 | 11 |
Maximum: **16**
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Problem 4 : Bruteforce Approach
We have to calculate the sum of all subarrays of size k and find the maximum out of them
#### Pseudeocode
```cpp
function maxSubarrayOfLengthK(A[], N, K) {
ans = INT_MIN
//first window
i = 0
j = k - 1
while (j < N) {
sum = 0
for (idx = start; idx <= end; idx++) {
sum += A[idx]
}
ans = max(sum, ans)
//going to next subarray of length k
i++
j++
}
print(ans)
}
```
#### Complexity
For what value of k will the iterations be highest ?
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/030/original/1.png?1681232198)
:::warning
Please take some time to think about the optimised solution approach on your own before reading further.....
:::
## Problem 4 : Optimized Approach using Prefix Sum Array
We can use **Prefix Sum Array** since we have to find sum within a range.
### Pseudeocode
```cpp
function maxSubarrayOfLengthK(A[], N, K) {
// calculate prefix sum array
pf[N]
pf[0] = A[0]
for (idx = 1; idx < N; idx++) {
pf[idx] = pf[idx - 1] + A[idx];
}
ans = INT_MIN
i = 0
j = K - 1
// calculate for each pair of indicies
while (j < N) {
sum = pf[j] - (i == 0 ? 0 : pf[i - 1])
ans = max(sum, ans)
i++
j++
}
print(ans)
}
```
### Question
What is Time Complexity and Space Complexity respectively?
**Choices**
- [ ] O(N^2) and O(N)
- [x] O(N) and O(N)
- [ ] O(N) and O(N^2)
- [ ] O(1) and O(N)
---
### Problem 4 Optimized Approach : using Sliding Window
We want to reduce the space complexity without modifying the given array, but how?
#### Observations
* We can get sum of next subarray using current subarray sum as follows:-
* By adding a new element to current sum.
* By subtracting the first element of current subarray.
Given array :-
| -3 | 4 | -2 | 5 | 3 | -2 | 8 | 2 | -1 | 4 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |:---:|
First subarray from 0 to 4:-
| -3 | 4 | -2 | 5 | 3 |
| --- | --- | --- | --- | --- |
Converting first to second subarray :-
| <span style="color:red"> ~~-3~~ </span> | 4 | -2 | 5 | 3 | <span style="color:green"> -2 </span> |
| --- | --- | --- | --- | --- | --- |
Based upon above observation can we say:-
<div class="alert alert-block alert-warning">
sum of all elements of next subarray = sum of elements of current subarray - first element of current subarray + new element
</div>
This approach is known as **Sliding window approach**.
#### Dry Run
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/066/original/Screenshot_%286%29.png?1681239141)
**We can clearly observe the window sliding in above run.**
#### Pseudeocode
```cpp
function maxSubarrayOfLengthK(A[], N, K) {
ans = INT_MIN
i = 0
j = K - 1
sum = 0 // here k iterations
for (int idx = i; idx <= j; idx++) {
sum += A[idx]
}
ans = max(sum, ans)
j++
i++
while (j < N) {
sum = sum + A[j] - A[i - 1]
ans = max(sum, ans)
// here N-k iterations
i++
j++
}
print(ans)
}
```
***Time Complexity : O(N)**
**Space Complexity : O(1)***
## Observations for solving problems on Subarrays.
### Observations
Following are the observations that can be useful when solving problems related to subarrays:
* Subarrays can be visualized as contiguous part of an array, where the starting and ending indices determine the subarray.
* The total number of subarrays in an array of length n is n*(n+1)/2.
* To print all possible subarrays, O(n^3) time complexity is required.
* The sum of all subarrays can be computed in O(n^2) time complexity and O(1) space complexity by using Carry Forward technique.
* The sum of all subarrays can be computed in O(n^2) time complexity and O(n) space complexity using the prefix sum technique.
* The number of subarrays containing a particular element arr[i] can be computed in O(n) time complexity and O(1) space complexity using the formula (i+1)*(n-i). This method is called `Contribution Technique`.

View File

@@ -0,0 +1,400 @@
# Carry Forward & Subarrays
## Problem 1 : Count of Pairs ag
Given a string **s** of lowercase characters, return the **count of pairs (i,j)** such that **i < j** and **s[ i ] is 'a'** and **s[ j ] is 'g'**.
### Example 1
```plaintext
String s = "abegag"
Ans = 3
```
### Explanation:
Here, [i,j] such that i<j and s[i] is 'a' and s[j] is 'g' are [0,3], [0,5] and [4,5]. So ans would be 3.
### Question
What is the count of **a,g** pairs in the array:-
s = **"acgdgag"**
**Choices**
- [x] 4
- [ ] 3
- [ ] 5
- [ ] 2
**Explanation:**
Here, [i,j] such that i<j and s[i] is 'a' and s[j] is 'g' are [0,2], [0,4], [0,6] and [5,6]. So ans would be 4.
### Question
How many **ag** pairs are in this string?
s = **"bcaggaag"**
**Choices**
- [x] 5
- [ ] 4
- [ ] 3
- [ ] 6
**Explanation:**
Here, [i,j] such that i<j and s[i] is 'a' and s[j] is 'g' are [2,3], [2,4], [2,7], [5,7] and [6,7]. So ans would be 5.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
### Problem 1 : Brute Force Solution
For every **'a'**, we need to find the count of **g's** on the right side of **a**. So, we need to have nested loops.
**Pseudocode**
```cpp
int count_ag(string s) {
int result = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'a') {
for (int j = i + 1; j < n; j++) {
if (s[j] == 'g') {
result++;
}
}
}
}
return result;
}
```
#### Time and Space Complexity
-- TC - $O(n^2)$
-- SC - $O(1)$
### Problem 1 Optimised solution
#### Observation:
* For every **'g'**, we need to know the count of **'a'** on left side of **'g'**.
* We will store the count of **'a'** and whenever **'g'** is encountered, we will add the count of **'a'** to the result.
#### Dry Run
Example: **"acbagkagg"**
![reference link](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/986/original/dry.jpeg?1682663462)
#### Pseudocode
```cpp
int count_ag(string s) {
int result = 0;
int count_a = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'a') {
count_a++;
} else if (s[i] == 'g') {
result += count_a;
}
}
return result;
}
```
#### Time and Space Complexity
What will be T.C and S.C for this approach?
-- TC - $O(n)$
-- SC - $O(1)$
## Introduction to Subarrays
### Definition
A subarray is a contiguous part of an array. It is formed by selecting a range of elements from the array. A subarray can have one or more elements and must be a contiguous part of the original array.
### Example
Consider the following array of integers:
| 4 | 1 | 2 | 3 | -1 | 6 | 9 | 8 | 12 |
| - | - | - | - | - | - | - | - | - |
* `2, 3, -1, 6` is a subarray of length 4.
* `9` is a subarray of single element.
* `4, 1, 2, 3, -1, 6, 9, 8, 12` is a subarray consisting of all the array elements.
* `4, 12` is **not** a subarray because loop does not count as subarray.
* `1, 2, 6` is **not** a subarray beacuse the array elements must be contiguous.
* `3, 2, 1, 4` is **not** a subarray because order of the elements in a subarray should be same as in the array.
### Question
A[] = { 2, 4, 1, 6, -3, 7, 8, 4}
Which of the following is a valid subarray?
**Choices**
- [ ] {1, 6, 8}
- [ ] {1, 4}
- [ ] {6, 1, 4, 2}
- [x] {7, 8, 4}
**Explanation:** {1, 6, 8} & {1, 4} are not contiguous parts of array. {6, 1, 4, 2} is not in the same order as in original array. Only {7, 8, 4} is a valid subarray.
### Representation of a Subarray
#### Representation of a Subarray
A Subarray can be uniquely represented in following ways:
1. By specifying the `start` and `end` index of the subarray.
2. By specifying the `start` index and `length` of the subarray.
If we consider the same array from the above example,
| 4 | 1 | 2 | 3 | -1 | 6 | 9 | 8 | 12 |
| - | - | - | - | - | - | - | - | - |
The subarray `2, 3, -1, 6` can be represented as
* the range of elements starting at index `2` and ending at index `5` (0-based indexing).
* the range of elements having length of `4` with start index as `2`.
### Question
How many subarrays of the following array start from index 0
[4, 2, 10, 3, 12, -2, 15]
**Choices**
- [ ] 6
- [x] 7
- [ ] 21
- [ ] 36
[4] (starting from index 0)
[4, 2]
[4, 2, 10]
[4, 2, 10, 3]
[4, 2, 10, 3, 12]
[4, 2, 10, 3, 12, -2]
[4, 2, 10, 3, 12, -2, 15]
Therefore, there are a total of 7 subarrays that start from index 0.
### Question
How many subarrays of the following array start from index 1
[4, 2, 10, 3, 12, -2, 15]
**Choices**
- [x] 6
- [ ] 7
- [ ] 21
- [ ] 36
[2] (starting from index 1)
[2, 10]
[2, 10, 3]
[2, 10, 3, 12]
[2, 10, 3, 12, -2]
[2, 10, 3, 12, -2, 15]
Therefore, there are a total of 6 subarrays that start from index 1.
### Formula to count no. of subarrays
No. of subarrays starting from index 0 = n
No. of subarrays starting from index 1 = n-1
No. of subarrays starting from index 2 = n-2
No. of subarrays starting from index 3 = n-3
...........
...........
No. of subarrays starting from index n-1 = 1
So, Using the formula for the sum of an arithmetic series, total number of subarrays = n + (n-1) + (n-2) + (n-3) + . . . . . . + 3 + 2 + 1 = n(n+1)/2.
``` cpp
total = n(n + 1) / 2
```
### Print the subarray of the array that starts from the start index and ends at the end index
#### Problem Statement
Given an array of integers and two indices, a start index and an end index, we need to print the subarrays of the array that starts from the start index and ends at the end index (both inclusive).
#### Solution
To solve this problem, we can simply iterate over the elements of the array from the start index to the end index (both inclusive) and print each element.
#### Pseudocode
```cpp
void printSubarray(int arr[], int start, int end) {
for (int i = start; i <= end; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
```
#### Time and Space Complexity
What will be T.C and S.C for the above approach?
* TC - O(n)
* SC - O(1)
### Print all possible subarrays of the array
**Problem Statement:**
Given an array of integers, we need to print all possible subarrays of the array.
**Example**
```cpp
Input: [1, 2, 3]
Output:
[1]
[1, 2]
[1, 2, 3]
[2]
[2, 3]
[3]
```
#### Solution
To solve this problem, we can generate all possible subarrays of the array using two nested loops.
* The outer loop iterates over the starting index of the subarray.
* The inner loop iterates over the ending index of the subarray.
* At each iteration, we print the subarray from the starting index to the ending index.
#### Pseudocode
```cpp
void printSubarrays(int arr[], int n) {
// Generate all possible subarrays
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// Print the current subarray
for (int k = i; k <= j; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
}
```
#### TC & SC:
TC - O(N^3)
SC - O(1)
### Problem 2 : Max And Min
**Given an array of N integers, return the length of smallest subarray which contains both maximum and minimum element of the array.**
### Question
What is the length of the smallest subarray which has both, the max and the min of the array?
| 2 | 2 | 6 | 4 | 5 | 1 | 5 | 2 | 6 | 4 | 1|
| --| --| --| --| --| --| --| --| --| --| --|
**Choices**
- [ ] 4
- [ ] 5
- [ ] 2
- [x] 3
Here, minimum element is 1 and maximum is 6. Smallest subarray which contains both is from index 8 to index 10 which is of length 10-8+1=3.
**Another Example**
```plaintext
A[ ] = { 1, 2, 3, 1, 3, 4, 6, 4, 6, 3}
Ans = 4
```
**Explanation:**
Here, minimum element is 1 and maximum is 6. Smallest subarray which contains both is from index 3 to index 6 which is of length 6-3+1=4.
:::warning
Please take some time to think about the brute force approach on your own before reading further.....
:::
### Problem 2 : Brute Force Solution
Check all subarrays and find the answer.
-- TC - $O(n^3)$
-- SC - $O(1)$
Note: It can be reduced to $O(n^2)$ since we can check miniumum and maximum in a subarray in second loop itself.
### Problem 2 : Optimised Solution Observation
* The answer subarray must have exactly one instance of minimum element and one instance of maximum element since we want the length to be minimum.
* The minimum and maximum value must be present at the corners of the subarray.
* So, basically we are looking for subarray **which starts with maximum value and ends with closest minimum value or which starts with minimum value and ends with closest maximum value.**
**NOTE:**
1. We can search a **min** for a **max** or vice versa, only in a single direction.
1. We don't have to consider all the pairs of min and max but look for closest pair, since we want to find smallest such subarray.
2. So we can keep track of the last found min and a last found max index.
#### Dry Run
```plaintext
A[ ] = { 2, 2, 6, 4, 5, 1, 5, 2, 6, 4, 1 }
```
Initially,
last_min_index = **-1**
last_max_index = **-1**
ans = **INT_MAX**
minValue = **1**
maxValue = **6**
| i | A[i] | last_min_index |last_max_index|ans|
| -------- | -------- | -------- |-------- |-------- |
| 0| 2| -1| -1| INT_MAX |
| 1| 2| -1| -1| INT_MAX |
| 2| 6| -1| 2| INT_MAX |
| 3| 4| -1| 2| INT_MAX |
| 4| 5| -1| 2| INT_MAX |
| 5| 1| 5| 2| 5-2+1 = 4|
| 6| 5| 5| 2| 4|
| 7| 2| 5| 2| 4|
| 8| 6| 5| 8| 4|
| 9| 4| 5| 8| 4|
| 10| 1| 10| 8|10-8+1 = 3|
**So final ans would be 3.**
#### Pseudocode
```cpp
int minSubarray(int A[], int n) {
// find maximum and minimum
// values in the array
int minValue = minOfArray(A);
int maxValue = maxOfArray(A);
int last_min_index = -1, last_max_index = -1, ans = INT_MAX;
for (int i = 0; i < N; i++) {
if (A[i] == minValue) {
last_min_index = i;
if (last_max_index != -1) {
ans = min(ans, i - last_max_index + 1);
}
}
if (A[i] == maxValue) {
last_max_index = i;
if (last_min_index != -1) {
ans = min(ans, i - last_min_index + 1);
}
}
}
return ans;
}
```
#### Time and Space Complexity
What will be T.C and S.C for this approach?
-- TC - $O(n)$
-- SC - $O(1)$

View File

@@ -0,0 +1,599 @@
# Prefix Sum
## Problem Description
Given N elements and Q queries. For each query, calculate sum of all elements from L to R [0 based index].
### Example:
A[ ] = [-3, 6, 2, 4, 5, 2, 8, -9, 3, 1]
Queries (Q)
| L | R | Solution |
| -------- | -------- | -------- |
| 4 | 8 | 9 |
| 3 | 7 | 10 |
| 1 | 3 | 12 |
| 0 | 4 | 14 |
| 7 | 7 | -9 |
:::info
Before moving forward, think about the brute force solution approach.....
:::
## Brute Force Approach
For each query Q, we iterate and calculate the sum of elements from index L to R
### Pseudocode
```cpp
Function querySum(Queries[][], Array[], querySize, size) {
for (i = 0; i < Queries.length; i++) {
L = Queries[i][0]
R = Queries[i][1]
sum = 0
for (j = L; j <= R; j++) {
sum += Array[j]
}
print(sum)
}
}
```
***Time Complexity : O(N * Q)**
**Space Complexity : O(1)***
>Since Time complexity of this approach is O(N * Q) then in a case where there are 10^5 elements & 10^5 queries where each query is (L=0 and R=10^5-1) we would encounter **TLE** hence this approach is Inefficient
### Question
Given the scores of the 10 overs of a cricket match
2, 8, 14, 29, 31, 49, 65, 79, 88, 97
How many runs were scored in just 7th over?
**Choices**
- [x] 16
- [ ] 20
- [ ] 18
- [ ] 17
Total runs scored in over 7th : 65 - 49 = 16
(score[7]-score[6])
### Question
Given the scores of the 10 overs of a cricket match
2, 8, 14, 29, 31, 49, 65, 79, 88, 97
How many runs were scored from 6th to 10th over(both included)?
**Choices**
- [x] 66
- [ ] 72
- [ ] 68
- [ ] 90
Total runs scored in over 6th to 10th : 97 - 31 = 66
(score[10]-score[5])
### Question
Given the scores of the 10 overs of a cricket match
2, 8, 14, 29, 31, 49, 65, 79, 88, 97
How many runs were scored in just 10th over?
**Choices**
- [ ] 7
- [ ] 8
- [x] 9
- [ ] 10
Total runs scored in over 6th to 10th : 97 - 88 = 9
(score[10]-score[9])
### Question
Given the scores of the 10 overs of a cricket match
2, 8, 14, 29, 31, 49, 65, 79, 88, 97
How many runs were scored from 3rd to 6th over(both included)?
**Choices**
- [ ] 70
- [ ] 40
- [ ] 9
- [x] 41
Total runs scored in over 3rd to 6th : 49-8 = 41
(score[6]-score[2])
### Question
Given the scores of the 10 overs of a cricket match
2, 8, 14, 29, 31, 49, 65, 79, 88, 97
How many runs were scored from 4th to 9th over(both included)?
**Choices**
- [ ] 75
- [ ] 80
- [x] 74
- [ ] 10
Total runs scored in over 4th to 9th : 88 - 14 = 74
(score[9]-score[3])
:::success
What do you observe from above cricket example ? Take some time and think about it....
:::
### Observation for Optimised Solution
#### Observation
* On observing cricket board score, we can say that queries can be answered in just constant time since we have cummulative scores.
* In the similar manner, if we have cummulative sum array for the above problem, we should be able to answer it in just constant time.
* We need to create cumulative sum or <B>prefix sum array</B> for above problem.
</div>
## How to create Prefix Sum Array ?
### Definition
pf[i] = sum of all elements from 0 till ith index.
<!-- </div> -->
### Example
Step1:-
Provided the intial array:-
| 2 | 5 | -1 | 7 | 1 |
| --- | --- | --- | --- | --- |
We'll create prefix sum array of size 5 i.e. size equal to intial array.
`Initialise pf[0] = initialArray[0]`
| 2 | - | - | - | - |
| --- | --- | --- | --- | --- |
| 2 | 7 | - | - | - |
| --- | --- | --- | --- | --- |
| 2 | 7 | 6 | - | - |
| --- | --- | --- | --- | --- |
| 2 | 7 | 6 | 13 | - |
| --- | --- | --- | --- | --- |
| 2 | 7 | 6 | 13 | 14 |
| --- | --- | --- | --- | --- |
Finally we have the prefix sum array :-
| 2 | 7 | 6 | 13 | 14 |
| --- | --- | --- | --- | --- |
### Question
Calculate the prefix sum array for following array:-
| 10 | 32 | 6 | 12 | 20 | 1 |
| --- | --- | --- | --- | --- |:---:|
**Choices**
- [x] `[10,42,48,60,80,81]`
- [ ] `[10,42,49,60,79,81]`
- [ ] `[42,48,60,80,81,10]`
- [ ] `[15,43,58,61,70,82]`
### Brute Force Code to create Prefix Sum Array and observation for Optimisation
```cpp
pf[N]
for (i = 0; i < N; i++) {
sum = 0;
for (int j = 0; j <= i; j++) {
sum = sum + A[j]
}
pf[i] = sum;
}
```
## Observation for Optimising Prefix Sum array calculations
pf[0] = A[0]
pf[1] = A[0] + A[1]
pf[2] = A[0] + A[1] + A[2]
pf[3] = A[0] + A[1] + A[2] + A[3]
pf[4] = A[0] + A[1] + A[2] + A[3] + A[4]
* Can we observe that we are making redundant calculations?
* We could utilise the previous sum value.
* pf[0] = A[0]
* pf[1] = pf[0] + A[1]
* pf[2] = pf[1] + A[2]
* pf[3] = pf[2] + A[3]
* pf[4] = pf[3] + A[4]
* **Generalised Equation is:** ```pf[i] = pf[i-1] + A[i]```
## Optimised Code:
```cpp
pf[N]
pf[0] = A[0];
for (i = 1; i < N; i++) {
pf[i] = pf[i - 1] + A[i];
}
```
* Time Complexity: O(N)
### How to answer the Queries ?
:::success
Now that we have created prefix sum array...finally how can we answer the queries ? Let's think for a while...
:::
A[ ] = [-3, 6, 2, 4, 5, 2, 8, -9, 3, 1]
pf[ ] =[-3, 3, 5, 9, 14, 16, 24, 15, 18, 19]
| L | R | Solution | |
| -------- | -------- | -------- | -------- |
| 4 | 8 | pf[8] - pf[3] | 18 - 9 = 9 |
| 3 | 7 | pf[7] - pf[2] |15 - 5 = 10 |
| 1 | 3 | pf[3] - pf[0] |9 - (-3) = 12 |
| 0 | 4 | pf[4] |14 |
| 7 | 7 | pf[7] - pf[6] |15 - 24 = -9 |
### Generalised Equation to find Sum:
sum[L R] = pf[R] - pf[L-1]
Note: if L==0, then sum[L R] = pf[R]
### Complete code for finding sum of queries using Prefix Sum array:
```cpp
Function querySum(Queries[][], Array[], querySize, size) {
//calculate pf array
pf[N]
pf[0] = A[0];
for (i = 1; i < N; i++) {
pf[i] = pf[i - 1] + A[i];
}
//answer queries
for (i = 0; i < Queries.length; i++) {
L = Queries[i][0];
R = Queries[i][1];
if (L == 0) {
sum = pf[R]
} else {
sum = pf[R] - pf[L - 1];
}
print(sum);
}
}
```
***Time Complexity : O(N+Q)**
**Space Complexity : O(N)***
### Space Complexity can be further optimised if you modify the given array.
```cpp
Function prefixSumArrayInplace(Array[], size) {
for (i = 1; i < size; i++) {
Array[i] = Array[i - 1] + Array[i];
}
}
```
***Time Complexity : O(N)**
**Space Complexity : O(1)***
### Problem 1 : Sum of even indexed elements
Given an array of size N and Q queries with start (s) and end (e) index. For every query, return the sum of all **even indexed elements** from **s to e**.
**Example**
```plaintext
A[ ] = { 2, 3, 1, 6, 4, 5 }
Query :
1 3
2 5
0 4
3 3
Ans:
1
5
7
0
```
### Explanation:
* From index 1 to 3, sum: A[2] = 1
* From index 2 to 5, sum: A[2]+A[4] = 5
* From index 0 to 4, sum: A[0]+A[2]+A[4] = 7
* From index 3 to 3, sum: 0
### Brute Force
How many of you can solve it in $O(N*Q)$ complexity?
**Idea:** For every query, Iterate over the array and generate the answer.
:::warning
Please take some time to think about the Optimised approach on your own before reading further.....
:::
### Problem 1 : Observation for Optimisation
Whenever range sum query is present, we should think in direction of **Prefix Sum**.
**Hint 1:** Should we find prefix sum of entire array?
**Expected:** No, it should be only for even indexed elements.
**We can assume that elements at odd indices are 0 and then create the prefix sum array.**
Consider this example:-
```
A[] = 2 3 1 6 4 5
PSe[] = 2 2 3 3 7 7
```
> Note: PSe</sub>[i] denotes sum of all even indexed elements from 0 to ith index.
If **i is even** we will use the following equation :-
<div class="alert alert-block alert-warning">
PSe</sub>[i] = PSe</sub>[i-1] + A[i]
</div>
If **i is odd** we will use the following equation :-
<div class="alert alert-block alert-warning">
PSe[i] = PSe[i-1]
</div>
### Question
Construct the Prefix Sum for even indexed elements for the given array
[2, 4, 3, 1, 5]
**Choices**
- [ ] 1, 6, 9, 10, 15
- [x] 2, 2, 5, 5, 10
- [ ] 0, 4, 4, 5, 5
- [ ] 0, 4, 7, 8, 8
We will assume elements at odd indices to be 0 and create a prefix sum array taking this assumption.
So ```2 2 5 5 10``` will be the answer.
### Problem 1 : Pseudocode
```cpp
void sum_of_even_indexed(int A[], int queries[][], int N) {
// prefix sum for even indexed elements
int PSe[N];
if (A[0] % 2 == 0) PSe[0] = A[0];
else PSe[0] = 0;
for (int i = 0; i < N; i++) {
if (i % 2 == 0) {
PSe[i] = PSe[i - 1] + A[i];
} else {
PSe[i] = PSe[i - 1];
}
}
for (int i = 0; i < queries.size(); i++) {
s = queries[i][0]
e = queries[i][1]
if (s == 0) {
print(PSe[e])
} else {
print(PSe[e] - PSe[s - 1])
}
}
}
```
### Complexity
-- TC - $O(n)$
-- SC - $O(n)$
### Problem 1 Extension : Sum of all odd indexed elements
If we have to calculate the sum of all ODD indexed elements from index **s** to **e**, then Prefix Sum array will be created as follows -
> if i is odd
<div class="alert alert-block alert-warning">
PSo[i] = PSo[i-1] + array[i]
</div>
> and if i is even :-
<div class="alert alert-block alert-warning">
PSo[i] = PSo[i-1]
</div>
### Problem 2 : Special Index
Given an array of size N, count the number of special index in the array.
**Note:** **Special Indices** are those after removing which, sum of all **EVEN** indexed elements is equal to sum of all **ODD** indexed elements.
**Example**
```plaintext
A[ ] = { 4, 3, 2, 7, 6, -2 }
Ans = 2
```
We can see that after removing 0th and 2nd index **S<sub>e</sub>** and **S<sub>o</sub>** are equal.
| i | A[i] | S<sub>e</sub> | S<sub>o</sub> |
| --- |------------------| ----- | ----- |
| 0 | { 3, 2, 7, 6, -2 } | 8 | 8 |
| 1 | { 4, 2, 7, 6, -2 } | 9 | 8 |
| 2 | { 4, 3, 7, 6, -2 } | 9 | 9 |
| 3 | { 4, 3, 2, 6, -2 } | 4 | 9 |
| 4 | { 4, 3, 2, 7, -2 } | 4 | 10 |
| 5 | { 4, 3, 2, 7, 6 } | 12 | 10 |
**Note: Please keep a pen and paper with you for solving quizzes.**
### Question
What will be the sum of elements at **ODD indices** in the resulting array after removal of **index 2** ?
A[ ] = [ 4, 1, 3, 7, 10 ]
**Choices**
- [ ] 8
- [ ] 14
- [x] 11
- [ ] 9
After removal of element at **index 2**, elements after index 2 has changed their positions:
Sum of elements at **ODD** indices from **[0 to 1]** + Sum of elements at **EVEN** indices from **[3 to 4]** =
1 + 10 = 11
### Question
What will be the sum of elements at **ODD indices** in the resulting array after removal of **index 3** ?
A[ ] = { 2, 3, 1, 4, 0, -1, 2, -2, 10, 8 }
**Choices**
- [ ] 8
- [x] 15
- [ ] 12
- [ ] 21
**Explanation:**
After removal of element at index 3, elements after index 3 has changed their positions:
Sum of elements at **ODD** indices from **[0 to 2]** index + Sum of elements at **EVEN** indices from **[4 to 9]** = A[1]+A[4]+A[6]+A[8] = **3+0+2+10 = 15**
### Question
What will be the sum of elements at EVEN indices in the resulting array after removal of index 3 ?
[2, 3, 1, 4, 0, -1, 2, -2, 10, 8]
**Choices**
- [ ] 15
- [x] 8
- [ ] 10
- [ ] 12
After removal of element at index 3, elements are after index 3 has changed their positions:
Sum of elements at **EVEN** indices from **[0 to 2]** index + Sum of elements at **ODD** indices from **[4 to 9]** = A[0]+A[2]+A[5]+A[7]+A[9] = 2+1+(-1)+(-2)+8 = 8
:::warning
Please take some time to think about the optimised solution approach on your own before reading further.....
:::
### Problem 2 : Observation for Optimised Approach
* Suppose, we want to check if **i** is a **Special Index**.
* Indices of elements present on the left side of i will remain intact while indices of elements present on the right side of element i will get changed.
* Elements which were placed on odd indices will shift on even indices and vice versa.
For example:
```plaintext
A[ ] = { 2, 3, 1, 4, 0, -1, 2, -2, 10, 8 }
```
Sum of **ODD** indexed elements after removing element at index 3 =
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/820/original/oddsum.png?1683629378" width=500 />
Sum of **EVEN** indexed elements after removing element at index 3 =
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/822/original/evensum.png?168362945" width=500 />
### Approach
* Create **Prefix Sum** arrays for **ODD** and **EVEN** indexed elements.
* Run a loop for $i$ from 0 to n 1, where n is the size of the array.
* For every element check whether **So** is equal to **Se** or not using the above equations.
* Increment the count if Se is equal to So.
**NOTE:** Handle the case of $i=0$.
### Pseudocode
```cpp
int count_special_index(int arr[], int n) {
// prefix sum for even indexed elements
int PSe[n];
// prefix sum for odd indexed elements
int PSo[n];
//Say we have already calculated PSe and PSo
//Code to find Special Indices
int count = 0;
for (int i = 0; i < n; i++) {
int Se, So;
if (i == 0) {
Se = PSo[n - 1] - PSo[i]; //sum from [i+1 n-1]
So = PSe[n - 1] - PSe[i]; //sum from [i+1 n-1]
} else {
Se = PSe[i - 1] + PSo[n - 1] - PSo[i]; //sum even from [0 to i-1] and odd from [i+1 n-1]
So = PSo[i - 1] + PSe[n - 1] - PSe[i]; //sum odd from [0 to i] and even from [i+1 n-1]
}
if (Se == So) {
count++;
}
}
return count;
}
```
### Complexity
-- TC - $O(n)$
-- SC - $O(n)$

View File

@@ -0,0 +1,484 @@
# Bit Manipulation Basics
## Decimal Number System
* The decimal system, also known as the base-10 system, is the number system we use in our everyday lives.
* It is called base-10 because a single digit can take 10 values from 0 to 9.
The position of each digit in a decimal number represents a different power of 10.
For example,
```cpp
342 = 300 + 40 + 2 = 3*10^2 + 4*10^1 + 2*10^0
```
```cpp
2563 = 2000 + 500 + 60 + 3 = 2*10^3 + 5*10^2 + 6*10^1 + 3*10^0
```
---
## Binary Number System
* The binary system, also known as the base-2 system, is used in digital electronics and computing.
* It has only two digits, which are 0 and 1.
In the binary system, each digit represents a different power of 2.
For example,
```cpp
110 = 1*2^2 + 1*2^1 + 0*2^0 = 4 + 2 + 0 = 6
```
```cpp
1011 = 1*2^3 + 0*2^2 1*2^1 + 1*2^0 = 8 + 0 + 2 + 1 = 11
```
---
### Binary to Decimal Conversion
For this conversion, we need to multiply each digit of the binary number by the corresponding power of 2, and then add up the results.
**Example 1:**
Convert binary number 1101 to decimal number.
```
Starting from the rightmost digit, we have:
1 * 2^0 = 1
0 * 2^1 = 0
1 * 2^2 = 4
1 * 2^3 = 8
Adding up the results, we get:
1 + 0 + 4 + 8 = 13
Therefore, the decimal equivalent of the binary number 1101 is 13.
```
**Example 2:**
Convert binary number 10101 to decimal number.
- Starting from the rightmost digit, we have:
```
1 * 2^0 = 1
0 * 2^1 = 0
1 * 2^2 = 4
0 * 2^3 = 0
1 * 2^4 = 16
```
- Adding up the results, we get:
```
1 + 0 + 4 + 0 + 16 = 21
```
Therefore, the decimal equivalent of the binary number 10101 is 21.
---
### Question
What is the decimal representation of this binary number: 1011010
**Choices**
- [ ] 45
- [x] 90
- [ ] 94
- [ ] 130
**Explanation:**
Starting from the rightmost digit, we have:
0 * 2^0 = 0
1 * 2^1 = 2
0 * 2^2 = 0
1 * 2^3 = 8
1 * 2^4 = 16
0 * 2^5 = 0
1 * 2^6 = 64
Adding up the results, we get: 0 + 2 + 0 + 8 + 16 + 0 + 64 = 90
Therefore, the decimal representation of the binary number 1011010 is 90.
---
### Decimal to Binary Conversion
We can solve it using long division method, for which we need to repeatedly divide the decimal number by 2 and record the remainder until the quotient becomes 0.
**Example:**
Convert decimal number 20 to binary number.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/146/original/bitmanipulationimage1.png?1683885852" width="40%" height="20%">
---
### Question
What is the binary representation of 45 ?
**Choices**
- [ ] 101100
- [ ] 101110
- [ ] 101111
- [x] 101101
**Explanation:** Here are the steps to convert decimal number 45 to binary:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/147/original/bitmanipulationimage2.png?1683885879" width="40%" height="20%">
---
### Addition of Decimal Numbers
**Example -**
```cpp
Calculate => (368 + 253)
```
<img
src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/817/original/Screenshot_2023-05-09_at_3.57.38_PM.png?1683628220" width="30%" >
**Explanation:**
* Start by adding the rightmost digits: 8 + 3 = 11 (digit = 11%10 = 1, carry 11/10 = 1)
* Next column: 1 + 6 + 5 = 12 (digit = 12%10 = 2, carry 12/10 = 1)
* Final column: 1 + 3 + 4 = 8 (digit = 8%10 = 8, carry 8/10 = 0)
Therefore, answer is 821.
---
### Addition of Binary Numbers
**Example 1:**
| | 1 | 0 | 1 | 0 | 1 |
|---|---|---|---|---|---|
| + | | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 | 1 | 0 |
**Explanation:**
d = answer digit, c = carry
* From right, 1 + 1 = 2 (d = 2%2=0, c = 2/2 = 1)
* Next: 1 + 0 + 0 = 1 (d = 1%2=1, c = 1/2 = 0)
* Next: 0 + 1 + 1 = 2 (d = 2%2=0, c = 2/2 = 1)
* Next: 1 + 0 + 1= 2 (d = 2%2=0, c = 2/2 = 1)
* Final: 1 + 1 = 2 (d = 2%2=0, c = 2/2 = 1)
* Finally, 1 carry is remaining, so write 1.
The result is 100010 in binary.
**Example 2:**
| | 1 | 1 | 0 | 1 | 0 | 1 |
|---|---|---|---|---|---|---|
| + | 1 | 0 | 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 1 | 0 | 1 | 1 |
**Explanation:**
d = answer digit, c = carry
* From Right: 1 + 0 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Next column: 0 + 0 + 1 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Next column: 0 + 1 + 1 = 2 (d: 2%2 = 0, c: 2/2 = 1)
* Next column: 1 + 0 + 0 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Next column: 0 + 1 + 0 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Next column: 0 + 1 + 1 = 2 (d: 2%2 = 0, c: 2/2 = 1)
* Finally, 1 carry is remaining, so write 1.
The result is 1011011 in binary.
---
### Question
What is the sum of these binary numbers: 10110 + 00111
**Choices**
- [ ] 11111
- [ ] 10101
- [ ] 11011
- [x] 11101
**Explanation:**
d = answer digit, c = carry
* Start by adding the rightmost bits: 0 + 1 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Next column: 0 + 1 + 1 = 2 (d: 2%2 = 0, c: 2/2 = 1)
* Next column: 1 + 1 + 1 = 3 (d: 3%2 = 1, c: 3/2 = 1)
* Next column: 1 + 0 + 0 = 1 (d: 1%2 = 1, c: 1/2 = 0)
* Final column: 0 + 1 + 0 = 1 (d: 1%2 = 1, c: 1/2 = 0)
The result is 11101 in binary.
---
### Bitwise Operators
* Bitwise operators are used to perform operations on individual bits of binary numbers.
* They are often used in computer programming to manipulate binary data.
* In bitwise operations, `0 -> false/unset` and `1 -> true/set`
#### AND (&)
* This operator takes two binary numbers and performs a logical AND operation on each pair of corresponding bits.
* The resulting bit in the output is 1 if and only if both the corresponding bits in the input are 1. Otherwise, the resulting bit is 0.
* The symbol for AND operator is '&'.
``` cpp
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
```
#### OR (|)
* This operator takes two binary numbers and performs a logical OR operation on each pair of corresponding bits.
* The resulting bit in the output is 1 if either one or both of the corresponding bits in the input are 1. Otherwise, the resulting bit is 0.
* The symbol for OR operator is '|'.
``` cpp
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
```
#### XOR (^)
* This operator takes two binary numbers and performs a logical XOR (exclusive OR) operation on each pair of corresponding bits.
* The resulting bit in the output is 1 if the corresponding bits in the input are different. Otherwise, the resulting bit is 0.
* The symbol for XOR operator is '^'.
``` cpp
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0
```
#### NOT(!/~)
* This operator takes a single binary number and performs a logical NOT operation on each bit.
* The resulting bit in the output is the opposite of the corresponding bit in the input.
* The symbols for NOT operator are '~' or '!'.
``` cpp
~0 = 1
~1 = 0
```
---
### Bitwise Operations Example
**Example 1:**
```cpp
5 & 6
//Binary representation
5 -> 101
6 -> 110
// Bitwise AND operation
101 & 110 = 100 = 4
```
**Example 2:**
```cpp
20 & 45
//Binary representation
20 -> 010100
45 -> 101101
// Bitwise AND operation
010100 & 101101 = 111101 = 61
```
**Example 3:**
```cpp
92 & 154
//Binary representation
92 -> 01011100
154 -> 10011010
// Bitwise OR operation
01011100 | 10011010 = 11011110 = 222
```
**Example 4**:
```cpp
~01011100
//Binary representation
92 -> 01011100
// Bitwise NOT operation
~01011100 = 10100011 = 163
```
**Example 5:**
```cpp
92 ^ 154
//Binary representation
92 -> 01011100
154 -> 10011010
// Bitwise XOR operation
01011100 ^ 10011010 = 11000110 = 198
```
---
### Question
What is the value of A ^ B (i.e. A XOR B) where, A = 20 and B = 45?
**Choices**
- [ ] 4
- [ ] 20
- [x] 57
- [ ] 61
**Explanation:**
* A = 20 = 00010100 (in binary)
* B = 45 = 00101101 (in binary)
Performing XOR on each pair of bits, we get:
```
00010100 ^ 00101101 = 00111001
```
Therefore, the value of A XOR B is 00111001, which is 57 in decimal format.
---
### Binary Representation of Negative numbers
To convert a negative number to its binary representation, we can use two's complement representation.
It works as follows -
* Convert the absolute value of number to Binary representation.
* Invert all the bits of number obtained in step 1.
* Add 1 to the number obtained in step 2.
Example of converting the negative number $-5$ to its $8-bit$ binary representation:
1. 5 to binary representation:```0000 0101```
2. Invert all the bits:`0000 0101 -> 1111 1010`
3. Add 1 to the inverted binary representation:
`1111 1010 + 0000 0001 = 1111 1011`
**Note:**
1. The MSB has a negative base and that is where the negative sign comes from.
2. In case of positive number, MSB is always 0 and in case of negative number, MSB is 1.
---
### Question
What is the binary representation of -3 in 8-bit signed integer format?
Choose the correct answer
**Choices**
- [x] 11111101
- [ ] 01111101
- [ ] 00000011
- [ ] 10101010
---
### Question
What is the binary representation of -10 in 8-bit signed integer format?
Choose the correct answer
**Choices**
- [x] 11110110
- [ ] 11110111
- [ ] 11111110
- [ ] 10101010
---
### Range of Data Types
What is the minimum & maximum no. that can be stored in the given no. of bits?
![](https://hackmd.io/_uploads/B1K61joE3.png)
Generalisation for N Bits:
![](https://hackmd.io/_uploads/Hk1JbioE2.png)
So, in general we can say that the {minimum,maximum} number in n-bit number is **{-2<sup>N-1</sup> , 2<sup>N-1</sup>-1}**.
#### Integer(32-bit number)
Integer is the 32 bit number. Its range is **{-2<sup>32-1</sup> , 2<sup>32-1</sup>-1}**.
#### Long(64-bit number)
Long is the 64 bit number. Its range is **{-2<sup>64-1</sup> , 2<sup>64-1</sup>-1}**.
### Approximation
Approximation is done to better approximate the range of values that can be stored in integer or long.
For integer,
![](https://hackmd.io/_uploads/SkjvJPtEn.png)
For long,
![](https://hackmd.io/_uploads/rJjtkwY4n.png)
---
### Importance of Constraints
Let's understand the importance of constraints using example.
Suppose we have two integers as
```
a = 10^5
b = 10^6
```
What will be the value of c ?
#### TRY 1:
```
int c = a*b
```
It will Overflow, i.e **c** will contain wrong value.
**Fails, the Reason:**
* The calculation happens at ALU.
* If we provide ALU with two INT, it calculates result in INT.
* Therefore, $a*b$ will overflow before even getting stored in c.
#### TRY 2:
Say, we change the data type of c to long, what will be the value of c?
```
long c = a*b
```
**Fails, the Reason:**
**c** would contain overflowed value since $a*b$ will overflow at the time of calculation, therefore there's no use to change datatype of **c** from INT to LONG.
#### TRY 3:
What if we typecast $a*b$ to long as below?
```
long c = long (a*b)
```
**Fails, the Reason:**
Already overflown, hence no use to typecast later.
#### TRY 4:
What if we change the equation as shown below?
```
long c = (long) a * b
```
This is the correct way to store.
**WORKS, the Reason:**
* Here, we have typecasted **a** to long before multiplying with **b**.
* If we send one INT and one LONG, ALU calculates answer in LONG.
### Question
Given an array of size N, calculate the sum of array elements.
**Constraints:**
1 <= N <= 10<sup>5</sup>
1 <= A[i] <= 10<sup>6</sup>
Is the following code correct ?
```
int sum = 0;
for (int i = 0; i < N; i++) {
sum = sum + A[i];
}
print(sum)
```
**We should look at constraints.**
As per constraint, range of sum will be as follows -
**1 <= sum <= 10<sup>11</sup>**
The above code is incorrect since sum can be as big as 10<sup>11</sup> which can't be stored in INTEGER.
Hence, we should change dataType of "sum" to LONG.

View File

@@ -0,0 +1,541 @@
# Interview Problems
## Analyzing constraints
### Tips on Problem Constraints
* Analyzing the constraints can help you determine which time complexity and data structure or algorithm to use for a given problem.
* It is important to look at the constraints whenever we are solving a problem.
Note: In Interviews, don't ask the constraints directly. Rather, tell your approach and ask the interviewer if you need to optimize further.
If,
| Constraint | Possible Time Complexities |
| ----------------------- | ------------------------------ |
| n <= 10^6 | O(n), O(nlogn) |
| n <= 20 | O(n!), O(2^n) |
| n <= 10^10 | O(logn), O(sqrt(n)) |
Note: These are just general guidelines. The actual time complexity can vary based on the specific problem and implementation.
It's always important to analyze the problem and determine the best approach for your specific solution.
---
### Problem 1 Find the maximum number of consecutive 1's after replacement
#### Problem Statement
Given an array of 1's and 0's, you are allowed to replace only one 0 with 1. Find the maximum number of consecutive 1's that can be obtained after making the replacement.
**Example 1**
```cpp
Input = [1, 1, 0, 1, 1, 0, 1, 1]
Output = 5
```
**Explanation:**
If we replace 0 at 2nd index or 0 at 5th index with 1, in both cases we get 5 consecutes 1's.
### Question
Find the maximum number of consecutive 1's that can be obtained after replacing only one 0 with 1.
A[] = [ 1, 1, 0, 1, 1, 0, 1, 1, 1 ]
**Choices**
- [ ] 4
- [ ] 5
- [x] 6
- [ ] 7
* If we replace 0 at 2nd index with 1 we get 5 consecutes 1's.
* If we replace 0 at 5th index with 1 we get 6 consecutes 1's.
Hence, the maximum is 6 consecutive 1's.
---
### Question
Find the maximum number of consecutive 1's that can be obtained after replacing only one 0 with 1.
A[] = [0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0]
**Choices**
- [ ] 4
- [ ] 5
- [x] 6
- [ ] 7
* If we replace 0 at 0th index with 1 we get 4 consecutes 1's.
* If we replace 0 at 4th index with 1 we get 6 consecutes 1's.
* If we replace 0 at 7th index with 1 we get 5 consecutes 1's.
* If we replace 0 at last index with 1 we get 3 consecutes 1's.
Hence, the maximum is 6 consecutive 1's.
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution Approach
* Maintain a variable say "ans", which keeps track of the maximum consecutive 1's encountered.
* Initialize it with 0.
* Iterate through the input array. When we encounter a zero at an index, we do the following:
* Count no. of consecutive 1's on left: **l**
* Count no. of consecutive 1's on right: **r**
* If (**l+r+1** > ans), replace ans with (**l+r+1**).
**Edge case**: When all the array elements are `1's`, then return the length of the whole array.
#### Pseudocode
```cpp
int findMaxConsecutiveOnes(int nums[]) {
int n = nums.size();
int maxCount = 0;
int totalOnes = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 1)
totalOnes++;
}
if (totalOnes == n)
return n;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
int l = 0, r = 0, j = i + 1;
// calculate the maximum consecutive ones after replacing this zero
while (j < n && nums[j] == 1) {
r++;
j++;
}
j = i - 1;
while (j >= 0 && nums[j] == 1) {
l++;
j--;
}
maxCount = max(l + r + 1, count);
}
}
return maxCount;
}
```
---
### Question
What will be the TC of this approach ?
**Choices**
- [x] O(n)
- [ ] O(n^2)
- [ ] O(n^3)
- [ ] O(n^4)
**Explanation:**
The time complexity of the above solution is O(n) because it performs a single pass over the input array and every element will get accessed at maximum of 3 times.
> ![](https://hackmd.io/_uploads/rk-sTkprh.png)
---
## Variation of Problem 1
### Coding Question 2
#### Problem Statement
Given an array of 1's and 0's, find the maximum number of consecutive 1's that can be obtained by SWAPPING at most one 0 with 1(already present in the string).
**Example 1**
```cpp
Input: [1, 0, 1, 1, 0, 1]
Output: 5
```
#### Explanation:
We can swap zero at index 4 with 1 to get the array [1, 0, 1, 1, 1, 1], which has 5 consecutive 1s.
---
### Question
find the maximum number of consecutive 1s that can be obtained by swapping at most one 0 with 1.
A[] = [1, 1, 0, 1, 1, 1]
**Choices**
- [ ] 2
- [ ] 4
- [x] 5
- [ ] 6
**Explanation:**
We can swap the zero at index 2 with 1 at either index 0 or index 5 to get the array which has 5 consecutive 1s.
---
### Problem 1 variation continues
#### Solution
* The solution is very similar to solution to previous problem except for some modifications.
* We iterate through the input array. When we encounter a zero at an index, we do the following:
* Count no. of consecutive 1's on left -> l.
* Count no. of consecutive 1's on right -> r.
* If (l+r) is equal to total no. of 1's in the array, then currMax = (l+r), else currMax = (l+r+1).
* If (currMax > ans), replace ans with (currMax)
**Edge case**: When all the array elements are `1's`, then return the length of the whole array.
#### Pseudocode
```cpp
int findMaxConsecutiveOnes(int nums[]) {
int n = nums.size();
int maxCount = 0;
int totalOnes = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 1)
totalOnes++;
}
if (totalOnes == n)
return n;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
int l = 0, r = 0, j = i + 1, currMax;
// calculate the maximum consecutive ones after swapping this zero
while (j < n && nums[j] == 1) {
r++;
j++;
}
j = i - 1;
while (j >= 0 && nums[j] == 1) {
l++;
j--;
}
if (l + r == totalOnes)
currMax = l + r;
else
currMax = l + r + 1
maxCount = max(currMax, count);
}
}
return maxCount;
}
```
#### Time and Space Complexity
* TC - O(n)
* SC - O(1)
---
### Problem 2 Majority Element
Given an array of N integers, find the **majority element.**
The **majority element** is the element that occurs more than n/2 times where n is size of the array.
**Example 1**
```plaintext
A[ ] = { 2, 1, 4 }
Ans = No Majority element
```
### Explanation
Here, none of the elements have frequency more than n/2 where n is 3.
**Example 2**
```plaintext
A[ ] = { 3, 4, 3, 2, 4, 4, 4, 4}
Ans = 4
```
#### Explanation
Here, frequency of 4 is more than n/2 that is 5 where n is 8. So 4 will be the majority element.
**Example 3**
```plaintext
A[ ] = { 3, 3, 4, 2, 4, 4, 2, 4}
Ans = No Majority element
```
#### Explanation:
Here, none of the elements have frequency more than n/2 where n is 8.
---
### Question
What is the majority element in this array?
3, 4, 3, 6, 1, 3, 2, 5, 3, 3, 3
**Choices**
- [ ] 1
- [x] 3
- [ ] 2
- [ ] 6
Here, 3 has frequency > n/2 where n is 11.
### Question
What is the majority element in the following array?
4, 6, 5, 3, 4, 5, 6, 4, 4, 4
**Choices**
- [ ] 3
- [ ] 4
- [ ] 6
- [x] No Majority Element
**Explanation:**
Here, none of the elements have frequency more than n/2 where n is 10.
---
### Question
At max how many majority elements can be there in an array?
**Choices**
- [x] 1
- [ ] 2
- [ ] n-1
- [ ] n
Suppose there is an array of size n. If frequency of an element is greater than n/2, then there cannot exist an element in remaining elements whose frequency is greater than n/2 .
Hence, there can be only one majority element.
---
### Problem 2 Brute Force
Iterate through every element in the array, count the number of times each element appears, and return the element that appears more than n/2 times.
#### Pseudocode
```cpp
void findMajority(int arr[], int n) {
int maxCount = 0;
int index = -1;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > maxCount) {
maxCount = count;
index = i;
}
}
if (maxCount > n / 2)
print(arr[index])
else
print("No Majority Element")
}
```
#### Complexity
-- TC - $O(n^2)$
-- SC - $O(1)$
:::warning
Please take some time to think about the Optimised approach on your own before reading further.....
:::
---
### Problem 2 Optimised Approach using Moores Voting Algorithm
#### Observation 1:
There can only be **one majority element** in the array.
#### Proof:
We will prove it by contradiction.
* Let's say there are two majority elements, say m1 and m2.
* frequency(m1) > n/2 and frequency(m2) > n/2
* Adding both sides,
* frequency(m1) + frequency(m2) > n **[it not possible]**
* Hence, Prooved.
#### Observation 2:
If we **remove any two distinct elements, the majority element remains the same.**
**Explanation 1:**
> Consider array of 13 blocks.
First **7 blocks** are filled with **GREEN colour**.
Next **6 blocks** are filled with **RED colour**.
**Majority** is **GREEN**.
If we remove 2 distinct blocks, 1 from GREEN and 1 from RED, we will be left with 11 elements.
**Majority** is still **GREEN**.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/886/original/e1.jpeg?1682577851)
> Again, If we remove 2 distinct elements, 1 from GREEN and 1 from RED, we will be left with 9 elements.
**Majority** is still **GREEN**.
![reference link](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/887/original/e2.jpeg?1682578235)
> If we continue this process we will get GREEN as MAJORITY element.
**Explanation 2:**
Suppose there are **4 parties** participating in an **election**.
* First: ORANGE party(OP) with **9** candidates.
* Second: YELLOW party(YP) with **3** candidates.
* Third: RED party(RP) with **2** candidates.
* Fourth: GREEN party(GP) with **3** candidates.
Currently, the **WINNER is ORANGE**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/032/666/original/elect.jpeg?1682430684)
| Remove | Orange | Yellow | Red | Green | Winner|
| --- |--- | ---| ----- | ------| ---|
|1 OP and 1 YP | 8 | 2 | 2 | 3 |Orange
|1 OP and 1 GP | 7 | 2 | 2 | 2 |Orange
|1 OP and 1 RP | 6 | 2 | 1 | 2 |Orange
|1 YP and 1 RP | 6 | 1 | 0 | 2 |Orange
|1 YP and 1 GP | 6 | 0 | 0 | 1 |Orange
|1 OP and 1 GP | 5 | 0 | 0 | 0 |Orange
We can observe that after removing 2 distinct party votes every time, majority is maintained at every point.
**Note:** We cannot remove same party votes twice.
---
### Problem 2 Moores Voting Algorithm Approach and Dry Run
#### Approach
* Iterate through each element of the array, keeping track of the majority element's count and index.
* If the next element is the same as the current majority element, increase the count; otherwise, decrease the count.
* If the count becomes zero, update the majority index to the current element and reset the count to 1.
* After the iteration, go through the array once again and determine the count of the majority element found.
* If count > N/2, return majority elsement; else majority element doesn't exist.
#### Dry Run
Please **dry run** for the following example:
```plaintext
A[ ] = { 3, 4, 3, 6, 1, 3, 2, 5, 3, 3, 3 }
```
#### Pseudocode
```cpp
int findCandidate(int a[], int size) {
int maj_index = 0, count = 1;
for (int i = 1; i < size; i++) {
if (count == 0) {
maj_index = i;
count = 1;
} else {
if (a[maj_index] == a[i])
count++;
else
count--;
}
}
//check if the candidate
//occurs more than n/2 times
int count = 0;
for (int i = 0; i < size; i++) {
if (a[i] == a[maj_index])
count++;
}
if (count > size / 2)
return a[maj_index];
else
return -1;
}
```
#### Time and Space Complexity
What will be T.C and S.C for this approach?
-- TC - $O(n)$
-- SC - $O(1)$
---
### Problem 3 Row to Column Zero
You are given a 2D integer matrix A, make all the elements in a row or column zero if the A[i][j] = 0. Specifically, make entire ith row and jth column zero.
**Example**
**Input:**
[1,2,3,4]
[5,6,7,0]
[9,2,0,4]
**Output:**
[1,2,0,0]
[0,0,0,0]
[0,0,0,0]
**Explanation:**
A[2][4] = A[3][3] = 0, so make 2nd row, 3rd row, 3rd column and 4th column zero
#### Observation
If you start row wise and make one row completely zero if it has 0 then you will loose information for making columns zero.
**Note:** None element is negative so see if you may use this for not loosing info.
#### Approach
* Let's start row wise first.
* Select rows one by one and make all the elements of that row -1(except which are 0), if any element in that row is 0.
* Similariy you have to do the same thing for columns.
* Now, before returning traverse the matrix and make all the -1 elements 0.
#### Pseudocode
```cpp
int n = A.size(), m = A[0].size();
for (int i = 0; i < n; i++) {
int flag = 0;
for (int j = 0; j < m; j++) {
if (A[i][j] == 0) flag = 1;
}
if (flag == 1) {
for (int j = 0; j < m; j++) {
if (A[i][j] != 0) A[i][j] = -1;
}
}
}
for (int j = 0; j < m; j++) {
int flag = 0;
for (int i = 0; i < n; i++) {
if (A[i][j] == 0) flag = 1;
}
if (flag == 1) {
for (int i = 0; i < n; i++) {
if (A[i][j] != 0) A[i][j] = -1;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (A[i][j] == -1) A[i][j] = 0;
}
}
return A;
```

View File

@@ -0,0 +1,477 @@
# Introduction To Arrays
## Space Complexity
* Space complexity is the max space(worst case) that is utilised at any point in time during running the algorithm.
* We also determine Space Complexity using **Big O**.
Consider the following example:
```pseudocode
func(int N) { // 4 bytes
int x; // 4 bytes
int y; // 4 bytes
long z; // 8 bytes
}
```
* We only consider the space utilised by our program and not the Input Space since it is not in our control, hence we'll ignore space taken by "int N".
* The above code takes total **16B** of memory.
* Hence, we say the **Space Complexity** of the above code is **O(1)** (1 resembles constant).
### Question
Find the Space Complexity [Big(O)] of the below program.
```pseudocode
func(int N) { // 4 bytes
int arr[10]; // 40 Bytes
int x; // 4 bytes
int y; // 4 bytes
long z; // 8 bytes
int[] arr = new int[N]; // 4 * N bytes
}
```
**Choices**
- [x] N
- [ ] 4N + 60
- [ ] Constant
- [ ] N^2
### Question
Find the Space Complexity [Big(O)] of the below program.
```pseudocode
func(int N) { // 4 bytes
int x = N; // 4 bytes
int y = x * x; // 4 bytes
long z = x + y; // 8 bytes
int[] arr = new int[N]; // 4 * N bytes
long[][] l = new long[N][N]; // 8 * N * N bytes
}
```
**Choices**
- [ ] N
- [ ] 4N + 60
- [ ] Constant
- [x] N^2
### Question on Space Complexity
Find the Space Complexity [Big(O)] of the below program.
```cpp
int maxArr(int arr[], int N) {
int ans = arr[0];
for(i from 1 to N-1) {
ans = max(ans, arr[i]);
}
return ans;
}
```
### Space complexity: O(1)
* Don't consider the space acquired by the input size. Space complexity is the order of extra space used by the algorithm.
* **arr[]** is already given to us, we didn't create it, hence it'll not be counted in the Space Complexity.
* **int N** will also not be counted in space but since it is contant hence doesn't matter.
* Additional space is also called **computational or auxiliary space.**
* The above code finds the max element of the Array.
### Introduction To Arrays
#### Definition
Array is the collection of same types of data. The datatype can be of any type i.e, int, float, char, etc. Below is the declaration of the array:
```
int arr[n];
```
Here, int is the datatype, arr is the name of the array and n is the size of an array.
We can access all the elements of the array as arr[0], arr[1] ….. arr[n-1].
**Note:** Array indexing starts with 0.
##### Why indexing starts at 0 ?
An array arr[i] is interpreted as *(arr+i). Here, arr denotes the address of the first array element or the 0 index element. So *(arr+i) means the element at i distance from the first element of the array.
### Question
What will be the indices of the first and last elements of an array of size **N**?
Choose the correct answer
**Choices**
- [ ] 1,N
- [x] 0,N-1
- [ ] 1,N-1
- [ ] 0,N
## Introduction to Arrays Continued
### Print all elements of the array
The elements of arrays can be printed by simply traversing all the elements. Below is the pseudocode to print all elements of array.
```
void print_array(int arr[],int n){
for(int i=0;i<n;i++){
print(arr[i]);
}
}
```
### Question
What is the time complexity of accessing element at the ith index in an array of size **N**?
**Choices**
- [ ] O(N)
- [x] O(1)
- [ ] O(N*N)
- [ ] O(log(N)).
### Question
int arr[5] = {5,-4,8,9,10}
Print sum of 1st and 5th element
Choose the correct answer
**Choices**
- [ ] print(arr[0]+arr[5])
- [x] print(arr[0]+arr[4])
- [ ] print(arr[1]+arr[5])
- [ ] print(arr[1]+arr[4])
### Question 1 Reverse the array
Given an array 'arr' of size 'N'. Reverse the entire array.
#### TestCase:
#### Input:
```
N = 5
arr = {1,2,3,4,5}
```
#### Output:
```
arr = {5,4,3,2,1}
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach
The simplest approach to solve the problem is to keep two pointers at the end, traverse the array till middle element and swap first element with last element, second with second last, third with third last and so on.
![](https://i.imgur.com/xUDocWR.png)
**What should be the stopping condition?**
Say N = 6
| i | j | swap |
| -------- | -------- | -------- |
| 0 | 5 | A[0] & A[5] |
| 1 | 4 | A[1] & A[4] |
| 2 | 3 | A[2] & A[3] |
| 3 | 2 | STOP |
Say N = 5
| i | j | swap |
| -------- | -------- | -------- |
| 0 | 4 | A[0] & A[4] |
| 1 | 3 | A[1] & A[3] |
| 2 | 2 | STOP |
We can stop as soon as $i>=j$
### Pseudocode
```cpp
Function reverse(int arr[], int N) {
int i = 0, j = N - 1;
while (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
```
#### Complexity:
**Time Complexity - O(N).
Space Complexity - O(1).**
### Question 2 Reverse in a range
Given an array 'arr' of size 'N' and integers 'l' and 'r'. Reverse the array from 'l' to 'r'.
#### TestCase:
#### Input:
```
N = 5
arr = {1,2,3,4,5}
[0 based index]
l = 1
r = 3
```
#### Output:
```
arr = {1,4,3,2,5}
```
#### Pseudocode
```cpp
Function reverse(int arr[], int N, int l, int r) {
while (l < r) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
```
#### Complexity:
**Time Complexity - O(N).
Space Complexity - O(1).**
### Question 3 Rotate K times
Given an array 'arr' of size 'N'. Rotate the array from right to left 'K' times. (i.e, if K = 1, last element will come at first position,...)
#### TestCase:
#### Input:
```
N = 5
arr = {1,2,3,4,5}
k = 2
```
#### Output:
```
arr = {4,5,1,2,3}
```
#### Explanation:
Initially the array is:
| 1 | 2 | 3 | 4 | 5 |
After 1st rotation:
| 5 | 1 | 2 | 3 | 4 |
After 2nd rotation:
| 4 | 5 | 1 | 2 | 3 |
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### BruteForce Approach
Simple approach is to rotate the array one element at a time.
#### Pseudocode
```cpp
Function rotateK(int arr[], int N, int K) {
for (int i = 0; i < K; i++) {
int temp = arr[N - 1];
for (int j = N - 1; j >= 1; j--) {
arr[j] = arr[j - 1];
}
arr[0] = temp;
}
}
```
#### Complexity:
**Time Complexity - O(N*K).
Space Complexity - O(1).**
### Optimized Approach
:::success
Please take some time to think about the optimised solution approach on your own before reading further.....
:::
#### Optimized Appraoch Observations
* After K rotations, last K elements become 1st K elements and rest elements will go at back.
For example - Suppose we have an array arr as shown below and k = 3.
`1 2 3 4 5 6 7`
After 1st rotation, k=1:
`7 1 2 3 4 5 6`
After 2nd rotation, k=2:
`6 7 1 2 3 4 5`
After 3rd rotation, k=3:
`5 6 7 1 2 3 4`
So, we have observed that last 3(K=3) elements i.e, `5 6 7` comes in front and rest elements appear at the end.
Therefore, we will first reverse the entire array, then reverse first K elements individually and then next N-K elements individually.
```
1 2 3 4 5 6 7 //Given Array, K=3
7 6 5 4 3 2 1 //Reversed Entire Array
5 6 7 4 3 2 1 //Reversed first K elements
5 6 7 1 2 3 4 //Reversed last N-K elements
```
#### Pseudocode
```cpp
Function countgreater(int arr[], int N, int k) {
reverse(arr, N, 0, N - 1);
reverse(arr, N, 0, K - 1);
reverse(arr, N, K, N - 1);
}
```
#### Edge Case
K might be very large but if we observe carefully then after N rotations the array comes to its initial state.
Hence, K rotation is equivalent to K%N rotations.
Suppose we have an array:
`1 2 3 4`
After 1st rotation, the array becomes:
`2 3 4 1`
After 2nd rotation, the array becomes:
`3 4 1 2`
After 3rd rotation, the array becomes:
`4 1 2 3`
Afer 4th rotation, the array becomes:
`1 2 3 4`
Hence, we have concluded that after **N** rotations, the array become same as before 1st rotation.
### Final Pseudocode
```cpp
Function countgreater(int arr[], int N, int K) {
K = k % N;
reverse(arr, N, 0, N - 1);
reverse(arr, N, 0, K - 1);
reverse(arr, N, K, N - 1);
}
```
#### Complexity:
**Time Complexity - O(N).
Space Complexity - O(1).**
## Dynamic Arrays
### Question:
What is the drawback of normal arrays?
#### Issue:
The size has to be declared before hand.
### Dynamic Arrays
* A dynamic array is an array with a big improvement: automatic resizing.
* It expands as you add more elements. So you don't need to determine the size ahead of time.
### Strengths:
**Fast lookups:** Just like arrays, retrieving the element at a given index takes
O(1) time.
**Variable size:** You can add as many items as you want, and the dynamic array will expand to hold them.
### Weaknesses:
**Slow worst-case appends:**
* Usually, adding a new element at the end of the dynamic array takes O(1) time.
* But if the dynamic array doesn't have any room for the new item, it'll need to expand, which takes O(n) time.
* It is because we have to take a new array of bigger size and copy all the elements to a new array and then add a new element.
* So, Time Complexity to add a new element to Dynamic array is **O(1) amortised**.
* Amortised means when most operations take **O(1)** but some operations take **O(N)**.
### Dynamic Arrays in Different Languages
#### Java
```
ArrayList<String> al = new ArrayList<>(); //Arraylist is created
```
```
al.add("50"); //50 is inserted at the end
```
```
al.clear(); // al={}
```
```
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
} //iterating the Arraylist
```
#### C++
```
vector<int> a; //vector is created
```
```
a.push_back(60);
//a = {10, 20, 30, 40, 50, 60} after insertion at end
```
```
a.clear(); // a={}
```
```
for(int i=0; i<a.size(); i++) {
cout<<a[i];
} //iterating the vector
```
#### Python
```
thislist = [] //created list
```
```
thislist.append("orange") //added orange at end
```
```
thislist.clear() //cleared the list
```
```
for i in range(len(thislist)):
print(thislist[i]) //iterating on the list
```

View File

@@ -0,0 +1,420 @@
# Introduction to Problem Solving
---
Notes Description
---
* Introduction to Problem Solving
* Time Complexity
* Introduction to Arrays
* Prefix Sum
* Carry Forward
* Subarrays
* 2D Matrices
* Sorting Basics
* Hashing Basics
* Strings Basics
* Bit Manipulation Basics
* Interview Problems
**Following will be covered in the notes!**
1. Count the Factors
2. Optimisation for counting the Factors
3. Check if a number is Prime
4. Sum of N Natural Numbers
5. Definition of AP & GP
6. How to find the number of a times a piece of code runs, i.e, number of Iterations.
7. How to compare two Algorithms.
## Count of factors of a number N
Q. What is a factor?
A. We say i is a factor of N if i divides N completely, i.e the remainder is 0.
How to programmatically check if i is a factor of N ?
We can use % operator which gives us the remainder.
=> **N % i == 0**
**Question 1:**
Given N, we have to count the factors of N.
**Note:** N > 0
**Question 2:**
Number of factors of the number 24.
**Choices**
- [ ] 4
- [ ] 6
- [x] 8
- [ ] 10
**Explanation:**
1, 2, 3, 4, 6, 8, 12, and 24 are the factors.
**Question 3:**
Number of factors of the number 10.
**Choices**
- [ ] 1
- [ ] 2
- [ ] 3
- [x] 4
**Explanation:**
1, 2, 5, and 10 are the factors.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Counting Factors Brute force solution
What is the minimum factor of a number ?
=> 1
What is the maximum factor of a number ?
=> The number itself
So, we can find all factors of N from 1 to N.
### Pseudocode
```cpp
function countfactors (N):
fac_count = 0
for i = 1 till N:
if N % i == 0:
fac = fac + 1
return fac
```
### Observations for Optimised Solution
* Now, your code runs on servers.
* When you submit your code, do you expect some time within which it should return the Output ?
* You wouldn't want to wait when you even don't know how long to wait for ?
* Just like that one friend who says, 'Just a little more time, almost there.' And you feel annoyed, not knowing how much longer you'll have to wait.
Servers have the capability of running ~10^8 Iterations in 1 sec.
|N| Iterations| Execution Time|
|-|----------|---------- |
|10^8| 10^8 iterations| 1 sec |
|10^9| 10^9 iterations| 10 sec |
|10^18| 10^18 iterations| 317 years |
### Optimisation for Counting Factors
**Optimization:**
i * j = N -> {i and j are factors of N}
=> j = N / i -> {i and N / i are factors of N}
For example, N = 24
|i| N / i|
|-|----------|
|1| 24|
|2| 12|
|3| 8|
|4| 6|
|6| 4|
|8| 3|
|12| 2|
|24| 1|
Q. Can we relate these values?
A. We are repeating numbers after a particular point. Here, that point is from 5th row.
Now, repeat the above process again for N = 100.
|i| N / i|
|-|----------|
|1| 100|
|2| 50|
|4| 25|
|5| 20|
|10| 10|
|20| 5|
|25| 4|
|50| 2|
|100| 1|
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
The factors are repeating from 6th row. After a certain point factors start repeating, so we need to find a point till we have to iterate.
We need to only iterate till -
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/846/original/upload_b7d89a4e3534f96005e65eaec0681e2a.png?1692787858)
### Pseudocode
```cpp
function countfactors (N):
fac_count = 0
for i = 1 till sqrt(N):
if N % i == 0:
fac = fac + 2
return fac
```
Q. Will the above work in all the cases?
A. No, not for perfect squares. Explain this for N = 100, what mistake we are doing. We will count 10 twice.
**Observation:** Using the above example, we need to modify the code for perfect squares.
### Pseudocode with Edge Case Covered
```cpp
function countfactors (N):
fac_count = 0
for i = 1 till sqrt(N):
if N % i == 0:
if i == N / i:
fac = fac + 1
else:
fac = fac + 2
return fac
```
Dry run the above code for below examples,
N = 24, 100, 1.
|N| Iterations| Execution Time|
|-|----------|---------- |
|10^18| 10^9 iterations| 10 secs |
To implement sqrt(n) , replace the condition i <= sqrt(N) by i * i <= N.
### Follow Up Question
Given N, You need to check if it is prime or not.
**Question**
How many prime numbers are there?
10, 11, 23, 2, 25, 27, 31
**Choices**
- [ ] 1
- [ ] 2
- [ ] 3
- [x] 4
**Explanation:**
Q. What is a prime Number?
A. Number which has only 2 factors, 1 and N itself.
So, 11, 23, 2, and 31 are the only prime numbers since they all have exactly 2 factors.
## Prime Check
Our original question was to check if a number is prime or not. For that, we can just count the number of factors to be 2.
```cpp
function checkPrime(N):
if countfactors(N) == 2:
return true
else:
return false
```
For N = 1, it will return false, which is correct. Since, 1 is neither prime nor composite.
---
**Question**
1 + 2 + 3 + 4 + 5 + 6 + .. 100 = ?
**Choices**
- [ ] 1010
- [x] 5050
- [ ] 5100
- [ ] 1009
**Explanation:**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/347/original/ytbMtMR.png?1684220222)
Generalize this for the first N natural numbers.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/348/original/iqYoobK.png?1684220244)
## Some basic math properties:
1. `[a,b]` - This type of range means that a and b are both inclusive.
2. `(a,b)` - This type of range means that a and b are both excluded.
**Question**
How many numbers are there in the range [3,10]?
**Choices**
- [ ] 7
- [ ] 6
- [x] 8
- [ ] 10
**Explanation:**
The range [3,10] includes all numbers from 3 to 10, inclusive. Inclusive means that both the lower bound (3) and the upper bound (10) are included in the range. Thus the numbers that are included are 3 4 5 6 7 8 9 10.
**Question**
How many numbers are there in the range [a,b]?
**Choices**
- [ ] b-a
- [x] b-a+1
- [ ] b-a-1
**Explanation:**
To find the number of numbers in a given range, we can subtract the lower bound from the upper bound and then add 1. Mathematically, this can be expressed as:
```
Number of numbers in the range
= Upper bound - Lower bound + 1
```
### What do we mean by Iteration?
The number of times a loop runs, is known as Iteration.
**Question**
How many times will the below loop run ?
```cpp
for(i=1; i<=N; i++)
{
if(i == N) break;
}
```
**Choices**
- [ ] N - 1
- [x] N
- [ ] N + 1
- [ ] log(N)
**Question**
How many iterations will be there in this loop ?
```cpp
for(int i = 0; i <= 100; i++){
s = s + i + i^2;
}
```
**Choices**
- [ ] 100 - 1
- [ ] 100
- [x] 101
- [ ] 0
**Question**
How many iterations will be there in this loop?
```cpp
func(){
for(int i = 1; i <= N; i++){
if(i % 2 == 0){
print(i);
}
}
for(int j = 1; j <= M; j++){
if(j % 2 == 0){
print(j);
}
}
}
```
**Choices**
- [ ] N
- [ ] M
- [ ] N * M
- [x] N + M
**Explanation:**
We are executing loops one after the other. Let's say we buy first 5 apples and then we buy 7 apples, the total apples will be 12, so correct ans is N + M
## Geometric Progression (G.P.)
> **Example for intution:**
```
5 10 20 40 80 ..
```
In these type of series, the common ratio is same. In the given example the common ratio r is
= 10/5
= 20/10
= 40/20
= 80/40
= 2
**Generic Notation:**
a, a * r, a * r^2, ...
### Sum of first N terms of a GP
**Sum of first N terms of GP:**
=![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/043/847/original/upload_7d7368fe780e904c2836a90ed74e5b1e.png?1692787881)
r cannot be equal to 1 because the denominator cannot be zero.
**Note:**
When r is equal to 1, the sum is given by a * n.
## How to compare two algorithms?
**Story**
There was a contest going on to SORT the array and 2 people took part in it (say Gaurav and Shila).
They had to sort the array in ascending order.
arr[5] = {3, 2, 6, 8, 1} -> {1, 2, 3, 6, 8}
Both of them submitted their algorithms and they are being run on the same input.
### Discussion
**Can we use execution time to compare two algorithms?**
Say initially **Algo1** took **15 sec** and **Algo2** took **10sec**.
This implies that **Shila's Algo 1** performed better, but then Gaurav pointed out that he was using **Windows XP** whereas Shila was using **MAC**, hence both were given the same laptops.........
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/050/original/time-complexity-2-image-1.png?1683815146)
### Conclusion
We can't evaluate algorithm's performance using **execution time** as it depends on a lot of factors like operating system, place of execution, language, etc.
**Question**
How can we compare two algorithms?
Which measure doesn't depend on any factor?
**Answer:** Number of Iterations
**Why?**
* The number of iterations of an algorithm remains the same irrespective of Operating System, place of execution, language, etc.

View File

@@ -0,0 +1,523 @@
# Beginner : Memory Management
---
## Introduction to stack
### Idli Maker Examples
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/250/original/Screenshot_2023-09-26_at_5.39.11_PM.png?1695922237" alt= “” width ="700" height="300">
### Stack
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/251/original/Screenshot_2023-09-26_at_5.37.44_PM.png?1695922271" alt= “” width ="600" height="300">
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
---
### Introduction to call stack
#### Example 1
Consider the below code:
```java
int add(int x, int y) {
return x + y;
}
int product(int x, int y) {
return x * y;
}
int subtract(int x, int y) {
return x - y;
}
public static void main() {
int x = 10;
int y = 20;
int temp1 = add(x, y);
int temp2 = product(x, y);
int temp3 = subtract(x, y);
System.out.println(temp1 + temp2 + temp3);
}
```
Following is the call stack execution for above code:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/252/original/Screenshot_2023-09-26_at_5.41.09_PM.png?1695922314" alt= “” width ="200" height="400">
**Ouput:** 220
#### Example 2
Consider the below code:
```java
int add(int x, int y) {
return x + y;
}
public static void main() {
int x = 10;
int y = 20;
int temp1 = add(x, y);
int temp2 = add(temp1, 30);
int temp3 = add(temp2, 40);
System.out.println(temp3);
}
```
Following is the call stack execution for above code:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/067/735/original/explanation.png?1710154203" alt= “” width ="200" height="400">
**Output:** 100
#### Example 3
Consider the below code:
```java
int add(int x, int y) {
return x + y;
}
static int fun(int a, int b) {
int sum = add(a, b);
int ans = sum * 10;
return ans;
}
static void extra(int w){
System.out.println("Hello");
System.out.println(w);
}
public static void main() {
int x = 10;
int y = 20;
int z = fun(x, y);
System.out.println(z);
extra(z);
}
```
Following is the call stack execution for above code:
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/828/original/Screenshot_2023-09-26_at_5.36.25_PM.png?1695730007" alt= “” width ="150" height="450">
**Output:**
```plaintext
300
Hello
310
```
---
### Types of Memory in Java
Following are the types of memory present in Java -
1. **Stack** -<br> All the primitive data type and reference will be stored in stack.
2. **Heap** -<br> Container of that reference is stored in heap. Arrays, ArrayList, Objects are created inside heap.
**Example 1**
Consider the below code:
```java
public static void main() {
int x = 10;
int[] ar = new int[3];
System.out.println(ar); // #ad1
System.out.println(ar[2]); // 0
ar[1] = 7;
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/253/original/upload_db1be0d6807a0107d3b4a49f92083d10.png?1695922800" alt= “” width ="400" height="400">
**Note**:
1. **Primitive data types:** [int, float, double, char, boolean, long] memory will be assigned in stack.
2. **Reference/ address of the container:** will be stored in stack.
3. **Container:** [Array/ Arraylist] will be stored in heap.
**Example 2**
Consider the below code:
```java
public static void main() {
int x = 10;
int[] ar = new int[3];
int[] ar2 = ar;
System.out.println(ar); // 4k
System.out.println(ar2); // 4k
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/253/original/upload_db1be0d6807a0107d3b4a49f92083d10.png?1695922800" alt= “” width ="300" height="300">
**Example 3**
Consider the below code:
```java
public static void main() {
int[] ar = new int[3];
System.out.println(ar); // 5k
ar[1] = 9;
ar[2] = 5;
ar = new int[5];
System.out.println(ar); // 7k
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/254/original/upload_838ad761524ff3f484346b1762d842ab.png?1695923038" alt= “” width ="300" height="300">
**Example 4**
Consider the below code:
```java
static void fun(int[] a){
System.out.println(a); // 9k
a[1] = 5;
}
public static void main() {
int[] ar = new int[3];
System.out.println(ar); // 9k
ar[0] = 90;
ar[1] = 50;
fun(ar);
System.out.println(ar[1]); // 5
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/255/original/upload_96b9617bf2562ab2cf70308c14562662.png?1695923094" alt= “” width ="300" height="300">
**Example 5**
Consider the below code:
```java
public static void main() {
float y = 7.84f;
int[][] mat = new int[3][4];
System.out.println(mat); // 9k
System.out.println(mat[1]); // 3k
System.out.println(mat[1][3]); // 0
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/256/original/upload_d6ef6f285e8852ea6483735ea9b275ff.png?1695923118" alt= “” width ="300" height="300">
**Example 6**
Consider the below code:
```java
static void sum(int[][] mat){
System.out.println(mat); // 2k
System.out.println(mat[0][0] + mat[1][0]); // 40
}
public static void main() {
int[][] mat = new int[2][3];
mat[0][0] = 15;
mat[1][0] = 25;
sum(mat);
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/258/original/upload_60fffb5badb5839f531e4a4b49d50280.png?1695923213" alt= “” width ="300" height="300">
**Example 7**
Consider the below code:
```java
static int sumOfRow(int[] arr){
System.out.println(arr); // 7k
int sum = 0;
for (int i = 0; i < arr.length; i++){
sum = sum + arr[i];
}
return sum;
}
public static void main() {
int[][] mat = new int[2][3];
mat[0][0] = 9;
mat[0][1] = 5;
mat[0][2] = 1;
int ans = sumOfRow(mat[0]); // 7k
System.out.println(ans); // 15
}
```
Now, lets analyze the given code -
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/259/original/upload_ebc077e9eb41f97f24666a4fc1c97c6c.png?1695923287" alt= “” width ="300" height="400">
### Question
Predict the Output :
```Java
static void change(int a) {
a = 50;
}
public static void main(String args[]) {
int a = 10;
change(a);
System.out.println(a);
}
```
**Choices**
- [x] 10
- [ ] 50
- [ ] Error
**Explanation**
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/260/original/upload_88f3bbcc4fd367434b74cf4b394cebe8.png?1695923386" alt= “” width ="200" height="300">
* The parameter variable 'a' of change function is reassigned to the value of 50, because both the functions have their own variables, so the variable "a" of main function is different than of variable "a" in change function.
* Stack changes are temporary.
---
### Question
Predict the output :
```java
static void change(int[]a) {
a[0] = 50;
}
public static void main(String args[]) {
int[]a = {10};
change(a);
System.out.println(a[0]);
}
```
**Choices**
- [ ] 10
- [x] 50
- [ ] Error
---
**Explanation:**
* The array a in change method and main method both refer to the same array object in the heap.
* Heap changes are permanent changes.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/261/original/upload_b6a922583fd12618a2bb53d4233d6569.png?1695923456" alt= “” width ="200" height="300">
---
### Question
Predict the output :
```java
static void test(int[]a) {
a = new int[1];
a[0] = 50;
}
public static void main(String args[]) {
int[]a = {10};
test(a);
System.out.println(a[0]);
}
```
**Choices**
- [x] 10
- [ ] 50
- [ ] Error
---
**Explanation:**
Inside the test method, a new integer array with length 1 is allocated on the heap memory, and the reference to this array is assigned to the parameter variable a. Hence, now the variable 'a' inside test function and main function point to different references.Heap changes are permanent.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/262/original/upload_2880b16a60cdc943bbd8deb67bc51f87.png?1695923573" alt= “” width ="200" height="300">
---
### Question
Predict the output:
```java
static void fun(int[] a) {
a = new int[1];
a[0] = 100;
}
public static void main() {
int[] a = {10, 20, 30};
fun(a);
System.out.println(a[0]);
}
```
**Choices**
- [x] 10
- [ ] 100
- [ ] Error
- [ ] inky pinky po
**Explanation:**
Inside the fun method, a new integer array with length 1 is allocated on the heap memory, and the reference to this array is assigned to the parameter variable a. Hence, now the variable 'a' inside test function and main function point to different references.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/263/original/upload_fe68bae5077ef0992c9d7cec41e6c8cb.png?1695923634" alt= “” width ="300" height="300">
---
### Question
Predict the output :
```java
static void swap(int a,int b) {
int temp = a;
a = b;
b = temp;
}
public static void main(String args[]) {
int a = 10;
int b = 20;
swap(a,b);
System.out.println(a + " " + b);
}
```
**Choices**
- [x] 10 20
- [ ] 20 10
- [ ] 10 10
- [ ] Error
**Explanation:**
* Swap function is called by value not by reference.
* So, the changes made in the swap function are temporary in the memory stack.
* Once we got out of the swap function, the changes will go because they are made in temporary variables.
* Hence no swapping is done and variable have the same value as previous.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/264/original/upload_95a36c6cecdaa3e8eb1fa455c50dd9b0.png?1695923691" alt= “” width ="200" height="300">
---
### Question
Predict the output :
```java
static void swap(int[]a,int[]b) {
int temp = a[0];
a[0] = b[0];
b[0] = temp;
}
public static void main(String args[]) {
int[]a = {10};
int[]b = {20};
swap(a,b);
System.out.println(a[0] + " " + b[0]);
}
```
**Choices**
- [ ] 10 20
- [x] 20 10
- [ ] 10 10
- [ ] Error
**Explanation:**
Inside swap function, the array variables 'a' & 'b' are passed by reference, so they are pointing to same references in the heap memory as of 'a' & 'b' variables inside main function.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/265/original/upload_30b26edaf41f106c5f23c653f55b87bd.png?1695923815" alt= “” width ="300" height="300">
---
### Question
Predict the output :
```java
static int[] fun(int[]a) {
a = new int[2];
a[0] = 50; a[1] = 60;
return a;
}
public static void main(String args[]) {
int[]a = {10,20,30};
a = fun(a);
System.out.println(a[0]);
}
```
**Choices**
- [ ] 10
- [x] 50
- [ ] Error
**Explanation:**
* When fun method is called on array a, then a new integer array is allocated on the heap memory.
* But since, we are returning the new array in the main method, so now the changes done in fun method persists.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/266/original/upload_ee2fe92543bb6f84908886e2144ef3d2.png?1695923985" alt= “” width ="300" height="300">
---
### Question
Predict the output :
```java
static void test(int[]a) {
a = new int[2];
a[0] = 94;
}
public static void main(String args[]) {
int[]a = {10,20,30};
test(a);
System.out.println(a[0]);
}
```
**Choices**
- [x] 10
- [ ] 94
- [ ] Error
**Explanation:**
Inside the test function, a new integer array with length 2 is allocated on the heap memory, and the reference to this array is assigned to the parameter variable a. Hence, now the variable 'a' inside test function and main function point to different references.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/267/original/upload_4bebf48ccf793236b9b7077d14c2b3c5.png?1695924086" alt= “” width ="300" height="300">

View File

@@ -0,0 +1,454 @@
# Sorting
## Introduction
**Sorting** is an arrangement of data in particular order on the basis of some parameter
### Example 1:
```
A[ ] = { 2, 3, 9, 12, 17, 19 }
```
The above example is sorted in ascending order on the basis of magnitude.
### Example 2:
```
A[ ] = { 19, 6, 5, 2, -1, -19 }
```
The above example is sorted in descending order on the basis of magnitude.
### Question
Is the array { 1, 13, 9 , 6, 12 } sorted ?
**Choices**
- [x] Yes
- [ ] No
In the above quiz, array is sorted in ascending order on the basis of count of factors. Count of factors for the above array is { 1, 2, 3, 4, 6 }.
**Sorting** is essential for organizing, analyzing, searching, and presenting data efficiently and effectively in various applications and contexts.
### Problem 1 : Minimize the cost to empty array
Given an array of **n** integers, minimize the cost to empty given array where cost of removing an element is equal to **sum of all elements left in an array**.
### Example 1
```plaintext
A[ ] = { 2, 1, 4 }
Ans = 11
```
**Explanation**
After removing 4 cost = 4+2+1 = 7
After removing 2 cost = 2+1 = 3
After removing 1 cost = 1 = 1
Total cost = 11
### Question
Minimum cost to remove all elements from array {4, 6, 1} ?
**Choices**
- [ ] 11
- [ ] 15
- [x] 17
- [ ] 21
After removing 6 cost = 4+6+1 = 11
After removing 4 cost = 4+1 = 5
After removing 1 cost = 1 = 1
Total cost = 17
### Question
Minimum cost to remove all elements from array[] = {3, 5, 1, -3}
**Choices**
- [ ] 4
- [x] 2
- [ ] 0
- [ ] 18
After removing 5 cost = 5+3+1+(-3) = 6
After removing 3 cost = 3+1+(-3) = 1
After removing 1 cost = 1+(-3) = -2
After removing -3 cost = -3) = -3
Total cost = 2
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Problem 1 Solution Approach
**Observation**
* Start removing from the largest element.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/455/original/remove.jpeg?1681489808)
Here we can see if we have to minimise the cost we should add the largest number minimum number of times, that implies it should be the first one to be removed.
The formula would be **$\sum$(i+1)\*arr[i]** where **i** is the index.
Follow the below steps to solve the problem.
* **Sort** the data in descending order.
* Initialise the **ans** equal to 0.
* Run a loop for i from 0 to **n** 1, where **n** is the size of the array.
* For every element add **arr[i]\*i** to the ans.
#### Pseudocode
```cpp
int calculate_cost(int arr[], int n) {
reverse_sort(arr);
int ans = 0;
for (int i = 0; i < n; i++) {
ans += i * arr[i];
}
return ans;
}
```
#### Time and Space Complexity
-- TC - O(nlogn)
-- SC - O(n)
### Problem 2 : Find count of Noble Integers
Given an array of distinct elements of size n, find the count of **noble integers**.
> Note: arr[i] is **noble** if count of elements smaller than arr[i] is equal to arr[i] where arr[i] is element at index i.
**Example 1**
```plaintext
A[ ] = { 1, -5, 3, 5, -10, 4}
Ans = 3
```
**Explanation**
For arr[2] there are three elements less than 3 that is 1, -5 and -10. So arr[0] is noble integer.
For arr[3] there are five elements less than 5 that is 1, 3, 4, 5, -5 and -10. So arr[3] is noble integer.
For arr[5] there are four elements less than 4 that is 1, 3, -5 and -10. So arr[5] is noble integer.
In total there are 3 noble elements.
### Question
Count the number of noble integers in the array. A = { -3, 0, 2 , 5 }
**Choices**
- [ ] 0
- [x] 1
- [ ] 2
- [ ] 3
**Explanation:**
For arr[2] there are two elements less than 2 that is -3 and 0. So arr[2] is noble integer.
In total there are 2 noble elements.
:::warning
Please take some time to think about the Brute Force solution approach on your own before reading further.....
:::
### Problem 2 : Bruteforce Solution
#### Observation
Iterate through every element in the array, for every element count the number of smaller elements.
#### Pseudocode
```cpp
int find_nobel_integers(int arr[], int n) {
int ans = 0;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[j] < arr[i])
count++;
}
if (count == arr[i]) {
ans++;
}
}
return ans;
}
```
#### Time and Space Complexity
-- TC - O(N^2)
-- SC - O(1)
### Problem 1 Optimised Solution
#### Optimised Solution - 1
* Hint 1: What is the extra work being done?
Expected: For every element, we are using an extra loop for calculating the count of smaller elements.
* Hint 2: Can sorting the array help here?
#### Observation:
If we sort the data all elements smaller than the element at index i will be on from index **0 to i-1**. So total number of smaller elements will be equal to **i**.
#### Pseudocode
```cpp
int find_nobel_integers(int arr[], int n) {
sort(arr);
int ans = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == i) {
ans = ans + 1;
}
}
return ans;
}
```
#### Time and Space Complexity
-- TC - O(nlogn)
-- SC - O(1)
### Problem 3 Find count of nobel integers (Not Distinct)
Given an array of size n, find the count of noble integers.
> Note: Same as previous question, but all elements need not to be distinct
### Question
Count the no of noble integers in the array. A = { -10, 1, 1, 3, 100 }
**Choices**
- [ ] 1
- [x] 3
- [ ] 2
- [ ] 4
**Explanation:**
For arr[1] and arr[2] there is one element less than 1. So arr[1] and arr[2] are noble integers.
Similarly arr[3] will be the npble lement as there are 3 elements less than 3.
So in total 3 elements are noble integers.
### Question
Count the no of noble integers in the array
A = { -10, 1, 1, 2, 4, 4, 4, 8, 10 }
**Choices**
- [ ] 4
- [x] 5
- [ ] 6
- [ ] 7
**Explanation:**
arr[1], arr[2], arr[4], arr[5], arr[6] are the noble elements here.
### Question
Count the no of noble integers in the array
A = { -3, 0, 2, 2, 5, 5, 5, 5, 8, 8, 10, 10, 10, 14 }
**Choices**
- [ ] 4
- [ ] 5
- [ ] 6
- [x] 7
**Explanation:**
For arr[8] and arr[9] there are eight elements less than 8 that is -3, 0, 2, 5. So arr[8] and arr[9] are noble integers.
Similarly arr[9], arr[10], arr[11], ar[12] are noble elements.
So in total 6 elements are noble integers.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Problem 3 Solution
#### Observation
* If the current element is same as previous element then the total number of smaller elements will be same as previous element.
* If current element is not equal to previous element then the total number of smaller elements is equal to its index.
#### Pseudocode
```cpp
int find_nobel_integers(int arr[], int n) {
sort(arr);
int count = 0, ans = 0;
if (arr[0] == 0) ans++;
for (int i = 1; i < n; i++) {
if (arr[i] != arr[i - 1])
count = i;
if (count == arr[i])
ans++;
}
return ans;
}
```
#### Time and Space Complexity
-- TC - O(nlogn)
-- SC - O(1)
## Sorting Algorithm - Selection Sort
A sorting algorithm is a method of reorganizing the elements in a meaningful order.
> Imagine this. You are asked to arrange students according to their increasing heights.
**Divide the queue of students into two parts arranged and unarranged.**
1. To begin with, place all the students in the unarranged queue.
2. From this unarranged queue, search for the shortest student and place him/her in the list of arranged students.
3. Again, from the unarranged queue, select the second-shortest student. Place this student in the arranged queue, just after the smallest student.
4. Repeat the above-given steps until all the students are placed into the arranged queue.
**Did you see what we just did here?**
We used the selection sort algorithm to arrange all the students in a height-wise order.
**To better understand selection sort, let's consider a list of Integers 5, 6, 4, 2.**
The steps to sort this list would involve
![](https://hackmd.io/_uploads/ByRkDJIR2.png)
#### Pseudocode:
```cpp
void selectionSort(int arr[], int size) {
int i, j, minIndex;
for (i = 0; i < size - 1; i++) {
// set minIndex equal to the first unsorted element
minIndex = i;
//iterate over unsorted sublist and find the minimum element
for (j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// swapping the minimum element with the element at minIndex to place it at its correct position
swap(arr[minIndex], arr[i]);
}
}
```
#### TC & SC
**Time Complexity:** O(N<sup>2</sup>) since we have to iterate entire list to search for a minimum element everytime.
For 1 element, N iterations,
For N elements, N<sup>2</sup> iterations.
**Space Complexity:** O(1)
## Sorting Algorithm - Insertion Sort
**Insertion Sort** is one of the simplest sorting techniques which you might have used in your daily lives while arranging a deck of cards.
> So without going into how this algorithm works, lets think about how you would usually go about arranging the deck of cards?
**Say you are given 10 cards, 1 to 10 of spades, all shuffled, and you want to sort these cards.**
1. You would basically pick any random card(e.g. 7), and place it into your left hand, assuming the left hand is meant to carry the sorted cards.
2. Then you would pick another random card, say 2, and place 2 in the correct position on your left hand, i.e. before 7.
3. Then again if you pick 5, you would place it between 2 and 7 on your left hand, and this way we know we are able to sort our deck of cards. Since we insert one element at a time in its correct position, hence its name “Insertion Sort”.
#### Dry Run
E.g. if elements were in order:
```3, 5, 2```
You can start by picking 3, and since there is no element to the left of 3, we can assume it is in the correct place.
Array:
```3, 5, 2```
You can pick 5, you compare 5 with 3, and you find 5 is in the correct order amongst the array of [3, 5].
Array:
```3, 5, 2```
Then you pick 2, you find the place in the left side array of [3,5] to place this 2. Since 2 must come before 3, we insert 2 before 3.
Array:
```2, 3, 5 →```
Which is a sorted order.
#### Approach
Line 2: We dont process the first element, as it has nothing to compare against.
Line 3: Loop from i=1 till the end, to process each element.
Line 4: Extract the element at position i i.e. array[i]. Let it be called E.
Line 5: To compare E with its left elements, loop j from i-1 to 0
Line 6, 7: Compare E with the left element, if E is lesser, then move array[j] to right by 1.
Line 8: Once we have found the position for E, place it there.
#### Pseudocode
```cpp
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) { // Start from 1 as arr[0] is always sorted
Int currentElement = arr[i];
Int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > currentElement) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Finally place the Current element at its correct position.
arr[j + 1] = currentElement;
}
}
```
#### TC & SC
**Time Complexity:**
**Worst Case:** O(N^2), when the array is sorted in reverse order.
**Best Case:** O(N), when the data is already sorted in desied order, in that case there will be no swap.
Space Complexity: O(1)
**Note**
1. Both Selection & Insertion are in-place sorting algorithms, means they don't need extra space.
2. Since the time complexity of both can go to O(N^2), it is only useful when we have a lesser number of elements to sort in an array.

View File

@@ -0,0 +1,382 @@
# String
A string can be defined as a sequence of characters or in other words we can say that it is an array of characters.
**Example**
Below are the examples of string:
```
"Welcome to Scaler"
"Hello World!"
```
**Note:** String is represented using double quote i.e, `""`. All the characters of string must be inside this quote.
**Character**
A character is a single symbol that represents a letter, number, or other symbol in a computer's character set. Characters are used to represent textual data, and they are typically represented using its ASCII value.
**Example**
```
'a'
'B'
'1'
'_'
```
Computer store everything in binary. So, how do we store strings in computer?
Each character has corresponding decimal value associated to it which is known as ASCII value.
**'A' to 'Z'** have ASCII from **65 to 90**
**'a' to 'z'** have ASCII from **97 to 122**
**'0' to '9'** have ASCII from **48 to 57**
Each character '?', '!', '\*', ... has a corresponding ASCII associated with it.
### Some Operations:
**Note:** Characters can also be printed using its ascii value. for example, the ascii value of 'A' is 65, so it can be printed as
```CPP
char ch = (char)65;
print(ch);
/*
character 'A' gets printed; we are assigning Integer to Char,hence in some languages typecasting will be required.
*/
```
```cpp=
char ch = (char)('a' + 1);
/*
When we do arithmetic operations on characters, automatically computations happen on their ASCII values.
*/
print(ch); //'b' will get printed
```
```cpp=
int x = 'a';
/*
No need to typecast since we are assigning Char to Int (smaller data type to bigger, so it will not overflow)
*/
print(x); //97 will be printed
```
## Question 1 : Switch cases
Given a string consisting of only alphabets(either lowercase or uppercase). Print all the characters of string in such a way that for all lowercase character, print its uppercase character and for all uppercase character, print its lowercase character.
**TestCase**
**Input**
```
"Hello"
```
**Output**
```
"hELLO"
```
**Explanation**
Here, there is only one uppercase character present in the string i.e, 'H' so convert it to lowercase character. All other characters are in lowercase, hence they are converted into uppercase characters.
### Question
What is the output for String = "aDgbHJe" ?
**Choices**
- [ ] ADGBHJE
- [ ] aDgbHJe
- [x] AdGBhjE
- [ ] adgbhje
---
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
**Observation**
The key observations are:
* Lowercase characters can be changed into uppercase by subtracting 32 from its ASCII values.
* Uppercase charactes can be changed into lowercase by adding 32 from its ASCII values.
The above points are derived from the fact that for every alphabet, the difference between its ascii value in lowercase and uppercase is 32.
#### Pseudocode
```cpp
Function toggle(char s[]) {
int n = s.size();
for (int i = 0; i < n; i++) {
if (s[i] >= 65 and s[i] <= 91) {
print(s[i] + 32);
} else {
print(s[i] - 32);
}
}
}
```
#### Complexity
Time Complexity- **O(N)**.
Space Complexity- **O(1)**.
## Substring
A substring is a contiguous sequence of characters within a string. A substring concept in string is similar to subarray concept in array.
**A substring can be:**
1. Continous part of string.
2. Full string can be a substring.
3. A single character can also be a subsring.
**Example**
Suppose, we have a string as
```
"abc"
```
There are total 6 substring can be formed from the above string. All substrings are
```
"a"
"b"
"c"
"ab"
"bc"
"abc"
```
### Question
How many total substrings will be there for the String "bxcd" ?
**Choices**
- [ ] 7
- [ ] 8
- [x] 10
- [ ] 9
---
**Explanation:**
All the substrings are as follows-
```
"b", "x", "c", "d", "bx", "xc", "cd", "bxc", "xcd", "bxcd"
```
We can also find the count using n*(n+1)/2.
### Question 2 Check Palindrome
Check whether the given substring of string **s** is palindrome or not.
A palindrome is the sequence of characters that reads the same forward and backward.for example, "nayan", "madam", etc.
**TestCase**
**Input**
```
s = "anamadamspe"
start = 3
end = 7
```
**Output**
```
true
```
**Explanation**
The substring formed from index 3 to 7 is "madam" which is palindrome.
### Question 2 Approach
#### Approach
Below is the simple algorithm to check whether the substring is palindrome or not:
* Initialize two indices *start* and *end* to point to the beginning and *end* of the string, respectively.
* While *start* is less than *end*, do the following:
* If the character at index *start* is not equal to the character at index *end*, the string is not a palindrome. Return false.
* Else, increment *start* and decrement *end*.
* If the loop completes without finding a non-matching pair, the string is a palindrome. Return true.
#### Pseudocode
```cpp
function ispalindrome(char s[], int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
} else {
start++;
end--;
}
}
return true;
}
```
#### Complexity
Time Complexity- **O(N)**.
Space Complexity- **O(1)**.
## Question 3 : Longest Palindromic substring
Given a string **s**, calculate the length of longest palindromic substring in **s**.
**TestCase**
**Input**
```
"anamadamm"
```
**Output**
```
5
```
**Explanation**
The substring "madam" of size 5 is the longest palindromic substring that can be formed from given string.
### Question
What is the length of longest palindromic substring within string "feacabacabgf" ?
**Choices**
- [ ] 6
- [ ] 3
- [x] 7
- [ ] 10
### Question
What is the length of longest palindromic substring within string "a d a e b c d f d c b e t g g t e" ?
**Choices**
- [ ] 6
- [ ] 3
- [x] 9
- [ ] 10
:::warning
Please take some time to think about the brute force solution approach on your own before reading further.....
:::
### Question 4 Brute Force Approach
The naive approach is to for all the substring check whether the string is palindrome or not. if it is palindrome and its size is greater than the previous answer(which is initially 0), then update the answer.
#### Pseudocode
```cpp
function longestPalindrome(char s[]) {
int N = s.size();
int ans = 0;
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
if (ispalindrome(s, i, j)) {
ans = max(ans, j - i + 1);
}
}
}
return ans;
}
```
#### Complexity
Time Complexity- **O(N^3)**.
Space Complexity- **O(1)**.
#### Idea
The key idea here is that:
* For odd length substring, take every character as a center and expand its center and gets maximum size palindromic substring.
* For even length substring, take every adjacent character as a center and expand its center and get maximum size palindromic substring.
#### Pseudocode
```cpp
function longestpalindrome(char s[]) {
int maxlength = 0;
int N = s.size();
for (int c = 0; c < N; c++) {
//odd length string
int left = c, right = c;
while (left >= 0 and right < N) {
if (s[left] != s[right]) {
break;
}
left--;
right++;
}
maxlength = max(maxlength, right - left - 1);
//even length string
left = c;
right = c + 1;
while (left >= 0 and right < N) {
if (s[left] != s[right]) {
break;
}
left--;
right++;
}
maxlength = max(maxlength, right - left - 1);
}
return maxlength;
}
```
#### Complexity
Time Complexity- **O(N^2)**.
Space Complexity- **O(1)**.
### Immutability of Strings
In languages like **Java, C#, JavaScript, Python and Go**, strings are immutable, which means it's **value can't be changed**.
```cpp=
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
```
![](https://hackmd.io/_uploads/SkGyXywRh.png)
* As seen above, because strings with the same content share storage in a single pool, this minimize creating a copy of the same value.
* That is to say, once a String is generated, its content cannot be changed and hence changing content will lead to the creation of a new String.
```cpp=
//Changing the value of s1
s1 = "Java";
//Updating with concat() operation
s2.concat(" World");
//The concatenated String will be created as a new instance and an object should refer to that instance to get the concatenated value.
String newS3 = s3.concat(" Scaler");
System.out.println("s1 refers to " + s1);
System.out.println("s2 refers to " + s2);
System.out.println("s3 refers to " + s3);
System.out.println("newS3 refers to " + newS3);
```
**Output**
```cpp=
s1 refers to Java
s2 refers to Hello
s3 refers to Hello
news3 refers to Hello Scaler
```
![](https://hackmd.io/_uploads/BkzzEkPC3.png)
As shown above, considering the example:
* String s1 is updated with a new value and that's why a new instance is created. Hence, s1 reference changes to that newly created instance "Java".
* String s2 and s3 remain unchanged as their references were not changed to a new instance created after performing concat() operation.
* "Hello World" remains unreferenced to any object and lost in the pool as s2.concat() operation (in line number 5) is not assigned to any object. That's why there is a reference to its result.
* String newS3 refers to the instance of s3.concat() operation that is "Hello Scaler" as it is referenced to new object newS3.
**Hence, Strings are immutable and whenever we change the string only its reference is changed to the new instance.**

View File

@@ -0,0 +1,565 @@
# Time Complexity
**Topics covered :**
1. Log Basics + Iteration Problems
2. Comparing Iterations using Graph
3. Time Complexity - Definition and Notations (Asymptotic Analysis - Big O)
6. TLE
7. Importance of Constraints
:::success
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
:::
## Basics of Logarithm
Q. What is the meaning of LOG ?
A. Logarithm is the inverse of exponential function.
Q. How to read the statement "log<sub>b</sub>(a)"?
A. To what value we need to raise b, such that we get a.
If log<sub>b</sub>(a) = c, then it means b<sup>c</sup> = a.
**Examples**
1. log<sub>2</sub>(64) = 6
**How?** 2 raise to the power what is 64? It's 6 since 2<sup>6</sup> = 64
2. log<sub>3</sub>(27) = 3
3. log<sub>5</sub>(25) = 2
4. log<sub>2</sub>(32) = 5
Now, calculate the floor values of the following logarithms.
5. log<sub>2</sub>(10) = 3
6. log<sub>2</sub>(40) = 5
**Note:**
If 2<sup>k</sup> = N => log<sub>2</sub>(N) = k
Let's look at one more formula:
1. What is log<sub>2</sub>(2^6)?
A. 6
Explanation: To what power you should raise 2, such that it equates to 2^6.
2. What is log<sub>3</sub>(3^5)?
A. 5
Explanation: To what power you should raise 3, such that it equates to 3^5.
**Note:**
In general, log<sub>a</sub>(a^N) = N
**Question**:
Given a positive integer N, how many times do we need to divide it by 2 (Consider only integer part) until it reaches 1.
For example, N = 100
100 -> 50 -> 25 -> 12 -> 6 -> 3 -> 1
Hence, 6 times.
What if N = 324?
324 -> 162 -> 81 -> 40 -> 20 -> 10 -> 5 -> 2 -> 1
Hence, 8 times.
### **Question**
How many times we need to divide 9 by 2 till it reaches 1 ?
**Choices**
- [ ] 4
- [x] 3
- [ ] 5
- [ ] 2
**Explanation:**
N --> N/2 --> N/4 --> N/8 --> ...... 1
N/2^0 --> N/2^1 --> N/2^2 --> N/2^3 --> ...... N/2^K
N/2^K = 1
K = log<sub>2</sub>(N)
### **Question**
How many times we need to divide 27 by 2 till reaches 1 ?
**Choices**
- [ ] 5
- [x] 4
- [ ] 3
- [ ] 6 -->
### **Question**
How many iterations will be there in this loop ?
```pseudocode
N > 0
i = N;
while (i > 1) {
i = i / 2;
}
```
**Choices**
- [ ] N
- [ ] N/2
- [ ] sqrt(N)
- [x] log(N)
**Explanation:**
The given loop starts with the initial value of i as N and continues until i becomes less than or equal to 1, by repeatedly dividing i by 2 in each iteration.
Hence, Iterations are log(N)
### **Question**
How many iterations will be there in this loop
```
for(i=1; i<N; i=i*2)
{
...
}
```
**Choices**
- [ ] infinite
- [ ] sqrt(N)
- [ ] 0
- [x] log(N)
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/486/original/AsFKtNz.png?1681540630)
### **Question**
How many iterations will be there in this loop ?
```pseudocode
N>=0
for(i=0; i<=N; i = i*2)
{
...
}
```
**Choices**
- [x] Infinite
- [ ] N/2
- [ ] 0
- [ ] log(N)
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/485/original/DlI3rSU.png?1681540550)
### Question
How many iterations will be there in this loop
```
for(i=1; i<=10; i++){
for(j=1; j<=N; j++){
/ ......../
}
}
```
**Choices**
- [ ] N + N
- [ ] N^2
- [x] 10 * N
- [ ] N + 10
> Multiplying the loops each time might not be correct. In this case, it works.
### **Question**
How many iterations will be there in this loop
```
for(i=1; i<=N; i++){
for(j=1; j<=N; j++){
...
}
}
```
**Choices**
- [ ] 2 * N
- [x] N * N
- [ ] 10 * N
- [ ] N * sqrt(N)
**Explanation:**
The given loop consists of two nested loops. The outer loop iterates from i=1 to i=N, and the inner loop iterates from j=1 to j=N.
For each value of i in the outer loop, the inner loop will iterate N times. This means that for every single iteration of the outer loop, the inner loop will iterate N times.
Therefore, the correct answer is N * N.
### **Question**
How many iterations will be there in this loop
```
for(i=1; i <= N; i++){
for(j=1; j <= N; j = j*2){
...
}
}
```
**Choices**
- [ ] (N^2 + 2N + 1)/2
- [x] N * log(N)
- [ ] N^2
- [ ] N(N+1)/2
**Explanation:**
The given loop consists of two nested loops. The outer loop iterates from i=1 to i <= N, and the inner loop iterates from j=1 to j <= N, with j being incremented by a power of 2 in each iteration.
For each value of i in the outer loop, the inner loop iterates in powers of 2 for j. This means that the inner loop will iterate for j=1, 2, 4, 8,... up to the largest power of 2 less than or equal to N, which is log<sub>2</sub>(N).
Therefore, the correct answer is N * log<sub>2</sub>(N).
### **Question**
How many iterations will be there in this loop ?
```
for(i = 1; i <= 4; i++) {
for(j = 1; j <= i ; j++) {
//print(i+j)
}
}
```
**Choices**
- [ ] log(N)
- [ ] 2N
- [x] 10
- [ ] N -->
### **Question**
How many Iterations will be there in this loop ?
```
for(i = 1; i <= N; i++) {
for(j = 1; j <= i ; j++) {
//print(i+j)
}
}
```
**Choices**
- [ ] log(N)
- [x] N*(N+1)/2
- [ ] (N-1)/2
- [ ] N/2
### **Question**
How many iterations will be there in this loop
```
for(i=1; i<=N; i++){
for(j=1; j<=(2^i); j++)
{
...
}
}
```
**Choices**
- [ ] 2^N
- [x] 2 * (2^N - 1)
- [ ] 2 * (2N)
- [ ] infinite
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/031/487/original/Cei0j2o.png?1681540943)
This is GP, where a=2, r=2 and no. of terms are N.
Consider two algorithms Algo1 and Algo2 given by Kushal and Ishani respectively.
Considering **N** to be the size of the input:
Algo|Number of Iterations
-|-
Algo1|100 * log(N)
Algo2|N / 10
Now, see the graph of the two algorithms based on N.
Graphs info:
* X-axis plots N (input size)
* Red line (Algo 1): **100 * log(N)**
* Blue line (Algo 2): **N/10**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/052/original/time-complexity-2-image-2.png?1683815171)
### Observations:
Assuming both graphs intersect at N = 3500, let's draw some observations.
For small input (N <= 3500), Ishani's algorithm performed better.
For large input (N > 3500), Kushal's algorithm performed better.
**In today's world data is huge**
* IndiaVSPak match viewership was **18M**.
* Baby Shark video has **2.8B** views.
Therefore, Kushal's algorithm won since it has lesser iterations for huge data value.
*We use **Asymptotic Analysis** to estimate the performance of an Algorithm when Input is huge.*
**Asymptotic Analysis** OR **Big(O)** simply means analysing perfomance of algorithms for **larger inputs**.
### Calculation of Big(O)
**Steps** for **Big O** calculation are as follows:
* Calculate **Iterations** based on **Input Size**
* Ignore **Lower Order Terms**
* Ignore **Constant Coefficients**
**Example-**
Kushal's algo took **100 * log<sub>2</sub>N** iterations: Big O is **O(log<sub>2</sub>N)**
Ishani's algo took **N / 10** iterations: Big O is **O(N)**
**For example**,
1. Iterations: 4N^2 + 3N + 1
2. Neglect lower order term: 3N + 1; Remaining Term: 4N^2
3. Neglect constant 4
Big O is O(N^2)
### Comparsion Order:
log(N) < sqrt(N) < N < N log(N) < N sqrt(N) < N^2 < N^3 < 2^(N) < N! < N^N
**Using an example**
N = 36
5 < 6 < 36 < 36\*5 < 36\*6 < 36<sup>2</sup> < 36<sup>3</sup> < 2<sup>36</sup> < 36! < 36<sup>36</sup>
**Ques:** What is the big notation time complexity of the following expression?
4N^2 + 3N + 6 sqrt(N) + 9 log_2(N) + 10
Ans = O(N^2)
### Question
F(N) = 4N + 3Nlog(N) + 1
O(F(N)) = ?
**Choices**
- [ ] N
- [x] N * logN
- [ ] Constant
- [ ] N^2
### Question
F(N) = 4NlogN + 3NSqrt(N) + 10^6
O(F(N)) = ?
**Choices**
- [ ] N
- [ ] N * logN
- [ ] N^2
- [x] N * Sqrt(N)
## Why do we neglect Lower Order Terms
Let's say the number of Iterations of an Algorithm are: N<sup>2</sup>+10N
N|Total Iterations = N<sup>2</sup>+10N|Lower Order Term = 10N|% of 10N in total iterations = 10N/(N<sup>2</sup>+10N)*100
-|-|-|-
10|200|100|50%
100|10<sup>4</sup>+10<sup>3</sup>|10<sup>3</sup>|Close to 9%
10000|10<sup>8</sup>+10<sup>5</sup>|10<sup>5</sup>|0.1%
## Conclusion
We can say that, as the **Input Size** increases, the contribution of **Lower Order Terms** decreases.
### Why do we neglect Constant Coefficients
When the comparison is on very larger input sizes, the constants do not matter after a certain point. For example,
| Algo 1(Nikhil)|Algo 2(Pooja)|Winner for Larger Input|
| -------- | -------- | -------- |
| 10 * log<sub>2</sub> N | N | Nikhil |
| 100 * log<sub>2</sub> N | N | Nikhil |
| 9 * N | N<sup>2</sup> | Nikhil |
| 10 * N | N<sup>2</sup> / 10| Nikhil |
| N * log<sub>2</sub> N | 100 * N | Pooja |
## Issues with Big(O)
### Issue 1
**We cannot always say that one algorithm will always be better than the other algorithm.**
**Example:**
* Algo1 (Iterations: 10<sup>3</sup> N) -> Big O: O(N)
* Algo2 (Iterations: N<sup>2</sup>) -> Big O: O(N<sup>2</sup>)
* Algo 1 is better than Algo 2 but only for large inputs, not for small input sizes.
|Input Size (N)| Algo 1 (10<sup>3</sup>) | Algo 2 (N<sup>2</sup>) | Optimised|
| --| --| --| --|
|N = 10| 10<sup>4</sup>| 10<sup>2</sup>|Algo 2|
|N = 100| 10<sup>5</sup>| 10<sup>4</sup>|Algo 2|
|N = 10<sup>3</sup>| 10<sup>6</sup>| 10<sup>6</sup>|Both are same|
|N = 10<sup>3</sup> + 1| (10<sup>3</sup>)*(10<sup>3</sup> + 1)| (10<sup>3</sup> + 1)*(10<sup>3</sup> + 1)|Algo 1|
|N = 10<sup>4</sup>| 10<sup>7</sup>| 10<sup>8</sup>|Algo 1|
**Claim:** For all large inputs >= 1000, Algo 1 will perform better than Algo 2.
### Issue 2
If 2 algorithms have same higher order terms, then Big O is not capable to identify algorithm with higher iterations.
Consider the following questions -
Count the number of odd elements from 1 to N
Code 1: Iterations: N
```pseudocode
for (int i = 1; i <= N; i++) {
if (i % 2 != 0) {
c = c + 1;
}
}
```
Code 2: Iterations: N/2
```pseudocode
for (int i = 1; i <= N; i = i + 2) {
c = c + 1;
}
```
In both, Big O is O(N) but we know second code is better.
## Time Limit Exceeded Error
* **Is it necessary to write the entire code and then test it to determine its correctness?**
* **Can we assess the logic's viability before writing any code?**
### Online Editors and Why TLE occurs
* Codes are executed on online servers of various platforms such as Codechef, Codeforces, etc.
* The **processing speed** of their server machines is **1 GHz** which means they can perform **10<sup>9</sup> instructions** per second.
* Generally, **codes should be executed in 1 second**.
Using this information, we can say at max our code should have at most **10<sup>9</sup> instructions**.
Instructions means any single operation such as multiplication, addition, function calling, single variable declaration, etc.
### Question
Consider the following code:
Find the total number of instructions in the code below (Note that the instructions involved in the loop part are repetitive)
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/034/057/original/time-complexity-2-image-7.png?1683815308)
**Conclusion:**
Calculating Instructions is tedious job, rather we can make certain approximations in terms of number of Iterations.
### Approximation 1
Suppose the **code** has as small as **10 Instructions in 1 Iteration**.
Therefore,
| Instructions | Iterations |
| -------- | -------- |
| 10 | 1 |
| 10^9 | 10^8 |
In **1 sec**, we can have at max **10<sup>9</sup> Instructions** or **10<sup>8</sup> Iterations**, provided there are **10 Instructions / Iteration**.
### Approximation 2
Suppose the **code** has as huge as **100 Instructions in 1 Iteration**.
Therefore,
| Instructions | Iterations |
| -------- | -------- |
| 100 | 1 |
| 10^9 | 10^7 |
In **1 sec**, we can have at max **10<sup>9</sup> Instructions** or **10<sup>7</sup> Iterations**, provided there are **100 Instructions / Iteration**.
### Conclusion:
In general, our code can have **10<sup>7</sup>** to **10<sup>8</sup> Iterations** to be able to run in **1 sec**.
## General Structure to solve a question
### How to approach a problem?
* Read the **Question** and **Constraints** carefully.
* Formulate an **Idea** or **Logic**.
* Verify the **Correctness** of the Logic.
* Mentally develop a **Pseudocode** or rough **Idea of Loops**.
* Determine the **Time Complexity** based on the Pseudocode.
* Assess if the time complexity is feasible and won't result in **Time Limit Exceeded (TLE)** errors.
* **Re-evaluate** the **Idea/Logic** if the time constraints are not met; otherwise, proceed.
* **Code** the idea if it is deemed feasible.
### Importance of Constraints
#### Question
If 1 <= N <= 10<sup>5</sup>,
then which of the following Big O will work ?
| Complexity | Iterations | Works ? |
| -------- | -------- | -------- |
| O(N<sup>3</sup>) | (10<sup>5</sup>)<sup>3</sup> | No |
| O(N<sup>2</sup>) log N | (10<sup>10</sup>)*log 10<sup>5</sup> | No |
| O(N<sup>2</sup>) | (10<sup>5</sup>)<sup>2</sup> | No |
| O(N * log N) | (10<sup>5</sup>)*log 10<sup>5</sup> | Yes |
#### Question
If 1 <= N <= 10<sup>6</sup>,
then which of the following Big O will work ?
| Complexity | Iterations | Works ? |
| -------- | -------- | -------- |
| O(N<sup>3</sup>) | (10<sup>6</sup>)<sup>3</sup> | No |
| O(N<sup>2</sup>) log N | (10<sup>12</sup>)*log 10<sup>6</sup> | No |
| O(N<sup>2</sup>) | (10<sup>12</sup>) | No |
| O(N * log N) | (10<sup>6</sup>)*log 10<sup>6</sup> ~ 10<sup>7</sup> | May Be |
| O(N) | (10<sup>6</sup>) | Yes |
#### Question
If constraints are
1 <= N <= 100, N<sup>3</sup> will also pass.
If constraints are
1 <= N <= 20, 2<sup>N</sup> will also pass.
**Note:**
In Online Assessments, if we are not getting any other approach to a problem, try out the code; it may pass some test cases, which is better than nothing.

View File

@@ -0,0 +1,315 @@
# Refresher : 1D Arrays
# Introduction To Arrays
---
## Definition
Array is the sequential collection of same types of data. The datatype can be of any type i.e, int, float, char, etc. Below is the declaration of the array:
```java
int arr[] = new int[5];
```
It can also be declared as:
```java
int[] arr = new int[5]
```
Here, int is the datatype, arr is the name of the array and n is the size of an array.
We can access all the elements of the array as arr[0], arr[1] ….. arr[n-1].
**Note:** Array indexing starts with 0.
---
### Question
Maximum index of array of size N is ?
Choose the correct answer
**Choices**
- [ ] 1
- [ ] 0
- [x] N-1
- [ ] N
---
### Question
Given an array as arr = {3,4,1,5,1}. What is ths sum of all elements in the array?
Choose the correct answer
**Choices**
- [ ] 12
- [ ] 13
- [x] 14
- [ ] 15
---
## Question 1
Take an integer array **arr** of size **N** as input and print its sum.
#### TestCase
##### Input
```java
N = 5
arr = {1,2,3,4,5}
```
##### Output
```plaintext
15
```
#### Explanation
To calculate the sum of all the elements in the array, we need a variable say **sum** which is initially zero. Then iterate all the elements and adding them to **sum**.
#### PseudoCode
```java
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + arr[i];
}
System.out.println("Sum is " + sum);
```
\
---
### Question
Given an array as arr = {3,4,1,5,1}. Find the maximum element.
Choose the correct answer
**Choices**
- [ ] 3
- [ ] 4
- [x] 5
- [ ] 1
---
## Question 2
Take an integer array **arr** of size **N** as input and print its maximum element.
#### TestCase
##### Input
```plaintext
N = 5
arr = {1,2,3,4,5}
```
##### Output
```plaintext
5
```
#### PseudoCode
```java
int maximum_element = 0;
for (int i = 0; i < n; i++) {
if (maximum_element < arr[i]) maximum_element = arr[i];
}
system.out.println("Sum is " + maximum_element);
```
---
### Question
What will be the output of the above code with
N = 5
arr = {-3, -7, -2, -10, -1}
array as input ?
Choose the correct answer
**Choices**
- [ ] -7
- [ ] -1
- [x] 0
- [ ] 2
**Explanation**
Initially we have assumed 0 as the max element in the array and in the given case, all the element is smaller than 0. So, the max element is 0.
---
### Question 2 PseudoCode
**Note:** We can fix it by initially assigning arr[0] to the maximum_element.
So the updated pseudocode is:
```java
int maximum_element = arr[0];
for (int i = 0; i < n; i++) {
if (maximum_element < arr[i]) maximum_element = arr[i];
}
system.out.println("Sum is " + maximum_element);
```
---
## Question 3
Take an integer array **arr** of size **N** as input and return its minimum element.
#### TestCase
##### Input
```java
N = 5
arr = {1,2,3,4,5}
```
##### Output
```plaintext
1
```
#### PseudoCode
```java
public static int findMin(int arr[], int n) {
int minimum_element = arr[0];
for (int i = 0; i < n; i++) {
if (minimum_element > arr[i]) minimum_element = arr[i];
}
return minimum_element;
}
```
---
## Question 4
Take an integer array **arr** of size **N** as input and check whether an integer **k** is present in that or not.
#### TestCase
##### Input
```java
N = 5
arr = {1,2,3,4,5}
k = 4
```
##### Output
```plaintext
true
```
#### Explanation
To check whether an integer **k** is present in the array or not, we need to check each element and compare it with **k**. If none of the element is equal to **k**,then return false.
#### PseudoCode
```java
public static boolean findK(int arr[], int n, int k) {
for (int i = 0; i < n; i++) {
if (arr[i] == k) return true;
}
return false;
}
```
---
### Question
Given an array as arr = {3,4,1,5,1}. What is the frequency of 1?
Frequency of any element is defined as the number of occurences of that element in the array.
Choose the correct answer
**Choices**
- [ ] 0
- [ ] 1
- [x] 2
- [ ] 3
---
## Question 5
Take an integer array **arr** of size **N** as input. Return the frequency of **K** in the array.
#### TestCase
##### Input
```java
N = 6
arr = {1,2,3,4,5,1}
k = 1
```
##### Output
```plaintext
2
```
**Note:** Here frequency is the number of times the element **k** occurs in the array.
#### PseudoCode
```java
public static int frequencyK(int arr[], int n, int k) {
int frequency = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == k) frequency++;
}
return frequency;
}
```
---
## Question 6
Given an integer array as an input, return the frequency count of the array.
#### TestCase
##### Input
```java
arr = {1,1,2,1,3,1,3}
```
##### Output
```plaintext
{4,4,1,4,2,4,2}
```
#### PseudoCode
```java
int[] frecount(int arr[]) {
int n = arr.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = frequencyK(arr, n, arr[i]);
}
return ans;
}
```
---
## Question 7
Given an integer array as an input, check whether it is strictly increasing.
#### TestCase
##### Input
```plaintext
N = 5
arr = {1,2,3,4,5}
```
##### Output
```plaintext
true
```
##### Explanation
All the element in the array is in sorted order. So, we can say that it is in strictly increasing order.
As
```plaintext
1 < 2 < 3 < 4 < 5
```
#### PseudoCode
```java
public static boolean strictlyincreasing(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
if (arr[i] >= arr[i + 1]) return false;
}
return true;
}
```

View File

@@ -0,0 +1,445 @@
# Refresher : 2D Arrays
# 2D Arrays
- Store similar types of items
- Sequential storage of elements
- It has both length and breadth
## Real-Time Application Example of 2D Arrays
- Chess
- Theatre Seats
- Bus
- Egg Tray
- Tic Toe Game
## Syntax
```cpp
int mat[][] = new int[row][col];
```
In 2D arrays, we have square brackets in the declaration but in the 1D array we use one square bracket to declare it(`int[] ar=new int[]`) and in 2D matrix declaration first bracket is used to specify the number of rows and second is for the number of columns.
||||Rows||
|-|-| -------- | -------- | -------- |
|| |&darr; |&darr; |&darr; |
||&rarr;|**-**|**-**|**-**|
|**Columns**|&rarr;|**-**|**-**|**-**|
||&rarr;|**-**|**-**|**-**|
In the above matrix, we have 3 rows and 3 columns.
## Example
|-|-|-|-|
|-|-|-|-|
|**-**|**-**|**-**|**-**|
|**-**|**-**|**-**|**-**|
In the above matrix, we have 3 rows and 4 columns, and we can declare it by writing `int[][] mat = new int[3][4]`.
Here also zero-based indexing works,
| **Col** | 0 | 1 | 2 | 3 |
|:--------------:|:-----:|:-----:|:-----:|:-----:|
| **Row:** **0** | **-** | **-** | **-** | - |
| **1** | **-** | **-** | **-** | **-** |
| **2** | **-** | **-** | **-** | **-** |
## How a particular cell is represented in a matrix
Every cell is represented in the form mat[rowNo][colNo]
| **Col** | 0 | 1 | 2 | 3 |
|:--------------:|:---------:|:---------:|:---------:|:---------:|
| **Row:** **0** | mat[0][0] | mat[0][1] | mat[0][2] | mat[0][3] |
| **1** | mat[1][0] | mat[1][1] | mat[1][2] | mat[1][3] |
| **2** | mat[2][0] | mat[2][1] | mat[2][2] | mat[2][3] |
---
### Question
How to create a matrix with 5 columns and 7 rows?
**Choices**
- [ ] int[][] mat = new int[5][7];
- [x] int[][] mat = new int[7][5];
- [ ] int[] mat = new int[5][7];
---
### Question
If you have a matrix of size M * N, what is the index of the top left corner?
**Choices**
- [ ] [top][left]
- [ ] [0][N - 1]
- [x] [0][0]
- [ ] [M - 1][N - 1]
---
### Question
If you have a matrix of size M * N, what is the index of the bottom right corner?
**Choices**
- [ ] [bottom][right]
- [ ] [0][M - 1]
- [ ] [N - 1][M - 1]
- [x] [M - 1][N - 1]
---
## Print the top row of a matrix
Given a matrix of size N * M, print its top row.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution
Coordinates of the first row of the matrix are: (0,0), (0,1), (0,2), _ _ _ , (0, M - 1).
Here column Number keeps on changing from 0 to M - 1 and row Number is always 0.
### Pseudocode
```cpp
for(int col = 0; i < M; i++){
print(mat[0][i]);
}
```
---
## Print the leftmost column of a matrix
### Problem Statement
Given a matrix of size N * M, print its leftmost column.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution
Coordinates of the leftmost column of the matrix are:
(0,0),
(1,0),
(2,0),
_ ,
_ ,
_ ,
(N-1,0).
Here row Number keeps on changing from 0 to N - 1 and the column Number is always 0.
### Pseudocode
```cpp
for(int row = 0; row < N; row++){
print(mat[row][0]);
}
```
---
## Print matrix row by row
### Problem Statement
Given a matrix of size N * M, print row by row
### Understanding the problem statement
We have to print every row of the matrix one by one, first print the elements of the first row then print the next line character, then print its second-row elements and then again the next line character, and so on till the last row, in this way we have to print all the rows one by one.
### Pseudocode
```cpp
for(int row = 0; row < N; row++){
for(int col = 0; col < M; col++){
print(mat[row][col]);
}
print("\n");
}
```
---
## Print matrix column by column
### Problem Statement
Given a matrix of size N * M, print column by column
### Example
**Input:**
| **Col** | 0 | 1 | 2 |
|:--------------:|:---:|:---:|:---:|
| **Row:** **0** | 1 | 3 | -2 |
| **1** | 9 | 0 | 8 |
**Output:**
1 9
3 0
-2 8
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
## Pseudocode
```cpp
for(int col = 0; col < M; col++){
for(int row = 0; row < N; row++){
print(mat[row][col]);
}
print("\n");
}
```
---
## Matrix coding practice
### Java Code for printing matrix row by row and column by column
```java
import java.util.*;
public class Main {
public static void printRowByRow(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
for (int row = 0; row < n; row++) {
for (int col = 0; col < m; col++) {
System.out.print(mat[row][col] + " ");
}
System.out.println();
}
System.out.println("-----------------------------");
}
public static void printColByCol(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
for (int col = 0; col < m; col++) {
for (int row = 0; row < n; row++) {
System.out.print(mat[row][col] + " ");
}
System.out.println();
}
System.out.println("-----------------------------");
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();
int[][] mat = new int[n][m];
for (int row = 0; row < n; row++) {
for (int col = 0; col < m; col++) {
mat[row][col] = scn.nextInt();
}
}
printRowByRow(mat);
printColByCol(mat);
}
}
```
---
## Sum of matrix
### Problem statement
Given a matrix of size N * M as an argument, return its sum.
### Example:
**Input**
||||
|-|-|-|
|1|3|-2|
|9|0|8|
**Output:**
19
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### PseudoCode
```java
public static int sum(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
int sum = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < m; col++) {
sum = sum + mat[row][col];
}
}
return sum;
}
```
---
## Waveform printing
### Problem statement
Given a matrix of size N * M as an argument, print it in waveform.
### Example:
**Input**
|||||
|-|-|-|-|
|1|3|-2|7|
|9|0|8|-1|
|5|6|-2|3|
|3|4|0|2|
**Output:**
1 3 -2 7
-1 8 0 9
5 6 -2 3
2 0 4 3
### Understanding the problem statement
Waveform printing, you have to print the first row of the matrix as it is, then print the second row in reverse order, then print the third row as it is, then print the fourth row in reverse order and so on, in this way, you have to print all the rows of the matrix.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Approach
If the row number of a matrix is even then we have to print as it is, if the row number is odd then we have to print in reverse order.
### PseudoCode
```java
public static void wavePrint(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
for (int row = 0; row < n; row++) {
if(row%2==0){
for (int col = 0; col < m; col++) {
System.out.print(mat[row][col]+" ");
}
}
else{
for (int col = m - 1; col >= 0; col--) {
System.out.print(mat[row][col]+" ");
}
}
System.out.println();
}
}
```
---
## Row wise sum
### Problem statement
Given a matrix of size N * M as an argument, return a row-wise sum.
### Example:
|||||
|-|-|-|-|
|1|3|-2|7|
|9|0|8|-1|
|5|6|-2|3|
**Output:**
[9, 16, 12]
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Understanding the problem statement
Return the sum of every row in the form of an array.
### PseudoCode
```java
public static int[] rowWiseSum(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
int[] ans = new int[n];
for (int row = 0; row < n; row++) {
int sum=0;
for (int col = 0; col < m; col++) {
sum = sum + mat[row][col];
}
ans[row] = sum;
}
return ans;
}
```
---
## Column-wise max
### Problem statement
Given a matrix of size N * M as an argument, return col-wise max.
### Example:
|||||
|-|-|-|-|
|1|3|-2|7|
|9|0|8|-1|
|5|6|-2|3|
**Output:**
[9, 6, 8, 7]
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Understanding the problem statement
Return a maximum of every column in the form of an array.
### PseudoCode
```java
public static int[] colWiseMax(int mat[][]) {
int n = mat.length; // rows
int m = mat[0].length; // cols
int[] ans = new int[m];
for (int col = 0; col < m; col++) {
int max = mat[0][col];
for (int row = 0; row < n; row++) {
if(mat[row][col] > max){
max = mat[row][col];
}
}
ans[col] = max;
}
return ans;
}
```

View File

@@ -0,0 +1,423 @@
# Refresher: Arraylists
# Arrays
Arrays have some disadvantages:
- Fixed-size(we cannot increase or decrease size of array)
- Size should be known in advance.
Due to these arrays are not suitable for some situations.
---
## ArrayList
ArrayList have all the advantages of arrays with some additional features
- Dynamic size
- Does not require to know the size in advance.
## Examples
Here are some real-world examples where using an ArrayList is preferred in comparison to using arrays.
- Shopping list
- New tabs of the browser
- Youtube playlist
## Syntax
```java
ArrayList<Type> arr = new ArrayList<Type>();
```
- Here Type has to be a class, it can not be a primitive.
- Primitives can be int, long, double, or boolean.
- Instead of primitives we can use wrapper classes and custom objects, which means we can use Integer, Long, Double, String, etc.
---
## Basic Operations
### Inserting element
We can add an element in the arraylist using `add()` and it adds an element at the end of the list.
### Get
It will fetch elements from the ArrayList using an index.
### Size
`size()` will give us the size of the ArrayList.
### Remove
It removes the element from the ArrayList present at a particular index.
### Set
It updates the value of a particular index to the new value.
```java
import java.util.*;
import java.lang.*;
class Main{
public static void main(String args[]){
ArrayList<Integer> arr = new ArrayList<Integer>();
//printing ArrayList
System.out.println(arr);
// add
arr.add(2);
arr.add(-1);
arr.add(5);
System.out.println(arr);
//get
System.out.println("2nd element is: "+arr.get(2));
// System.out.println(arr.get(-1)); it gives an error as the -1 index does not exist for arr
// System.out.println(arr.get(3)); it gives an error as 3 index does not exist for arr
// Size
System.out.println("Size is: " + arr.size());
// Remove
arr.remove(1);
System.out.println(arr);
// Set
arr.set(1, 8);
System.out.println(arr);
}
}
```
**Output**
```plaintext
[]
[2, -1, 5]
2nd element is: 5
Size is: 3
[2, 5]
[2, 8]
```
---
# Taking Arraylist as an input
```java
import java.util.*;
import java.lang.*;
class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
// Taking ArrayList as input
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = sc.nextInt();
for(int i = 0 ; i < n ; i++){
int tmp = sc.nextInt();
arr.add(tmp);
}
System.out.println(arr);
}
}
```
---
## Problem Statement
Given an ArrayList as input, return an ArrayList of the multiples of 5 or 7.
## Example
**Input:** [1, 5, 3, 0, 7]
**Output:** [5, 0, 7]
## Solution
Iterate over the input ArrayList, and check if the element is divisible by 5 or 7 then simply add it to the result ArrayList.
## PsuedoCode
```java
import java.util.*;
import java.lang.*;
class Main{
public static ArrayList<Integer> multiples(ArrayList<Integer> arr){
ArrayList<Integer> ans = new ArrayList<Integer>();
for(int i = 0; i < arr.size(); i++){
int val = arr.get(i);
if(val % 5 == 0 || val % 7 == 0)
ans.add(val);
}
return ans;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
// Taking ArrayList as input
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = sc.nextInt();
for(int i = 0 ; i < n ; i++){
int tmp = sc.nextInt();
arr.add(tmp);
}
System.out.println(multiples(arr));
}
}
```
---
## Problem Statement
Given two integers A and B as input, return an ArrayList containing first B multiples of A.
## Example
**Input:** A = 2, B = 4
**Output:** [2, 4, 6, 8]
**Explanation:** First four multiple of 2 are A * 1 = 2 * 1 = 2, A * 2 = 2 * 2 = 4, A * 3 = 2 * 3 = 6, A * 4 = 2 * 4 = 8
## PsuedoCode
```java
import java.util.*;
import java.lang.*;
class Main{
public static ArrayList<Integer> firstB(int A, int B){
ArrayList<Integer> ans = new ArrayList<Integer>();
for(int i = 1; i <= B; i++){
ans.add(A * i);
}
return ans;
}
public static void main(String args[]){
System.out.println(firstB(3, 5));
}
}
```
**Output:**
```plaintext
[3, 6, 9, 12, 15]
```
---
# 2D Arrays
We can imagine 2D arrays as array of arrays.
## 2D ArrayList
2D ArrayList are ArrayList of ArrayLists
## Syntax
```java
ArrayList< ArrayList<Type> > mat = new ArrayList< ArrayList<Type> >();
```
## Basic Operations
- **Add:** We can add ArrayList inside 2D ArrayList. We can ArrayLists of different sizes in a single 2D ArrayList.
- Get
- Size
- Remove
- Set
```java
import java.util.*;
import java.lang.*;
class Main{
public static void main(String args[]){
ArrayList< ArrayList<Integer> > list2d = new ArrayList< ArrayList<Integer> >();
// Add
ArrayList<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
a1.add(4);
list2d.add(a1);
ArrayList<Integer> a2 = new ArrayList<Integer>();
a2.add(0);
list2d.add(a2);
ArrayList<Integer> a3 = new ArrayList<Integer>();
a3.add(10);
a3.add(-5);
a3.add(1);
list2d.add(a3);
System.out.println(list2d);
// Get
System.out.println(list2d.get(0));
System.out.println(list2d.get(2).get(1));
// Size
System.out.println(list2d.size());
System.out.println(list2d.get(1).size());
// Remove
list2d.remove(1);
System.out.println(list2d);
// Set
ArrayList<Integer> a4 = new ArrayList<Integer>();
a4.add(-2);
a4.add(5);
a4.add(8);
list2d.set(0,a4);
System.out.println(list2d);
// Update a list element
list2d.get(1).set(1, -15);
System.out.println(list2d);
}
}
```
**Output:**
```plaintext
[[1, 4], [0], [10, -5, 1]]
[1, 4]
-5
3
1
[[1, 4], [10, -5, 1]]
[[-2, 5, 8], [10, -5, 1]]
[[-2, 5, 8], [10, -15, 1]]
```
---
## Problem Statement
Given a 2D Arraylist as input, print it line by line.
## Explanation
Every nested list of 2D ArrayList is to be printed in different lines and the elements in a single line are separated by space.
## Example
**Input:** [[1, 4], [0], [10, -5, 1]]
**Output:**
1 4
0
10 -5 1
## Code
```java
import java.util.*;
import java.lang.*;
class Main{
public static void print2DList(ArrayList< ArrayList<Integer> > list2d){
for(int i = 0 ; i < list2d.size() ; i++){
// get the ith ArrayList
ArrayList<Integer> ls = list2d.get(i);
//Print the ith list
for(int j = 0 ; j < ls.size() ; j++){
System.out.print(ls.get(j) + " ");
}
System.out.println();
}
}
public static void main(String args[]){
ArrayList< ArrayList<Integer> > list2d = new ArrayList< ArrayList<Integer> >();
ArrayList<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
a1.add(4);
list2d.add(a1);
ArrayList<Integer> a2 = new ArrayList<Integer>();
a2.add(0);
list2d.add(a2);
ArrayList<Integer> a3 = new ArrayList<Integer>();
a3.add(10);
a3.add(-5);
a3.add(1);
list2d.add(a3);
print2DList(list2d);
}
}
```
**Output:**
```plaintext
1 4
0
10 -5 1
```
---
## Problem Statement
Given an integer N as input, return the numeric staircase.
## Example
**Input:** 3
**Output:**
```plaintext
[
[1].
[1, 2],
[1, 2, 3]
]
```
## Code
```java
import java.util.*;
import java.lang.*;
class Main{
public static ArrayList< ArrayList<Integer> > staircase(int N){
ArrayList< ArrayList<Integer> > ans = new ArrayList< ArrayList<Integer> >();
for(int row = 1 ; row <= N ; row++){
ArrayList<Integer> rw = new ArrayList<Integer>();
for(int col = 1 ; col <= row ; col++){
rw.add(col);
}
ans.add(rw);
}
return ans;
}
public static void main(String args[]){
System.out.println(staircase(3));
}
}
```
**Output:**
```plaintext
[[1], [1, 2], [1, 2, 3]]
```
---
# Some pointers
- Use Java 8 Oracle JDK - Language
- Gets easier with use

View File

@@ -0,0 +1,525 @@
# Refresher : For Loop
---
### Question
```java
// 1.
while(// 2.) {
// 3.
// 4.
}
```
Which sequence correctly represents the order of operations in the while loop?
**Choices**
- [ ] Initialisaton , Loop work, Condition , Update
- [ ] Initialisation , update, Loop work , Condition
- [x] Initialisation , Condition, Loop work, Update
- [ ] Loop work, Initialisation, Condition, Update
**Explanation:**
* **Initialization:** In this step, the loop control variable is initialized to a starting value. It is usually the first step before the loop begins.
* **Condition:** The loop condition is evaluated before each iteration. If the condition is true, the loop body will be executed; otherwise, the loop will terminate.
* **Loop work:** This represents the actual code or operations that are executed inside the loop body during each iteration.
* **Update:** After each iteration, the loop control variable is updated or modified. It prepares the loop for the next iteration by changing its value.
So, the correct flow of the loop is Initialization -> Condition -> Loop work -> Update.
---
## For Loops
The for loop in most programming languages follows the syntax given below:
```java
for(initialization; condition; update) {
loop work;
}
```
The meaning of each step is same as while loop.
For Loop and while can be used interchaneably. They are like Water and Jal.
### Example-1:
Given N as input, Print from 1 to N.
Provided we have input N, this is how the `for` loop looks like:
### Code:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (N): ");
int N = scanner.nextInt();
for (int i = 1 ; i <= N; i ++ ) {
System.out.print(i + " ");
}
scanner.close();
}
}
```
### Explanation
* **Initialization:** `int i = 1`; - Firstly, we initialize i = 1. This sets the starting point for the loop.
* **Condition:** `i <= N`; - Loop continues to execute till `i <= N`. In each iteration, it checks if i <= N. If it is true, the loop work is done; otherwise, the loop terminates.
* **Loop Body (Action):** `System.out.print(i + " ");` - During each iteration, the loop body prints the value of i, followed by a space.
* **Update:** `i ++` - After each iteration, i is incremented by 1. This prepares loop for next iteration.
### Example-2:
Given N as input, print all odd numbers from 1 to N.
### Approach:
* First, we take input from user.
* Then we run the loop from 1 to N.
* Since we want to print only odd numbers, we increment by 2 to skip even numbers.
* The loop body prints the value of `i`
### Code:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (N): ");
int N = scanner.nextInt();
for (int i = 1; i <= N; i += 2) {
System.out.print(i + " ");
}
scanner.close();
}
}
```
---
## What are Factors of a Number
**i** is said to be the factor of N if i divides N completely, i.e **N % i = 0**
Let's take an Integer as an example and find its factors:
**Example 1:** Find the factors of 6.
Since 1, 2, 3, 6 divides 6 completely, hence factors of 6 are 1, 2, 3, and 6.
**Example 2:** Find the factors of 10.
Since 1, 2, 5, 10 divides 10 completely hence, the factors of 10 are 1, 2, 5, and 10.
---
### Question
What are the factors of 24 ?
**Choices**
- [ ] 2, 3, 4, 6, 8, 12
- [ ] 1, 2, 3, 4, 6, 8, 12
- [x] 1, 2, 3, 4, 6, 8, 12, 24
**Explanation**
Factors of 24 are 1, 2, 3, 4, 6, 8, 12, and 24.
---
## Print the factors of a positive number N
How to print the factors of a positive number N ?
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Approach:
* The range of factors of a positive integer N is from 1 to N.
* We can simply iterate from 1 to N to get all the factors
* If N % i == 0, increment count variable.
### Code:
```java
import java.util.Scanner;
public class Main {
public static void printFactors(int N) {
System.out.print("Factors of " + N + ": ");
for (int i = 1; i <= N; ++ i) {
if (N % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (N): ");
int N = scanner.nextInt();
printFactors(N);
scanner.close();
}
}
```
---
### Question
Definition of Prime :
If a number **"N"** is divisible by **1** and itself is called **Prime Number**.
**Choices**
- [ ] True
- [x] False
**Explanation:**
As per above definition, 1 will also be a Prime Number since its factors are 1 and itself.
But we know 1 is not a Prime Number, hence the definition is wrong.
**Correct Definition:** A prime number has exactly two factors.
**For example:**
2 is a prime number because it has only two factors, 1 and 2.
3 is a prime number because it has only two factors, 1 and 3.
5 is a prime number because it has only two factors, 1 and 5.
---
## Prime Numbers
### How to check if a number is prime or not?
* We just need to check if N has exactly 2 factors, then it is Prime.
* So, we can make use of previous code to get the factors of N and check if factors are 2 or not.
### Code:
```java
import java.util.Scanner;
public class Main {
public static boolean isPrime(int number) {
int divisorCount = 0;
for (int i = 1; i <= number; ++ i) {
if (number % i == 0) {
divisorCount ++ ;
}
}
return (divisorCount == 2);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int divisorCount = 0;
System.out.print("Enter a number: ");
int N = scanner.nextInt();
for (int i = 1; i <= N; ++ i) {
if (N % i == 0) {
divisorCount ++ ;
}
}
if (isPrime(N)) {
System.out.println("Prime");
} else {
System.out.println("Not Prime");
}
scanner.close();
}
}
```
---
### Question
What is the smallest prime number?
**Choices**
- [ ] 0
- [ ] 1
- [x] 2
- [ ] 3
**Explanation:**
The smallest prime number is 2. Also, it is the only even prime number.
---
## Break and Continue statements
### Explanation of Break statement
The `break` statement is used to exit or terminate the nearest enclosing loop prematurely. When the `break` statement is encountered inside a loop, it immediately stops the loop's execution and transfers control to the statement following the loop. It helps avoid unnecessary iterations and is often used to terminate a loop early based on a specific condition.
The code for finding if a number is prime or not can be modified using `break` statement to avoid more efforts
In the given code, the goal is to check if the number N is prime or not. We can use the `break` statement to optimize the loop and avoid unnecessary iterations. The idea is that if we find any divisor of N, other than 1 and N, we can conclude that N is not prime, and there is no need to check further.
Here's the modified code using the `break` statement:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int N = scanner.nextInt();
int divisorCount = 0;
for (int i = 1; i <= N; i ++ ) {
if (N % i == 0) {
divisorCount ++ ;
if (divisorCount > 2) {
// If we find more than 2 divisors, break the loop
break;
}
}
}
if (divisorCount == 2) {
System.out.println(N + " is a prime number.");
} else {
System.out.println(N + " is not a prime number.");
}
scanner.close();
}
}
```
* If `cnt` is greater than 2 (meaning N has more than two divisors), the break statement is used to terminate the loop early, avoiding unnecessary iterations.
* After the loop, it checks if `cnt` is equal to 2. If `cnt` is exactly 2, it means N has exactly two divisors (1 and N), so it is prime.
* Depending on the value of `cnt`, it prints either "Prime" or "Not Prime" on the screen.
### Explaination of Continue statement
The `continue` statement is used to skip the rest of the current iteration in a loop and move on to the next iteration immediately. When the `continue` statement is encountered inside a loop, it interrupts the current iteration's execution and starts the next iteration of the loop.
We can use the continue statement to skip odd numbers and only print the even numbers between 1 and N.
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (N): ");
int N = scanner.nextInt();
System.out.print("Even numbers between 1 and " + N + ": ");
for (int i = 1; i <= N; ++ i) {
if (i % 2 != 0) {
// Skip odd numbers using continue statement
continue;
}
System.out.print(i + " ");
}
System.out.println();
scanner.close();
}
}
```
* The code takes the input N from the user using `std::cin`.
* It then enters a for loop that iterates from 1 to N.
* Inside the loop, there is an if condition: `if (i % 2 != 0)`.
* The condition checks if `i` is odd (i.e., not divisible by 2). If `i` is odd, the continue statement is executed, and the rest of the loop's body is skipped.
* Therefore, when `i` is odd, the loop moves on to the next iteration, effectively skipping the odd numbers.
* For all even values of i, the loop prints the even numbers between 1 and N, separated by spaces.
---
## How to Solve Questions with T Test Cases
To solve questions with T test cases, you'll need to write a program that can handle multiple test cases. Typically, the input for each test case will be provided one after the other, and your program should process each test case and produce the corresponding output.
Here's a general approach to handle T test cases in your program:
* Read the value of T (the number of test cases) from the input.
* Use a loop to iterate T times to process each test case.
* For each test case, read the input data specific to that test case.
* Perform the required operations or computations for that test case.
* Output the result for that test case.
* Repeat steps 3 to 5 until all T test cases are processed.
Here's an example to illustrate the process:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of test cases (T): ");
int T = scanner.nextInt();
for (int t = 1; t <= T; ++ t) {
// Read input data specific to the current test case
// For example, prompt the user to enter data for each test case
// int N = scanner.nextInt();
// String input = scanner.next();
// ...
// Perform computations or operations for the current test case
// For example, process the input data and calculate the result
// int result = processData(N, input);
// ...
// Output the result for the current test case
// For example, print the result for each test case
// System.out.println("Result for Test Case " + t + ": " + result);
// ...
}
scanner.close();
}
}
```
---
## Scope of Variables
### Explanation
The scope of a variable refers to the region of a program where that variable is accessible and can be used. It determines the portion of the code in which a variable exists and retains its value.
```java
import java.lang.*;
import java.util.*;
class Main {
// public static void main(String args[]) {
// // Scope of Variable
// // Useful lifetime of a variable
// int x = 10;
// //....
// //....
// //....
// System.out.println(x);
// //....
// //....
// } // closing of the parent bracket
// // Line 10-18 is the scope of the variable
public static void main(String args[]) {
// Case 1
// int x = 10;
// int y = 15;
// {
// System.out.println(x + " " + y);
// }
// Case 2
// int x = 10;
// {
// int y = 15;
// System.out.println(x + " " + y);
// }
// {
// System.out.println(x + " " + y);
// }
// Case 3
// int x = 10;
// int y = 15;
// {
// y = 10;
// System.out.println(x + " " + y);
// }
// {
// System.out.println(x + " " + y);
// }
}
}
```
The provided Java code demonstrates different cases illustrating variable scope in Java. Let's go through each case:
**Case 1:**
```java
public static void main(String args[]) {
int x = 10;
int y = 15;
{
System.out.println(x + " " + y);
}
}
```
In this case, `x` and `y` are declared and initialized in the main method. Inside the block (denoted by curly braces {}), both `x` and `y` are accessible since they are in the same scope. **The output will be "10 15"**.
**Case 2:**
```java
public static void main(String args[]) {
int x = 10;
{
int y = 15;
System.out.println(x + " " + y);
}
{
System.out.println(x + " " + y);
}
}
```
In this case, `x` is declared and initialized in the main method. Inside the first block, `x` is accessible since it is in the same scope. However, `y` is declared within this block and is only accessible within this block. Attempting to access `y` in the second block will result in a compilation error because it is outside of its scope. **The output will be "10 15"**, **followed by a compilation error for the second System.out.println(x + " " + y);**.
**Case 3:**
```java
public static void main(String args[]) {
int x = 10;
int y = 15;
{
y = 10;
System.out.println(x + " " + y);
}
{
System.out.println(x + " " + y);
}
}
```
In this case, `x` and `y` are declared and initialized in the main method. Inside the first block, `x` and `y` are accessible since they are in the same scope. The value of `y` is modified to 10 inside the block. **The output will be "10 10"**. In the second block, `x` is accessible, but `y` is not redeclared, so the modified value from the previous block will be used. The output will be "10 10".

View File

@@ -0,0 +1,359 @@
# Refresher : Functions
## Problem in Non-Functional Programming
Let's understand the problems arises in Non-Functional programming by taking an example as:
Suppose we have given three integers say a,b,c & we have to calculate the sum of digits of all these numbers seperately. So, the basic program to do that is as shown below.
```java
main(){
--------
--------
int sum1 = 0 , sum2 = 0 , sum3 = 0;
while(a > 0){
sum1 += a % 10;
a /= 10;
}
system.out.println(sum1);
while(b > 0){
sum2 += b % 10;
b /= 10;
}
system.out.println(sum2);
while(c > 0){
sum3 += c % 10;
c /= 10;
}
system.out.println(sum3);
}
```
In the above code, we have to write the same piece of code thrice. So this is the major problem.
The above code have many problems:
* **Redundancy**.
* **Readability**.
* **Maintainability**.
### How to Solve the Above Problems?
We can solve the problems using black box technique as:
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/071/original/upload_032a5f59f1b42d8ddf823df91ceb367b.png?1695097169)
Here, when we require to calculate the sum of digits then we will simply invoke this box and pass the integer in it, then it will return the sum as an output.
When this box is taken together with input and output then this is known as the **function**. By using the function we can overcome the problems mentioned above.
### Syntax of Function
```java
ansType function name(inputType input){
// Main logic.
return ans;
}
```
This is how the typical function looks like.
Let's create a function to sum 2 numbers.
```java
int 2sum(int a,int b){
int sum = a + b;
return sum;
}
```
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/072/original/upload_d3b1c9008a1e6f7b1f05e21dc8a9d923.png?1695097263)
**Note:** In case, the return type is void then no need to return anything(return statement is optional).
---
### Question
What will be the output?
```java
class Test {
public static int sum(int a, int b){
return a + b;
}
public static void main(String[] args){
int a = 15, b = 5;
System.out.println(sum(a, 10));
}
}
```
Choose the correct answer
**Choices**
- [ ] 20
- [x] 25
- [ ] 15
- [ ] 0
**Explanation**
The a & b defined inside the sum function is different from that is defined in the main function. We have passed a & 10 as a argument. that's why the value of b that is defined inside the sum function is 10. Hence, the sum is 25.
---
### Question
What will be the output?
```java
class Test {
public static int sum(int a, int b){
return a + b;
}
public static void main(String[] args){
int a = 15, b = 5;
sum(a,b);
}
}
```
Choose the correct answer
**Choices**
- [ ] 20
- [ ] Error
- [ ] 15
- [x] Nothing will be printed.
**Explanation**
There is not any printing statement like `system.out.print()`. Hence, nothing is printed.
---
### Question
What will be the output?
```java
class Test {
public static int sum(int a, int b){
System.out.print(a + b);
}
public static void main(String[] args){
int a = 15, b = 5;
sum(a,b);
}
}
```
Choose the correct answer
**Choices**
- [ ] 20
- [x] Error
- [ ] 15
- [ ] Nothing will be printed.
**Explanation**
Error because the return type of sum function is int but it does not return anything.
---
### Question
What will be the output?
```java
class Test {
public static int sum(int a, int b){
return a + b;
}
public static void main(String[] args){
int a = 15, b = 5;
System.out.println(sum(20, b));
}
}
```
Choose the correct answer
**Choices**
- [ ] 20
- [ ] Error
- [x] 25
- [ ] Nothing will be printed.
---
### Question
What will be the output?
```java
class Test {
public static int sum(int a, int b){
return a + b;
}
public static void main(String[] args){
int a = 15, b = 5;
System.out.println(sum(6, 10));
}
}
```
Choose the correct answer
**Choices**
- [ ] 20
- [ ] Error
- [x] 16
---
## Question 1
Given an integer **N**, return whether the integer is even or not.
#### TestCase
##### Input 1
```plaintext
12
```
##### Output 1
```plaintext
true
```
##### Input 2
```plaintext
5
```
##### Output 2
```plaintext
false
```
### PseudoCode
```java
public static boolean iseven(int n){
if(n % 2 == 0) return true;
else return false;
}
```
---
## Question 2
Given an integer **N**, return whether its height is small, medium or large.
* if it is less than 10, then its small.
* if it is between 10 to 20, then its medium.
* if it is greater than 20, then large.
#### TestCase
##### Input 1
```plaintext
5
```
##### Output 1
```plaintext
small
```
##### Input 2
```plaintext
51
```
##### Output 2
```plaintext
large
```
### PseudoCode
```java
public static String height(int n){
if(n < 10) return "small";
else if(n < 20) return "medium";
else return "large".
}
```
---
## Question 3
Given two doubles as argument, return the area of the rectangle.
#### TestCase
##### Input 1
```plaintext
1.0
2.0
```
##### Output 1
```plaintext
2.0
```
### PseudoCode
```java
public static double areaofrectangle(double a, double b){
double area = a * b;
return area;
}
```
---
## Question 4
Given the radius(double) of the circle, return the area of the circle.
#### TestCase
##### Input 1
```plaintext
7.0
```
##### Output 1
```plaintext
154.0
```
### PseudoCode
```java
public static double areaofcircle(double radius){
double area = 3.14 * radius * radius;
return area;
}
```
**Note:** Instead of writing the value of PI as 3.14, we can directly use the module Math.PI. To use that we have to import the maths library.
---
## Question 5
Given an integer **N** as an input, print all the prime numbers between 1 to N.
#### TestCase
##### Input 1
```plaintext
10
```
##### Output 1
```plaintext
2 3 5 7
```
#### Explanation
Prime number is the number which is not divisible by any oof the number except 1 and itself. So, to find the number of prime numbers between 1 to **N**, just count the number of itegers which divides it. if it is equal to 2 then it is prime number.
#### PseudoCode
```java
public static void primenumbers(int n) {
for (int num = 1; num <= n; num++) {
int factors = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) factors++;
}
if (factors == 2) system.out.print(num);
}
}
```
We can further break it as:
```java
public static boolean isprime(int n) {
int factors = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) factors++;
}
if (factors == 2) return true;
else return false;
}
public static void primenumbers(int n) {
for (int num = 1; num <= n; num++) {
if (isprime(num)) system.out.print(num);
}
}
```

View File

@@ -0,0 +1,518 @@
# Refresher: HashMap & HashSet
# HashSet
HashSet is a collection of unique elements.
## Example 1
We have a bag, which has some numbers inside it.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/541/original/upload_2ef858012b3b58d9c1da8518a1cdb8ff.png?1697783784)
This bag has unique elements, which means every number appears once only.
If we want to add 9 in a bag, then it will be not inserted as the bag already has 9.
Some other examples which contain unique elements are:
- Email-id
- username
- Fingerprints
## Example 2
Let us assume we have an array `arr = [1, 3, -2, 7, 1, 1, -2]`
Now if we want to create a HashSet of it then it contains unique elements.
`HS = [1, 7, -2, 3]`
Here we can see that **hashset does not have any sequence of elements.**
## Syntax
```java
HashSet<Type> hs = new HashSet<Type>();
```
Here Type can be any class
## Basic Operations
We can perform the following operations on HashSet.
- **Add:** Used to add element in HashSet.
- **Contains** Used to check whether HashSet contains a certain element or not.
- Size
- Remove
- **Print:** We use each loop for printing the elements of HashSet
---
### Question
For the given HashSet hs, what will be the size after the following operations?
```
HashSet<Integer> hs = new HashSet<Integer>();
hs.add(3);
hs.add(-2);
hs.add(10);
hs.add(3);
hs.add(10);
hs.add(0);
```
**Choices**
- [ ] 2
- [ ] 3
- [ ] 5
- [x] 4
**Explanation**
```plaintext
The unique elements added to the HashSet are: 3, -2, 10, 0.
So, the size of the HashSet is 4.
```
**Example**
```java
import java.util.*;
import java.lang.*;
class Main{
public static void main(String args[]){
HashSet<Integer> hs = new HashSet<Integer>();
//printing HashSet
System.out.println(hs);
// add
hs.add(3);
hs.add(-2);
hs.add(10);
hs.add(3);
hs.add(10);
hs.add(0);
System.out.println(hs);
// Contains
System.out.println(hs.contains(3));
System.out.println(hs.contains(-1));
// Size
System.out.println("Size is: " + hs.size());
// Remove
hs.remove(3);
System.out.println(hs);
// print
for(Integer i : hs){ // for each loop
System.out.println(i);
}
}
}
```
**Output:**
```plaintext
[]
[0, -2, 3, 10]
true
false
Size is: 4
[0, -2, 10]
```
---
## ArrayList HashSet
## ArrayList
- Sequential order.
- Duplicates allowed
## HashSet
- Sequence not maintained
- Unique element present only.
---
## Problem Statement
Given an integer array as input, add its elements to a HashSet and return the HashSet.
## PseudoCode
```java
import java.util.*;
import java.lang.*;
class Main{
public static HashSet<Integer> convertToHashset(int[] arr){
HashSet<Integer> ans = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++){
ans.add(arr[i]);
}
return ans;
}
public static void main(String args[]){
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
System.out.println(convertToHashset(arr));
}
}
```
**Output:**
```plaintext
[1, -2, 3, 4, 5]
```
---
## Problem Statement
Given 2 HashSet as input, print their common elements.
## Example
**Input:**
HS1: {0, -2, 4, 10}
HS2: {1, -2, 3, 4, 5}
**Output:** -2 3
## Understanding the problem
We have to print the elements that are present in both the HashSet.
## PseudoCode
```java
import java.util.*;
import java.lang.*;
class Main{
public static void intersect(HashSet<Integer> hs1, HashSet<Integer> hs2){
for(Integer i : hs1){
if(hs2.contains(i)){
System.out.print(i + " ");
}
}
}
public static HashSet<Integer> convertToHashset(int[] arr){
HashSet<Integer> ans = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++){
ans.add(arr[i]);
}
return ans;
}
public static void main(String args[]){
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
HashSet<Integer> hs1 = convertToHashset(arr);
System.out.println(hs1);
int arr2[] = {0, -2, 3, 10};
HashSet<Integer> hs2 = convertToHashset(arr2);
System.out.println(hs2);
intersect(hs1, hs2);
}
}
```
**Output:**
```plaintext
[1, -2, 3, 4, 5]
[0, -2, 3, 10]
-2 3
````
---
### Question
What operation is used to remove an element from a HashSet?
**Choices**
- [ ] Add
- [ ] Size
- [x] Remove
- [ ] Contain
**Explanation**
```plaintext
The `Remove` operation is used to remove an element from a HashSet.
```
---
## HashMap
HashMap is a data structure which contains key-value pairs.
## Example
Let us suppose we have states and its population.
| States | Population |
|:-------:|:----------:|
| Punjab | 15 |
| Haryana | 18 |
| UP | 20 |
| Delhi | 18 |
Now if we have the above data, and our question is to tell the population of UP, then we can simply tell the value next to UP(20).
Here we can say UP->20 is a pair, where UP is a key, corresponding to which some values are stored, and by this key, we access the data.
Here states are key and population are values.
| States(key) | Population(value) |
|:-----------:|:-----------------:|
| Punjab | 15 |
| Haryana | 18 |
| UP | 20 |
| Delhi | 18 |
Some other examples are:
- User id -> password
- Word -> Meaning (dictionary)
## Features of HashMap
- Duplicate values are allowed
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/542/original/upload_8d142119409f4145b2271918798093b2.png?1697784005)
- Duplicate keys are not allowed.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/543/original/upload_db02073a1c4a022ec47d46ad9953369e.png?1697784028)
- No order of data, key-value pairs are in random order.
## Syntax
```java
HashMap<keyType, valueType> hm = new HashMap<keyType, valueType>();
```
## Basic Operations
We can perform the following operations on HashMap.
- Add
- Contains
- Get
- Update
- Size
- Remove
- Print
### Example
```java
import java.util.*;
import java.lang.*;
class Main{
public static void main(String args[]){
HashMap<String, Integer> hm = new HashMap<String, Integer>();
// add
hm.put("Delhi", 18);
hm.put("Punjab", 20);
hm.put("Haryana", 18);
hm.put("Goa", 5);
System.out.println(hm);
// Contains
System.out.println(hm.containsKey("Gujarat"));
System.out.println(hm.containsKey("Goa"));
// Get
System.out.println(hm.get("Gujarat"));
System.out.println(hm.get("Goa"));
// Update
hm.put("Goa", 6);
System.out.println(hm);
// Size
System.out.println("Size is: " + hm.size());
// Remove
hm.remove("Goa");
System.out.println(hm);
// print
// 1. get all keys
// hm.keySet()-> returns a set of keys of HashMap
// 2. Use keys to iterate over the map
for(String state : hm.keySet()){
System.out.println(state + " -> " + hm.get(state));
}
}
}
```
**Output:**
```plaintext
{Delhi = 18, Haryana = 18, Goa = 5, Punjab = 20}
false
true
null
5
{Delhi = 18, Haryana = 18, Goa = 6, Punjab = 20}
Size is: 4
{Delhi = 18, Haryana = 18, Punjab = 20}
Delhi -> 18
Haryana -> 18
Punjab -> 20
```
---
### Question
In a HashMap, what is the purpose of the get operation?
**Choices**
- [ ] Add a key-value pair
- [x] Retrieve the value associated with a key
- [ ] Check if a key is present
- [ ] Remove a key-value pair
**Explanation**
```plaintext
The `get` operation in HashMap is used to retrieve the value associated with a given key.
```
---
## Problem Statement
Given an integer array as input, return the corresponding frequency map.
## Example
**Input:**
arr = [1, 4, 3, -2, 1, 1, 4, 5, 3]
**Output:**
```plaintext
hm = {
1: 3,
4: 2,
3: 2,
-2: 1,
5: 1
}
```
## Solution
In this, we iterate over every element of an array, for every element we have two possibilities.
1. Current element is not in the hashmap(`hm.containsKey(arr[i]) == false`).
then add the current element into HashMap with frequency 1.
2. The current element is already present in the HashMap as a key and has some value.
then simply increase the previously stored frequency of the current element by 1.
## PseudoCode
```java
import java.util.*;
import java.lang.*;
class Main{
public static HashMap<Integer, Integer> freqMap(int arr[]){
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++){
// case 1 - arr[i] not present in hashmap
if(hm.containsKey(arr[i]) == false){
hm.put(arr[i],1);
}
// case - arr[i] already present in hashmap
// before current element, hm -> {2: 3}
// current -> 2
// hm -> {2: 3}
else{
int beforeValue = hm.get(arr[i]);
int newValue = beforeValue + 1;
hm.put(arr[i], newValue);
}
}
return hm;
}
public static void main(String args[]){
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
System.out.println(freqMap(arr));
}
}
```
**Output:**
```plaintext
{1 = 3, -2 = 1, 3 = 2, 4 = 2, 5 = 1}
````
## DryRun
**Input:**
arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3}
**Solution:**
1. Initially our hashmap is empty, `hm = {}`,
2. Now we start iterating array elements, first element is 1, it is not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1}`.
3. Next element is 4, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1}`.
4. Next element is 3, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1, 3: 1}`.
5. Next element is -2, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1, 3: 1, -2: 1}`.
6. The next element is 1, it is available in HashMap, so if the condition becomes false, we will go to the else part.
```java
beforeValue = hm.get(1) = 1
newValue = beforeValue + 1 = 1 + 1 = 2
hm.put(1, 2)
```
then hashmap becomes, `hm = {1: 2, 4: 1, 3: 1, -2: 1}`.
7. The next element is again 1, it is available in HashMap, so if the condition becomes false, we will go to the else part.
```java
beforeValue = hm.get(1) = 2
newValue = beforeValue + 1 = 2 + 1 = 3
hm.put(1, 3)
```
then hashmap becomes, `hm = {1: 3, 4: 1, 3: 1, -2: 1}`.
8. The next element is 4, it is available in HashMap, so if the condition becomes false, we will go to the else part.
```java
beforeValue = hm.get(4) = 1
newValue = beforeValue + 1 = 1 + 1 = 2
hm.put(4, 2)
```
then hashmap becomes, `hm = {1: 3, 4: 2, 3: 1, -2: 1}`.
9. Next element is 5, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 3, 4: 2, 3: 1, -2: 1, 5: 1}`.
10. The next element is 3, it is available in HashMap, so if the condition becomes false, we will go to the else part.
```java
beforeValue = hm.get(3) = 1
newValue = beforeValue + 1 = 1 + 1 = 2
hm.put(3, 2)
```
then hashmap becomes, `hm = {1: 3, 4: 2, 3: 2, -2: 1, 5: 1}`.

View File

@@ -0,0 +1,683 @@
# Refresher : Introduction to Java : If-Else
## If-Else
#### Example
Let's start with real world example of ordering coffee from a cafe :-
* The customer might ask the receptionist ***If* you have coffee then provide coffee.**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/036/013/original/p50.png?1685876618)
* Or ***If* you have coffee then provide coffee, *else* provide tea**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/036/015/original/p51.png?1685876698)
* In programming we have to tackle real world situations.
* **How can we tackle the situation described above in the example using programming ?**
* If we pay attention to questions asked in the example we find the following keywords ***If*** & ***Else***.
* We can code the above situations using if else conditions.
#### If-Else Syntax
```cpp
if(is coffee available ? ){
// serve coffee
}
else{
// serve tea
}
```
* **Is coffee available ?** is the **Condition**.
* **The condition is statement which can have only true/false as answers** or we say it's of **boolean** type
---
## Question 1
### Question
Given an integer age as input, print whether the person is eligible to vote or not ?
> A person is eleigible if the person's age >= 18
#### Testcase 1
```plaintext
Input :
20
```
#### Solution 1
`Output : Eligible`
#### Testcase 2
```plaintext
Input :
14
```
#### Solution 2
`Output : Not Eligible`
#### Approach
* Using conditional statements we check:
* If age is >= 18 print Eligible.
* Else print Not Eligible
#### Pseudeocode
```cpp
public static void main() {
if (age >= 18) {
System.out.print("Eligible");
} else {
System.out.print("Not Eligible");
}
}
```
---
## Question 2
### Question
Given two integers A and B as input, print the larger
> A will not be equal to B
#### Testcase 1
```plaintext
Input :
A = 4, B = 6
```
#### Solution 1
`Output : 6 is bigger`
#### Testcase 2
```plaintext
Input :
A = 9, B = 6
```
#### Solution 2
`Output : 9 is bigger`
#### Approach
* Using conditional statements we check:
* If A > B print **A is bigger**.
* Else print **B is bigger**.
#### Pseudeocode
```java
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
int B = scn.nextInt();
if (A > B) {
System.out.print(A + "is bigger");
} else {
System.out.print(B + "is bigger");
}
}
```
---
## Question 2 part 2
### Question
Given two integers A and B as input, print the large
#### Testcase 1
```plaintext
Input :
A = 4, B = 6
```
#### Solution 1
`Output : 6 is bigger`
#### Testcase 2
```plaintext
Input :
A = 9, B = 6
```
#### Solution 2
`Output : 9 is bigger`
#### Testcase 2
```plaintext
Input :
A = 6, B = 6
```
#### Solution 2
`Output : Both are equal`
#### Approach
* Using conditional statements we check:
* If A > B print **A is bigger**.
* Else if A < B print **B is bigger**.
* Else print **Both are equal**.
#### Pseudeocode
```java
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
int B = scn.nextInt();
if (A > B) {
System.out.print(A + "is bigger");
} else if (B > A) {
System.out.print(B + "is bigger");
} else {
System.out.print("Both are equal");
}
}
```
---
## Question 3
### Question
Given temperature of patient in farenheit as input,
print whether the temperature is low, normal, high
>normal from 98.2 till 98.8
#### Testcase 1
```plaintext
Input :
98.1
```
#### Solution 1
`Output : Low`
#### Testcase 2
```plaintext
Input :
98.5
```
#### Solution 2
`Output : normal`
#### Testcase 3
```plaintext
Input :
99.3
```
#### Solution 3
`Output : high`
---
### Question
Which data type should be used to store temperature of a patient ?
**Choices**
- [x] Double
- [ ] Int
- [ ] String
- [ ] long
**Solution**
```plaintext
Double is used to store the numbers with decimals.
```
#### Approach
* Using conditional statements we check:
* If temperature is < 98.2 print low.
* Else if temperature > 98.5 print high**.
* Else print normal
#### Pseudeocode
```java
public static void main() {
scn = new Scanner(System.in);
double temperature = scn.nextDouble();
if (temperature < 98.2) {
System.out.print("low");
} else if (temperature > 98.8) {
System.out.print("high");
} else {
System.out.print("normal");
}
}
```
---
## Operators
### Division
* Division is denoted by **/** operator.
* Provided below is the output datatype based on dividend and divisor datatype.
* int / int ---> int
* float / int ---> float
* int / float ---> float
* float / float ---> float
* long / int ---> long
* double / float ---> double
* int / long are replacable
* float / double are replacable
* To convert a number to float put a f in the ending of it.
* To convert a number to double we can write it with .0 in the end.
#### Example
```cpp
System.out.println(9 / 3) ; // int / int ---> int output would be 3
System.out.println(11 / 3); // int / int ---> int output would be 3
System.out.println(11f / 3) ; // float / int ---> float output would be 3.6666
```
### Multiplication
* Multiplication is denoted by <b>*</b> operator.
* Provided below is the output datatype based on multiplicand and multiplier datatype.
* int * int ---> int
* int * long ---> long
* long * int ---> long
* long * long --->long
* int / float are replacable
* long / double are replacable
#### Example 1
```java
int x = 100000;
int y = 100000;
int z = x * y
System.out.println(z); // prints garbage value
```
* The above code gives garbage value as output but **why ?**
* We can see that when we multiply x and y i.e 100000 * 100000 then output would be 10<sup>10</sup>.
* Since the range of integer datatype is roughly 10<sup>9</sup> we would get garbage value due to overflow as we store it in z (int).
#### Example 2
```java
int x = 100000;
int y = 100000;
long z = x * y
System.out.println(z); // prints garbage value
```
* The above code gives garbage value as output but **why ?** **even though we have changed the datatype of z from int ---> long.**
* We have changed the datatype of z but the according to rules above :-
* int * int ---> int
* Therefore we need to explicitly change datatype of the multiplicand or the multiplier to long so that :-
* long * int ---> long
* Therefore :-
```java
int x = 100000;
int y = 100000;
long z = (long)x * y;
System.out.println(z); // prints 10000000000
```
---
### Question
What will be the output according to Java :
```java
int a = 100000;
int b = 400000;
long c = (long)(a * b);
System.out.println(c);
```
**Choices**
- [x] Some random number
- [ ] 40000000000
- [ ] Compilation error
- [ ] No Output
**Solution**
* First we are doing a * b i.e int * int therefore the output will be int.
* Overflow would have already occured before typecasting to long.
* Hence the random value is printed.
---
### Operators Continued
### Modulo
* Modulo is denoted by **%** operator.
* Gives us the remainder when a is divided by b i.e. a % b = remainder when a is divided by b.
#### Examples
* 7 % 3 ---> 1
* 8 % 5 ---> 3
* 10 % 1 ---> 0
* 5 % 12 ---> ?
* Answer is 5 by **why ?**.
* Because 5 % 12 = 12 * 0 + 5 where 5 is dividend, 12 is divisor , 0 is quotient & 5 is remainder.
---
### Question
What is the result?
System.out.print(17 % 4);
**Choices**
- [x] 1
- [ ] 4
- [ ] 16
- [ ] 5
**Solution**
```plaintext
dividend = divisor* quotient + remainder
=> 17 = 4 * 4 + 1
```
---
### Question
What will be the result of a % b, when b perfectly divides a with no remainder ?
**Choices**
- [x] 0
- [ ] b -1
- [ ] b
- [ ] a
**Solution**
```plaintext
dividend = divisor * quotient + remainder
if dividend is divided perfectly by divisor then the remainder is 0
```
---
## Question 4
### Question
Given an integer as input, print whether it is even or Odd
#### Testcase 1
```plaintext
Input :
3
```
#### Solution 1
`Output : odd`
#### Testcase 2
```plaintext
Input :
6
```
#### Solution 2
`Output : even`
---
### Question
If a % 2 == 0, what can we say about a ?
**Choices**
- [x] even
- [ ] odd
- [ ] prime
- [ ] remainder
---
### Approach
* Using conditional statements we check:
* If A % 2 == 0 print **even**.
* Else print **odd**.
#### Pseudeocode
```cpp
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
int B = scn.nextInt();
if (A % 2 == 0) {
System.out.print("even");
} else {
System.out.print("odd");
}
}
```
---
## Question 5
### Question
Q5 : Given an integer as input, print its last digit
#### Testcase 1
```plaintext
Input :
73
```
#### Solution 1
`Output : 3`
#### Testcase 2
```plaintext
Input :
651
```
#### Solution 2
`Output : 1`
#### Approach
* Print A % 10
#### Pseudeocode
```cpp
scn = new Scanner(System.in);
int A = scn.nextInt();
System.out.print(A % 10);
```
---
### Operators Continued
### Relational Operators
* **A > B** ---> Checks weather A is greater than B.
* **A < B** ---> Checks weather A is less than B.
* **A >= B** ---> Checks weather A is greater than or equalt to B.
* **A <= B** ---> Checks weather A is less than or equal to B.
* **A == B** ---> Checks weather A is equals B.
* **A != B** ---> Checks weather A is not equal to B.
### Logical Operators
* AND operator is denoted by **&&**
* Truth table is provided below.
| A | B | A && B |
|:---:|:---:|:------:|
| T | F | F |
| F | T | F |
| F | F | F |
| T | T | T |
* OR operator is denoted by **||**
* Truth table is provided below.
| A | B | A && B |
|:---:|:---:|:------:|
| T | F | T |
| F | T | T |
| F | F | F |
| T | T | T |
---
## Question 6
### Question
Q6 : Given units of electricity consumed as an integer input A, print the bill amount. Provided below is the range of electricity consumed and rate at which it is charged:-
[1-50] ---> ₹1
[51-100] ---> ₹2
[101 and beyond] ---> ₹4
#### Testcase 1
```plaintext
Input :
20
```
#### Solution 1
`Output : 20 * 1 = 20`
#### Testcase 2
```plaintext
Input :
80
```
#### Solution 2
`Output : 50 * 1 + 30 * 2 = 110`
#### Testcase 3
```plaintext
Input :
120
```
#### Solution 3
`Output : 50 * 1 + 50 * 2 + 20 * 4= 230`
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Pseudeocode
```java
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
if (A >= 1 && A <= 50) {
System.out.print(A * 1);
} else if (A >= 51 && A <= 100) {
System.out.print(50 + (A - 50) * 2);
} else {
System.out.print(50 + (50 * 2) + ((A - 100) * 4));
}
}
```
---
### Question 7
### Question
Q7 : Given an integer A as input
* If it is a multiple of 3, print Fizz
* If it is a multiple of 5, print Buzz
* If it is a multiple of 3 and 5, print Fizz-Buzz
#### Testcase 1
```plaintext
Input :
5
```
#### Solution 1
`Output : Buzz`
#### Testcase 2
```plaintext
Input :
3
```
#### Solution 2
`Output : Fizz`
#### Testcase 3
```plaintext
Input :
30
```
#### Solution 3
`Output : Fizz-Buzz`
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
#### Approach 1
```java
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
if (A % 3 == 0) {
System.out.print("Fizz");
} else if (A % 5 == 0) {
System.out.print("Buzz");
} else if (A % 3 == 0 && A % 5 == 0) {
System.out.print("Fizz-Buzz");
}
}
```
* When we test the above approach on A = 30, we get output as "Fizz"
* But correct output would be "Fizz-Buzz", so **why the wrong answer ?**
* Since if-else work in a chained manner the condition A % 3 == 0 is checked first.
* Therefore "Fizz" is printed
* Correct approach would be to check condition ( A % 3 == 0 && A % 5 == 0 ) first.
#### Pseudeocode
```java
public static void main() {
scn = new Scanner(System.in);
int A = scn.nextInt();
if (A % 3 == 0 && A % 5 == 0) {
System.out.print("Fizz-Buzz");
} else if (A % 5 == 0) {
System.out.print("Buzz");
} else if (A % 3 == 0) {
System.out.print("Fizz");
}
}
```

View File

@@ -0,0 +1,476 @@
# Introduction to Problem Solving
---
## Agenda
1. Output in Java
2. Data Types
3. Typecasting
4. Input
5. Quizzes
6. Dashboard Walkthrough
---
## Output in Java
Let's start with the famous example - **Hello World**
### Code to Print string/sentence/text
```cpp
public static void main(){
System.out.print("Hello World!");
}
```
### Code to **print number**
```cpp
public static void main(){
System.out.print(1);
}
```
### Observation
* Whenever we print a string, we put double quotes **" "** around it.
* Double quotes are not required for printing numbers.
---
### Question
System.out.print("Hey There");
**Choices**
- [x] Hey There
- [ ] "Hey There"
- [ ] Error
- [ ] "Hey There
**Explanation**
String between **""** will get printed. Therefore, solution is **Hey There**
---
### Question
system.out.print(10);
**Choices**
- [x] Error
- [ ] 2
- [ ] 10
- [ ] "10"
**Solution**
There is syntax error in above code.
Instead of **"system"** it should be **"System"**.
Error thrown is - "error: package system does not exist"
---
### Question
Predict the output:
System.out.print("5 * 10");
**Choices**
- [x] 5 * 10
- [ ] "5 * 10"
- [ ] 50
- [ ] Error
**Solution**
Prints the sentence / string / charactes between **""**, so instead of doing calculation & printing 50, we get :-
**5 * 10**
---
### Output in Java Continued
#### Code to Print Answers to Basic Arithimetic Operations
```cpp
public static void main(){
System.out.print(5 * 10); // gives 50 as output
System.out.print(10 / 5); // gives 2 as output
System.out.print(10 + 5); // gives 15 as output
System.out.print(10 - 5); // gives 5 as output
}
```
* **We use println to print in next line**
```cpp
public static void main(){
System.out.println("My name is [instructor]");
System.out.print("I am from [Hometown]");
}
```
---
### Question
```java
System.out.println("This question");
System.out.println("is easy!");
```
What's output of the above program ?
**Choices**
- [ ] This question is easy!
- [ ] This questionis easy!
- [x] This question
is easy!
- [ ] This question's easy!
**Solution**
In first statement println is written hence "This question" gets printed and control goes to new line, then in next line, again println is there, so "is easy!" gets printed and control goes to next line.
---
### Question
```java
System.out.println("Red");
System.out.print("Blue ");
System.out.println("Green");
System.out.print("Yellow");
```
What's output of the above programme ?
**Choices**
- [ ] Red
Blue Green Yellow
- [x] Red
Blue Green
Yellow
- [ ] Red
BlueGreen
Yellow
- [ ] Red Blue Green Yellow
**Solution**
First line has println, so after "Red" gets printed, control goes to new line.
Second statement has print, so after "Blue " gets printed, controls stays in the same line
Third line has println, so after "Green" gets printed, control goes to new line.
Fourth statement has print, so after "Yellow" gets printed, controls stays in the same line
---
### Output in Java Continued
* We can do single line comments by ---> **//**
```cpp
// single line comment
```
* We can do multi-line comments by ---> /* */
```cpp
/*
this
is a
multiline
comment
*/
```
* Shortcut to do multi-line comments is to select the part to be commented and press ctrl + /
* We can concatenate two strings like:-
```cpp
System.out.println("Ram " + "Shayam"); // output: ram shayam and the control will go to the next line
System.out.println("My age is " + 25 ); // output: My age is 25 and the control will go to the next line
```
---
### Question
Predict the output:
System.out.print( 7 + 1 + "156");
**Choices**
- [ ] 71156
- [x] 8156
- [ ] 1568
- [ ] 15617
---
### Question
Predict the output:
System.out.print("156" + 7 + 1);
**Choices**
- [ ] 1568
- [ ] 15678
- [x] 15671
- [ ] 1568
**Solution**
Calculation shall happen from left to right.
For first +, one operand is number and another is string, so it will concatenate them, i.e 1567.
Then for second +, both operands are string, therefore concatenation will happen.
Hence, **answer is 15671**.
---
## Data types in java
### Data types
1. **Primitive Data Types**
These are predefined in the Java programming language.
**For example:** byte, short, int, long, double, float, boolean, char
2. **Non-Primitive Data Types**
These are not predefined but defined by the programmer according to the need for a particular task.
**For example:** String, Arrays, class, etc.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/018/original/upload_8cbd044be7918278a42d8de841f78dac.png?1695053574)
**Primitive data types** are divided into two different types of values.
1. Numeric Data Types
2. Non-Numeric Data Types
#### Numeric Data Types
Numeric data types are used to store numeric values such as whole numbers and fractional numbers. They are divided into two parts, **integer** and **floating**.
**1. Integer**
**Byte, short, long, and int** these data types are used to store **whole numbers**
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/020/original/upload_b72992ead956aa0b3a1c17308ceca576.png?1695053630)
A. **Byte** Datatype:
It is commonly used when we want to store very small numbers of very limited size. Their data value is in the range of -128 to 127.
```cpp
byte a = 123;
System.out.print(a); //Printing 123
```
B. **Short** Data Type
The short data type can have data values- in the range of -32,768 to 32767.
```cpp
short a = 123;
System.out.println(a); //Printing 123
```
C. **Int** Data Type
The int data type is commonly used when we want to save memory in large arrays. The range is from -2,147,483,648 (-2^31) to 2,147,483,647 (2^31-1).
```cpp
int a = 123;
System.out.println(a); //Printing the 123
```
D. **Long** Data Type
The long data type is used when the int data type cannot handle a wider range than the int data type range. Data values is in the range of -9,223,372,036,854,775,808(-2^61) to 9,223,372,036,854,775,807(2^61 - 1).
```cpp
long a = 123123123;
System.out.println(a); //Printing the value of a
```
**2. Floating Values Data Types**
There are two types of Floating values data types in java that are used to store fractional number values.
E. **Float** Data Type:
This data type is used to store numbers that have decimals up to 6 and 7 points.
```cpp
float a = 1231.231;
System.out.println(a); //Printing the value of a
```
F. **Double** Data Type:
This data type is used to store numbers that have decimals up to 15 decimals
```cpp
double a = 12312.23123;
System.out.print(a); //Printing the value of a
```
We generally use Integer and Long Data Types.
Remember their actual range is very tricky. Therefore, we can remember by stating in power of 10.
### Close Approximations:
**Int** - { -10^9 to 10^9 }
**Long** - { -10^18 to 10^18 }
#### Non Numeric Data Types
**String**
Strings can be created by giving sequence of characters surrounded by double quotes to a variable.
Example:
String S = “This is a String”
**Note:** We will study non primitive data types later.
---
## Typecasting in java
### Typecasting
* Typecasting is converting one datatype to another.
* We can understand the concept of typecasting by following analogy.
* Let's have two tanks
* one large, with more capacity(say 100ml)
* one small (say 50ml)
* The large tanks corresponds to long datatype and small one corresponds to int datatype.
* Let's see the cases
* **Case 1:-** If water from smaller tank is poured to larger tank (int to long typecasting).
* In this case the larger tank hold all the water or we can say int can be typecasted to long.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/022/original/p47.png?1695053732)
* **Case 2:-** If larger tank has water <= 50 ml and water from larger tank is poured to smaller tank.
* Since the water in larger tank is equal to smaller tanks capacity the operation can be done.
* We can say that long can be typecasted to int, if the data is within constraints of int datatype value range.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/023/original/p48.png?1695053757)
* **Case 3:-** If larger tank has water > 50 ml and water from larger tank is poured to smaller tank.
* In this case, water will OVERFLOW.
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/024/original/p49.png?1695053775)
* When long is typecasted to int for data not within constraints of int datatype, the result would be **garbage value**.
#### Using variables
```cpp
String name = "arnav"
System.out.print("My name is " + name)
```
* We can declare variables as follows:-
```cpp
int i = 5;
long p = 1000000000l;
float f = 3.14f;
double d = 1.141516171819;
```
* By default integers are considered int
* By default decimal values are considered double
* Convention of putting l ,f before long and float is only in coding area, not in input
#### Typecasting example 1
```cpp
// small --> large
int i = 5,
long I = i;
System.out.println(I); // will give 5 as output
```
#### Typecasting example 2
```cpp
// large —-> small
long l = 100000000000l
int i = l
System.out.print(i);
```
* Above conversion will give an error:-Datatypes incompatible possible lossy conversion.
* This type of typecasting is **implicit typecasting**.
#### Typecasting example 3
```cpp
// large —> small
long l = 1000l;
int i = l;
System.out.print(i);
```
* For safety, above conversion will give an error:- Datatypes incompatible possible lossy conversion.
* We can force the conversion by using **explicit typecasting**
```cpp
long l = 1000l;
int i = (int)l; // forcing to convert; explicit typecasting
System.out.print(i);// 1000 as output
```
* If we force the same typecasting with data out of int value range
* In above case we would get garbage value.
```cpp
long l = 10000000000l;
int i = (int)l;
// forcing to convert
// explicit typecasting
System.out.print(i);// garbage value as output
```
---
### Input in java
* Scanner class is used to take inputs in java.
* Following are the methods to take number inputs in java:-
```cpp
scn = new Scanner(System.in);
int i = scn.nextInt();
long t = scn.nextLong();
float f = scn.nextFloat( ) ;
double d = scn.nextDouble();
```
* Following are methods to take string input in java.
```cpp
//scn. next ( ) —> Reads only 1 word from input
String s = scn.next();
System. out. print(s);
//scn.nextLine() —> Reads entire line from input
String s1 = scn.nextLine();
System.out.print(s1);
```
---
## Question 1
### Question
Take 2 names X and Y as input and print X loves Y.
### Testcase
```java
X = Ram
Y = Shyam
```
### Solution
`Output : Ram loves Shyam`
#### Code
```java
String x = scn.next();
String y = scn.next();
System.out.print(x + " loves " + y);
```
---
## Question 2
### Question
Take name X and age Y as input and print X age is Y.
### Testcase
```cpp
X = Aarnav
Y = 25
```
### Solution
`Output : Aarnav age is 25`
#### Code
```java
String x = scn.next();
String y = scn.nextInt();
System.out.print(x + " age is " + y);
```

View File

@@ -0,0 +1,493 @@
# Refresher : Patterns
## Question 1
Given **N** as input, print * **N** times.
#### TestCase
##### Input
```plaintext
5
```
##### Output
```plaintext
* * * * *
```
#### PseudoCode
```java
function pattern(int N) {
for (int i = 1; i <= N; i++) {
system.out.print(' * ');
}
}
```
---
## Question 2
Given **N** as input. Print a square of size **N * N** containing * in each cell.
#### TestCase
##### Input
```plaintext
5
```
##### Output
```plaintext
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
```
#### PseudoCode
```java
function pattern(int N){
for(int i = 1 ; i <= N ; i ++ ){
for(int j = 1 ; j <= N ; j ++ ){
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 3
Given **N**,**M** as input, print a rectangle of size **N * M** containing * in each cell.
#### TestCase
##### Input
```plaintext
N = 3
M = 4
```
##### Output
```plaintext
* * * *
* * * *
* * * *
```
#### PseudoCode
```java
function pattern(int N,int M){
for(int i = 1 ; i <= N ; i ++ ){
for(int j = 1 ; j <= M ; j ++ ){
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 4
Given **N** as input, print a staircase pattern of size **N**.
#### TestCase
##### Input
```plaintext
5
```
##### Output
```plaintext
*
* *
* * *
* * * *
* * * * *
```
#### Observation
The key observation here is that:
* The staircase pattern formed the right-angled triangle.
* The number of stars in each row is equal to the row number.
| Row | Stars |
|:---:|:-----:|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
#### PseudoCode
```java
function pattern(int N){
for(int i = 1 ; i <= N ; i ++ ){
for(int j = 1 ; j <= i ; j ++ ){
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 5
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 3
```
##### Output 1
```plaintext
*
* 2
* 2 *
```
##### Input 2
```plaintext
N = 4
```
##### Output 2
```plaintext
*
* 2
* 2 *
* 2 * 4
```
#### Observation
The key observations are:
* For even column numbers, print * .
* For odd column numbers, print the column number.
#### PseudoCode
```java
function pattern(int N){
for(int i = 1 ; i <= N ; i ++ ){
for(int j = 1 ; j <= i ; j ++ ){
if(j % 2 == 1) system.out.print(' * ');
else system.out.print(j);
}
system.out.println();
}
}
```
---
## Question 6
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 3
```
##### Output 1
```plaintext
* _ *
* _ *
* _ *
```
##### Input 2
```plaintext
N = 4
```
##### Output 2
```plaintext
* _ _ *
* _ _ *
* _ _ *
* _ _ *
```
#### Observation
The key observation here is that:
* The first and last column number of each row is * .
* There are total (N - 2) spaces in between stars( * ).
#### PseudoCode
```java
function pattern(int N){
for(int i = 1 ; i <= N ; i ++ ){
system.out.print(' * ');
for(int j = 2 ; j <= N - 1 ; j ++ ){
system.out.print('_');
}
system.out.print(' * ');
system.out.println();
}
}
```
---
## Question 7
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 3
```
##### Output 1
```plaintext
* * *
* *
*
```
##### Input 2
```plaintext
N = 4
```
##### Output 2
```plaintext
* * * *
* * *
* *
*
```
#### Observation
As shown in above, the number of stars in each row is one less than the previous row except 1st row where number of stars is **N**. Hence, we can derive the formula:
* Number of stars in each row is equal to the (N - rowNumber + 1).
For N = 4,
| Row | Stars |
|:---:|:-----:|
| 1 | 4 |
| 2 | 3 |
| 3 | 2 |
| 4 | 1 |
#### PseudoCode
```java
function pattern(int N){
for(int i = 1 ; i <= N ; i ++ ){
for(int j = i ; j <= N ; j ++ ){
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 8
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 3
```
##### Output 1
```plaintext
* *
* *
* *
```
##### Input 2
```plaintext
N = 4
```
##### Output 2
```plaintext
* *
* *
* *
* *
```
#### Observation
The key observation here is that:
* The first and last character of each row is ' * '.
* Number of spaces in each row is one less than the previous row except first row where number of spaces between stars is **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in between stars( * ).
For N = 4,
| Row | Total number of spaces between stars |
|:---:|:-----:|
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
| 4 | 0 |
#### PseudoCode
```java
function pattern(int N) {
for (int i = 1; i <= N; i++) {
system.out.print(' * ');
for (int j = 1; j <= N - i; j++) {
system.out.print(' ');
}
system.out.print(' * ');
system.out.println();
}
}
```
---
## Question 9
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 3
```
##### Output 1
```plaintext
*
* *
* * *
```
##### Input 2
```plaintext
N = 4
```
##### Output 2
```plaintext
*
* *
* * *
* * * *
```
#### Observation
The key observation here is that:
* Number of spaces in each row is one less than the previous row except 1st row where number of spaces are **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in the starting of each row.
* Number of sars in each row is one more than the previous row except 1st row where number of stars are **1**. Hence we can say that there are total (rowNumber) stars at the last of each row.
For N = 4,
| Row | Total number of spaces | Total number of stars |
|:---:|:----------------------:|:---------------------:|
| 1 | 3 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
| 4 | 0 | 4 |
#### PseudoCode
```java
function pattern(int N) {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N - i; j++) {
system.out.print(' ');
}
for (int j = 1; j <= i; j++) {
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 10
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 4
```
##### Output 1
```plaintext
********
*** ***
** **
* *
```
#### Observation
The key observation here is that:
* There are total (N - rowNumber + 1) stars in the begining and end of each row.
* There are total ((rowNumber - 1) * 2) spaces between these stars.
For N = 4,
| Row | Stars | Spaces | Stars |
|:---:|:-----:|:------:|:-----:|
| 1 | 4 | 0 | 4 |
| 2 | 3 | 2 | 3 |
| 3 | 2 | 4 | 2 |
| 4 | 1 | 6 | 1 |
#### PseudoCode
```java
function pattern(int N) {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N - i + 1; j++) {
system.out.print(' * ');
}
for (int j = 1; j <= (i - 1) * 2; j++) {
system.out.print(' ');
}
for (int j = 1; j <= N - i + 1; j++) {
system.out.print(' * ');
}
system.out.println();
}
}
```
---
## Question 11
Given **N** as input, print the pattern as shown below.
#### TestCase
##### Input 1
```plaintext
N = 4
```
##### Output 1
```plaintext
*
***
*****
*******
```
#### Observation
The key observation here is that:
* Number of spaces in each row is one less than the previous row except 1st row where number of spaces are **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in the starting of each row.
* Number of stars in each row is two more than the previous row except 1st row where number of stars are **1**. Hence we can say that there are total ((rowNumber - 1) * 2 + 1) stars between these spaces.
For N = 4,
| Row | Spaces | Stars | Spaces |
|:---:|:-----:|:------:|:-----:|
| 1 | 3 | 1 | 3 |
| 2 | 2 | 3 | 2 |
| 3 | 1 | 5 | 1 |
| 4 | 0 | 7 | 0 |
#### PseudoCode
```java
function pattern(int N) {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N - i; j++) {
system.out.print(' ');
}
for (int j = 1; j <= (i - 1) * 2 + 1; j++) {
system.out.print(' * ');
}
for (int j = 1; j <= N - i + 1; j++) {
system.out.print(' ');
}
system.out.println();
}
}
```

View File

@@ -0,0 +1,279 @@
# Refresher : Strings
# Introduction to String
---
## Explanation
Lets consider this following pseudo-code:
```java
System.out.print("Hello World")
```
The part ie "Hello World" is known as **string**.
String is defined as the sequence of characters.
Characters involves - [A - Z] , [a - z] , [0 - 9] , spaces, tabs, new line, **{@,#,$,...}**.
### Examples
* "abc123" - This is a string
* "abc $ - This is **not** a string, as this dont have ending double quotes.
* " 123 " - This is a string
* 123 - This is **not** a string. This is an integer
---
## String VS Integer
"123" is a string but `123` is an integer. On string we apply operations like concatanation, length ,etc. In integer, we apply addition, multiplication,etc.
The basic difference in string and integer is in the operations we do on them.
---
## String in Computers
### Explanation
The computers only understands binary, which is base 2. All the numbers which is base 10 is converted to binary so that computers understands it.
All the texts, pictures, audios , etc are similarly converted to numbers in computers.
Lets suppose we have a string "xyz" and in computer x is denoted by the number a, y is by b and z is by c. So we can say that "xyz" is represented by the number [ a b c].
But there is no inherent rule of mapping, all this is done by assumption, which creates a problem. So to make things uniform, ASCII standard is implemented.
---
## ASCII
### Explanation
ASCII, in full American Standard Code for Information Interchange, a standard data-encoding format for electronic communication between computers. ASCII assigns standard numeric values to letters, numerals, punctuation marks, and other characters used in computers.
The ASCII table looks like this:-
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/538/original/upload_b9eac62788e8d64eb48a0af5e3ac2b25.png?1697782855)
> The learners are not required to remember this.
---
## ASCII
### Explanation
Suppose we have a string:
```java
String country = "India";
```
We assume String is an array of characters, hence it is comprehended as:
```java
"India" -> ['I', 'n', 'd', 'i', 'a']
```
Length of string is given by
```java
str.length()
```
If we want to access the i-th character of the string, we use:
```java
str.charAt(index)
```
### Question - 1
Given a String, print its characters in new line
**Input:**
```java
String -> "India"
```
**Output:**
```plaintext
I
n
d
i
a
```
**Approach:** Iterate through each character in the string using a for loop and print it on a new
**Code:**
```java
for(int i = 0; i < country.length(); i++) {
System.out.println(country.charAt(i));
}
```
### Question - 2
Given a String, print the ASCII of its characters in new line
**Input:**
```java
String -> "India"
```
**Output:**
```plaintext
73
110
100
105
97
```
> Hint : Java understands characters as numbers
**Approach:** Iterate through each character in the string, cast it to an integer to get its ASCII value, and then print that value on a new line.
**Code:**
```java
String str = "India";
for(int i = 0; i < str.length(); i++) {
System.out.println((int)str.charAt(i));
}
```
### Question - 3
Given a String, print the count of upper-case characters
**Input:**
```java
String -> "kjRS78q31@3 Q"
```
**Output:** 3
> Hint 1 : A-Z = $65 - 90$
> Hint 2 : You don't need Hint 1
**Approach:** The approach iterates over each character of the string str. For each character, it checks if it falls within the ASCII range for uppercase letters ('A' to 'Z'). If so, it increments the counter cnt. At the end, the total count of uppercase characters is printed.
**Code:**
```java
int cnt = 0;
String str = "kjRS78q31@3 Q";
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= 'A' && c <= 'Z') {
cnt++;
}
}
System.out.println("Count of uppercase chars is " + cnt);
```
### Question - 4
Given a String, print the count of special characters
**Input:**
```java
String -> "kjRS78q31@3 Q"
```
**Output:** 2
> Special Characters means non numeric
**Approach:** The code iterates over each character of the string str. For each character, it checks if it's neither a number, nor an uppercase letter, nor a lowercase letter (i.e., it's a special character). If so, it increments the counter cnt. The final count represents the number of special characters.
**Code:**
```java
public static int specialChars(String str) {
int cnt = 0;
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(
!(c >= '0' && c <= '9') &&
!(c >= 'A' && c <= 'Z') &&
!(c >= 'a' && c <= 'z')
) {
cnt++;
}
}
return cnt;
}
```
### Question - 5
Given a string, return the string in reverse
**Input:** : "Aarnav"
**Output:** "vanraA"
* **Approach 1:** For each character in the string (from front to back), prepend it to the result. This builds the reversed string from front to back.
```java
ans = ""
ans = 'A' + ans = 'A' + "" = "A"
ans = 'a' + ans = 'a' + "A" = "aA"
ans = 'r' + ans = 'r' + "aA" = "raA"
.
.
ans = 'v' + ans = 'v' + "anraA" = "vanraA"
```
* **Approach 2:** For each character in the string (from back to front), append it to the result. This builds the reversed string from back to front.
```java
ans = ""
ans = "" + 'v' = "v"
ans = "v" + 'a' = "va"
.
.
.
ans = "vanra" + 'A' = "vanraA"
```
**Code:**
```java
public static String reverse(String str) {
String ans = "";
for(int i = 0; i < str.length(); i++) {
ans = str.charAt(i) + ans;
}
return ans;
}
```
### Question - 6
Given a String, check whether its a palindrome
**Palindrome** - A string which reads the same from front and back
**Examples** - madam, maam, malayalam, dad, mom, racecar, nitin
> Hint: Re-use previous reverse code
**Approach:** Reverse the given string and compare it with the original. If they are identical, then the string is a palindrome.
**Code:**
```java
public static boolean isPalindrome(String str) {
String rev = reverse(str);
if (str.equals(rev)) {
return true;
} else {
return false;
}
}
```

View File

@@ -0,0 +1,561 @@
# Refresher : While Loop
## While Loop
### Example
* Say we need to print "Hello" 5 times.
* We can do it as :-
```cpp
System.out.print("Hello");
System.out.print("Hello");
System.out.print("Hello");
System.out.print("Hello");
System.out.print("Hello");
```
* But what if we have to do the same 100 times or 1000 times ?
* It would be not feasible.
* Solution to above is to use **while loop** :-
```cpp
int count = 0 ;
while(count < 5)
{
System.out.print("Hello");
count ++ ;
}
```
#### Syntax
```cpp
intialization
while(Condition)
{
// loop work
updation
}
```
---
### Question
```
int i = 1;
i = i + 1;
```
What is the new value of i ?
**Choices**
- [x] 2
- [ ] 1
- [ ] 0
- [ ] 3
**Solution**
```plaintext
i = 1
i = i + 1 => i = 1 + 1 = 2
```
---
## Question 1
### Question
Given an integer N as input. Print from 1 to N ?
#### Testcase 1
```plaintext
Input :
N = 4
```
#### Solution 1
`Output : 1 2 3 4`
#### Approach
* Intialize the count with 1.
* While loop will execute till count <= N.
* Print count.
* In loop update the count by increamenting 1.
#### Code
```cpp
public static void main(){
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = 1;
while (count <= N) {
System.out.printLn(count + " ");
count++ ;
}
}
```
---
## Question 2
### Question
Given an integer N as input. Print from N to 1 ?
#### Testcase 1
```plaintext
Input :
N = 4
```
#### Solution 1
`Output : 4 3 2 1`
#### Approach
* Intialize the count with N.
* While loop will execute till count >= 1.
* Print count.
* In loop update the count by decreamenting it by 1.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = N;
while (count >= 1) {
System.out.print(count + " ");
count--;
}
}
```
---
## Question 3
### Question
Given an integer N as input. Print odd values from 1 to N ?
#### Testcase 1
```plaintext
Input : N = 8
```
#### Solution 1
```plaintext
Output : 1 3 5 7
```
#### Approach
* Since odd numbers start from 1, intialize the count with 1.
* While loop will execute till count <= N.
* print count.
* In loop update the count by increamenting it by 2 since adding 2 to previous odd will yeild next odd number.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = 1;
while (count <= N) {
System.out.print(count + " ");
count += 2;
}
}
```
---
## Question 4
### Question
Given an integer N as input. Print odd values from 1 to N ?
#### Testcase 1
```plaintext
Input :
N = 8
```
#### Solution 1
`Output : 1 3 5 7`
#### Approach
* Since odd numbers start from 1, intialize the count with 1.
* While loop will execute till count <= N.
* print count.
* In loop update the count by increamenting it by 2 since adding 2 to previous odd will yeild next odd number.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = 1;
while (count <= N) {
System.out.print(count + " ");
count += 2;
}
}
```
---
## Question 5
### Question
Given an integer N as input, print multiples Of 4 till N ?
#### Testcase 1
```plaintext
Input : N = 18
```
#### Solution 1
```plaintext
Output : 4 8 12 16
```
#### Approach
* Since multiple of 4 numbers start from 4, intialize the count with 4.
* While loop will execute till count <= N.
* Print count.
* In loop update the count by increamenting it by 4 since adding 4 to previous multiple will yeild the next multiple.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = 4;
while (count <= N) {
System.out.print(count + " ");
count += 4;
}
}
```
---
### Question
```cpp
int i = 1;
while (i <= 10) {
i = i * i;
System.out.print(i + " ");
i++;
}
```
What will be the output ?
**Choices**
- [x] 1 4 25
- [ ] Error
- [ ] Infinite loop
- [ ] 100 12 34
**Solution**
```plaintext
|i = 1 | i <= 10 | i * i = 1 | i++ = 2 |---> iteration 1
|i = 2 | i <= 10 | i * i = 4 | i++ = 5 |---> iteration 2
|i = 5 | i <= 10 | i * i = 25 | i++ = 26 |---> iteration 3
```
---
### Question
```java
public static void main() {
int i = 0;
while (i <= 10) {
System.out.print(i + " ");
i = i * i;
}
}
```
What will be the output ?
**Choices**
- [x] Loop will never end
- [ ] 1 4 9 16 25 36 49 64 81 100
- [ ] 1 2 3 4
- [ ] 0 0 0 0
**Solution**
```plaintext
Since i would always be less than 10 hence infinite loop
```
---
## Question 6
### Question
Q5 : Given an integer N as input, print perfect squares till N ?
> Perfect square —> An integer whose square root is an integer
#### Testcase 1
```plaintext
Input : N = 30
```
#### Solution 1
```plaintext
Output : 1 4 9 16 25
```
#### Approach
* Intialize count = 1
* While loop will execute till count * count <= N.
* Print count * count.
* In loop update the count by increamenting it by 1.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int count = 1;
while (count * count <= N) {
System.out.print(count * count + " ");
count += 1;
}
}
```
---
## Question 7
### Question
Given an integer N as input, print it's digits ?
#### Testcase 1
```plaintext
Input : N = 6531
```
#### Solution 1
```plaintext
Output : 1 3 5 6
```
#### Observations
| N | N % 10 |
|:----:|:----:|
| 6531 | 1 |
| 653 | 3 |
| 65 | 5 |
| 6 | 6 |
* We can see that answer to % 10 of numbers present in the table coincide with the answer.
* We need to find a way to arrive at these numbers while iterating.
* We can do this by dividing number in each iteration by 10.
| N | N/10 |
|:----:|:----:|
| 6531 | 653 |
| 653 | 65 |
| 65 | 6 |
| 6 | 0 |
#### Approach
* Input N.
* While loop will execute till N > 0.
* Print N % 10.
* In loop update the N by dividing it by 10.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
while (N > 0) {
System.out.print(N + " ");
N /= 10;
}
}
```
### Edge Cases
**TestCase 1**
```plaintext
Input :-
N = 0
```
**Solution 1**
```plaintext
Output = 0
```
**Approach** to handle edge case -
* Input N.
* While loop will execute till N >= 0.
* Print N % 10.
* In loop update the N by dividing it by 10.
**Code 1**
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
while (N >= 0) {
System.out.print(N + " ");
N /= 10;
}
}
```
* The above approach leads to **infinite loop**.
* We need to handle above case seperately in if else.
**TestCase 2**
```plaintext
Input :-
N = - 6351 (i.e N < 0)
```
**Solution 2**
```plaintext
Output : 1 3 5 6
```
* Since answer of N < 0 would be same as that of N > 0.
* So we just multiple N with -1 in order to convert it to +ve number .
#### Code final
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
if (N == 0) {
System.out.print(0);
} else {
if (N < 0) {
N *= -1;
}
while (N > 0) {
print(N + " ")
N /= 10;
}
}
}
```
---
## Question 8
### Question
Given an integer N as input, print sum of it's digits ?
> N > 0
#### Testcase 1
```plaintext
Input : N = 6531
```
#### Solution 1
```plaintext
Output : 15
```
#### Approach
* Input N & Intialize sum = 0
* While loop will execute till N > 0.
* Add N % 10 to sum.
* In loop update the N by dividing it by 10.
#### Pseudeocode
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int Sum = 0;
while (N > 0) {
Sum += (N % 10);
N /= 10;
}
System.out.print(Sum);
}
```
---
### Question
Which of the following will add the digit `d` to the back of a number `r`
**Choices**
- [x] r * 10 + d
- [ ] d * r
- [ ] d + r
- [ ] d * 10 + r
**Solution**
```plaintext
Let r = 13 & d = 4
We want to add d behind r i.e we need number 134
So r * 10 = 130
r * 10 + d => 130 + 4 = 134
```
---
## Question 9
### Question
Given an integer N as input, Reverse it ?
> N > 0
#### Testcase 1
```plaintext
Input :
N = 6531
```
#### Solution 1
`Output : 1356`
#### Approach
* Input N & Intialize reverse = 0
* While loop will execute till N > 0.
* Set reverse = reverse * 10 + N % 10.
* In loop update the N by dividing it by 10.
#### Code
```cpp
public static void main() {
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
int reverse = 0;
while (N > 0) {
d = N % 10;
reverse = reverse * 10 + d;
N /= 10;
}
System.out.print(reverse);
}
```

View File

@@ -0,0 +1,505 @@
# Refresher: Iteration 1
---
### Question
What is the output of the following?
```python
a = 3
a *= 4
print(a)
```
**Choices***
- [ ] 3
- [ ] 4
- [ ] 7
- [x] 12
---
### Question
What is the output of the following?
```python
a = 5
if(a < 6):
print('Option 1')
if(a < 3):
print('Option 2')
else:
print('Option 3')
```
**Choices**
- [ ] Option 1
- [ ] Option 2
- [ ] Option 3
- [x] Option 1
Option 3
---
### Question
What is the output of the following?
```python
a = 1
b = 0
c = 1
if ( a and b):
print("Option 1")
elif (a and c):
print("Option 2")
else:
print("Option 3")
```
**Choices**
- [ ] Option 1
- [x] Option 2
- [ ] Option 3
- [ ] Option 4
---
### Question
What is the output of the following?
```python
count = 0
while(count < 10):
print(10, end = ' ')
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [ ] Infinite Loop
- [x] 10 10 10 10 10 10 10 10 10 10
---
## Introduction
* Imagine we wish to print the numbers from `1` to `1000`.
* So we can write the code as follows:
```python
print(1)
print(2)
..
..
..
print(1000)
```
* This is not an intelligent task to do. If the task is simple and we want to repeat it 5 times, we might write the same piece of code 5 times But this is not a practical approach if the repetition number is like `100` or `1000`.
* There is a principle in programming called **DRY**
Do you know the full form of it?
* **Don't Repeat Yourself**
* Even if you are writing the same code three times, you are not doing a good job at it. We can either use loops or functions.
* Before seeing loops, let us see why Python does things in a certain way.
* I have a friend Ramesh and I have to take `10` toffies from him. I will pick a chocolate and start counting from `1` until I reach `10` and then stop.
* Let us see in code what we are doing. Each time in a loop we will check if condition until we reach the else part.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/355/original/upload_3c122a95efe68296140b852a2b3fdd5b.png?1708931051)
```python
count = 0
if(count < 10):
take toffee
count += 1
else
stop
```
* There are four things we always do in a loop:
1. Initialization
2. Condition
3. Action
4. Updation
* We will discuss the `while` loop in this class and the `for` loop in the next as it is different in different programming languages.
* The while loop will only run till the condition is true. As soon as the condition becomes false we exit the loop and execute the rest of the code.
### Syntax
```python
variable initialization
while (condition)
{
action
update variable
}
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/356/original/upload_5df881452fccdde7c6aeb1db1b70e8a0.png?1708931114)
This can be read as while this condition is **true** perform this action and update the variable.
Let us quickly move to an example to understand better.
---
## Print numbers from 1 to n
### Example 1 - Print Numbers from 1 to n
```python
n = input()
count = 1
while(count <= n): # can also be written as (count < n + 1)
print(count)
count += 1
print("end")
```
* Parenthesis are optional in while condition.
* Dry run for n = 5
If I do not write the incrementing `count` statement what will happen?
It will fall in the infinite loop and `1` will be printed forever.
* Always ensure you have all 4 things while writing a loop.
* In any programming language all the loops will always have these four things.
* An alternative way of writing this code is as follows:
```python
n = input()
count = 0
while count < n:
count += 1
print(count)
```
This is because counting in programming languages starts from `0`. Array indexing in most of the languages also starts from `0`. This is doing the same thing except the statements are shuffled.
---
## Print number from n to 1
### Example 2 - Print Number From n to 1
* Go grab your notebook, iPad, or laptop try writing code for the above question, and put the solution in the chat section.
* Writing in a book is best practice.
```python
n = int(input())
while n >= 1:
print(n)
n -= 1
```
* Dry run for n = 5
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/358/original/upload_075cfea2f2168b9130db73ee44a714da.png?1708931178)
---
## Print even numbers from 1 to 100
### Example 3 - Print Even Numbers From 1 to 100
* Once done paste it into the chat section
**Note:** Don't forget the updation of a variable. Also, some of the solutions have conditions where the loop doesn't run at all.
```python
n = int(input())
count = 1
while count <= n:
if count % 2 == 0:
print(count)
count += 1
```
* Write the updation statement in the beginning only.
**Alternative Solution:**
In each interaction, we can update the count by 2. Initially, instead of starting from 1, we can start from 2, and in each iteration, we can do `count += 2` this will always result in an even number.
```python
n = int(input()):
count = 2
while count <= n:
print(count)
count += 2
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/359/original/upload_1548f50a2f2023d5e00150ec29692b2f.png?1708931216)
This is an optimization of the above code as we are not checking the condition as well as the loop will only run half the times of `n`.
---
## Print the sum of all even numbers from 1 to 20
### Example 4 - Print the Sum of All Even Numbers From 1 to 20
We already know how to generate even numbers between `1` to `20`.
Instead of printing it, we need to store it in the bucket.
So we can keep adding these to a number and return the sum at the end.
```python
sum = 0
count = 2
while(count <= n):
sum += count
count += 2
print(sum)
```
---
## Print the digits of number `459`
### Example (VVIMP) - Print the Digits of Number 459 (order Doesn't Matter)
* How to get digits of a number in iteration
* Scraper -> extracts the last digit
* Scissors -> Cuts the last digit
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/360/original/upload_37782f2922540e6578503eb663cec769.png?1708931339)
We will scrape the last digit, print the result, and cut the last digit. This process is continued until all the digits are cut. This is a loop, right?
Is there any operation I told you in the past which takes `459` and returns `9`?
* taking `% 10` (modulo 10) will return the last digit.
* `459 % 10 -> 9`
* `45 % 10 -> 5`
* `4 % 10 -> 4`
Is there any operation that takes `459` and returns `45`, basically cutting the last digit?
* taking `/ 10` (integer division by 10) will return the last digit.
* `int(459 / 10) -> 45`
* `int(45 / 10) -> 4`
* `int(4 / 10) -> 0`
Only division will give the floor value such as `45.9`. Also, `459 // 10` doesn't work with negative integers as `-459` will give `-45.9 -> -46`. Thus, we can simply use `int(val)` to get the integer part of the remaining number.
```python
n = int(input())
while n > 0:
print(n % 10)
n = int(n / 10)
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/361/original/upload_45c12528520f54b65f85c663d69a343f.png?1708931386)
---
### Question
What is the output of the following?
```python
print(149 % 10)
```
**Choices**
- [ ] 14
- [x] 9
- [ ] 1
- [ ] 0
---
## Break and Continue Statements
### Break Statement
**Note:** Only for loops
If you want to break out of the loop if a certain condition is met then you use `break`. It will break the entire loop and execute the next statement.
**Definition** Whenever a break is executed inside a loop, it terminates the loop.
What will be the output of the following code?
```python
count = 1
while count <= 100:
if count == 4:
break
print(count, end=" ")
count += 1
```
**Output**
```plaintext
1 2 3
```
### Continue Statement
**Note:** Only for loops
**Definition** It skips the inside loop and continues the loop's execution.
```python
count = 1
while count <= 10:
count += 1
if count == 4:
continue
print(count, end=" ")
```
**Output**
```plaintext
1 2 3 5 6 7 8 9 10 11
```
* The continue statement simply skips the rest of the instructions of the current interaction and begins with the next iteration.
Look at the example below:
```python
count = 1
while count <= 10:
if count == 4:
continue
print(count, end=" ")
count += 1
```
* This will end up in an infinite loop. As the updation condition is never performed due to continue statment. So once it reaches 4, it keeps looping on 4.
---
## While-else
* Only and only in Python
* Else block will run only after the loop successfully terminates without a break.
```python
count = 1
while count <= 100:
if count == 4:
break
print(count, end=" ")
count += 1
else:
print("Yayy!")
```
* It will not print `Yayy!` as it is terminated via a `break` statement rather than terminating naturally.
---
## Check whether a number is prime or not
### Example - Check Whether a Number is Prime or Not
* Prime number is only divisible by `1` or the number itself.
* One is neither prime not consonant.
* We can say that `a` is divisible by `n` if `a % n == 0`.
* We can say that `24` is not prime as `24` divides `2, 4, 6, 8, etc.`
* We can say that `23` is a prime number cause it only divides `1` and `23`.
* Write a code to check if the number is prime or not. Start a loop from `2` to `n-1` if it is dividing any number then return `not prime` else `prime`. We are not required to use `break`, `continue`, or `while else`.
**Solution 1:**
Let us say our number is `25`.
We will use a variable `flag` to store whether a number is prime or not. It is simply a boolean variable initialized with `false`.
As soon as the number is divisible by some other number we can change its value to `true` and it is not prime. If the number is not divisible by any other number the `flag` remains `false` and we can conclude that it is a prime number.
```python
n = int(input())
count = 2
flag = False
while count < n:
if n % count == 0:
flag = True
count += 1
if flag:
print("Not Prime")
else:
print("Prime")
```
**Solution 2:**
* Is not very different from the previous solution.
* Now consider if the number is `9`, it is divisible by `3`. Do we need to check for other numbers? We don't! If the given number is divisible by any other number, we can break from the loop and declare that it is prime.
* This is a great situation where we can use `break`.
```python
n = int(input())
count = 2
flag = False
while count < n:
if n % count == 0:
flag = True
break
count += 1
if flag:
print("Not Prime")
else:
print("Prime")
```
**Solution 2:**
* We can remove the flag. We can use the `while else` statement.
* Instead of checking the flag, we can say that if we didn't break from the loop, it is a prime number.
* So as soon as we encounter that the number is divisible by some other number we print it is not prime. In the else part we print it is prime.
```python
n = int(input())
i = 2
while i < n:
if n % i == 0:
print("not prime")
break
i += 1
else:
print("prime number")
```
---
### Question
When can we say a number A is divisible by n?
**Choices**
- [x] A % n == 0
- [ ] A / n == 0
- [ ] A // n == 0
- [ ] A % n != 0
---
### Question
What is the output of the following?
```python
count = 1
while(count <= 5):
if(count == 2):
break
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 3 4 5
- [x] 1
- [ ] 1 2
- [ ] 0 1
---
### Question
What is the output of the following?
```python
count = 1
while(count <= 5):
if(count == 3):
continue
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 2 3 4 5
- [ ] 1 2 4
- [ ] 0 1 2 4 5
- [x] Infinite Loop

View File

@@ -0,0 +1,486 @@
# Refresher: Iteration 2
# Introduction
---
### Recap
* introduction to loop
* while, while else
* break and continue
* print 1 to n, n to 1
* print even numbers, sum
* prime numbers
* scrapers and scissors
---
### Question
What is the output of the following?
```python
count = 0
while(count < 10):
print(10, end = ' ')
count += 1
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [x] 10 10 10 10 10 10 10 10 10 10
- [ ] Infinite Loop
---
### Question
Which is true for an Odd number n?
**Choices**
- [ ] n % 2 == 0
- [x] n % 2 = = 1
---
### Question
What operation can be used to get the last digit of a number?
**Choices**
- [ ] n - 10
- [ ] n // 10
- [ ] int(n / 10)
- [x] n % 10
---
### Question
What will be the output of the following?
```python
count = 1
while(count <= 5):
if(count == 2):
break
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 3 4 5
- [x] 1
- [ ] 1 2
- [ ] 0 1
---
## Range Function
1. `range(n)` returns number from 0 to n-1.
* start = 0
* jump = 1
* number line example
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/362/original/upload_7f9c7eeebbf0c0d002f592640e888065.png?1708932201)
* range(-5) -> nothing as decrementing -5 we will never reach anywhere.
* range(1) -> 0
2. range(start, end) -> general numbers from [start, end-1]
* jump -> +1
* range(1,3) -> 1,2
* range(-5, -1) -> -5, -4, -3, -2
* range(-4, -10) -> nothing
* range(5, 1) -> nothing
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/363/original/upload_17b7f2a819543a855560aeb856b7c327.png?1708932266)
3. range(start, end, jump)
* start, end - 1
* range(1,6,2) -> 1, 3, 5
* range(0, -5, -1) -> 0, -1, -2, -3, -4
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/364/original/upload_2732cf5a66563800ba66530fac1d84fc.png?1708932301)
### Precautions
* jump can not be zero
* range always takes and returns an integer value
---
## Iterables an Iterators
* Assume that we have a bag of candies. I put my hand in the bag and take the candies out of the back one by one.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/365/original/upload_e1c2e9662f5d17873ba95ed6134f2684.png?1708932357)
* Examples - list, dict, set, string, range, enumerate, tuple
* Iterables are groups of objects
* Iterator can be related to the hand that we are using to take candies out of the iterables(bag of candies).
### Range as an Iterable
* Range is iterable, it is a collection of integers. If the range returns nothing we can say the bag is empty it doesn't return anything.
`print(range(3))` What will this return?
* Print is not an iterator it will simply return `range(3)`.
* for loop is one of the best iterators.
---
## For Loop
**Syntax:**
```python
for variable in iterable:
action
```
* With for loop we can skip initialization, condition, and updation.
* It is an alternative to the `foreach` loop.
* The for loop can be used with iterables such as lists, dictionaries, etc. This will be covered when we will discuss lists and other iterables.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/366/original/upload_cda895392e6a7ae96cbef51f67006f2e.png?1708932415)
### Question - Print 1 to 100?
```python
for i in range(1, 101):
print(i)
```
---
### Question
What will the sequence be generated by the following?
```python
range(5)
```
**Choices**
- [ ] 1 2 3 4 5
- [ ] 0 1 2 3 4 5
- [ ] 1 2 3 4
- [x] 0 1 2 3 4
---
### Question
What will the sequence be generated by the following?
```python
range(5,15, 2)
```
**Choices**
- [ ] 5,6,7,8,9,10,11,12,13,14,15
- [ ] 5,7,9,11,13,15
- [x] 5,7,9,11,13
- [ ] 5,6,7,8,9,10,11,12,13,14
---
### Question
What will the sequence be generated by the following?
```python
range(-5,0,1)
```
**Choices**
- [ ] -5,-4,-3,-2,-1,0
- [ ] Nothing
- [ ] 0,-1,-2,-3,-4,-5
- [x] -5,-4,-3,-2,-1
---
### Question
What will the sequence be generated by the following?
```python
range(-10,-5,-1)
```
**Choices**
- [ ] -10,-9,-8,-7,-6,-5
- [ ] -10,-9,-8,-7,-6
- [x] Nothing
- [ ] -6,-7,-8,-9,-10
---
### Question
What is the output of the following?
```python
for i in range(0,1):
print('Hello')
```
**Choices**
- [ ] Hello
Hello
- [ ] Hello
- [x] Nothing
- [ ] 0
1
How many values will be returned by this:
```python
range(n) -> n
```
If you want the loop to run `n` times just say range(n). The loop will run `n` times but start with zero till `n-1` therefore `n` values.
```python
range(5) -> 0, 1, 2, 3, 4 => 5 values
```
---
## Break and Continue in For Loop
* Break and Continue is same as we saw in while loop.
* If you want to break out of the loop if a certain condition is met then you use break. It will break the entire loop and execute the next statement.
* It skips the inside loop and continues the loops execution.
**[ASK THE LEARNERS]**
is `_`(underscore) a valid variable name?
* Variable should start with an alphabet or an `_`
* can only have underscore, alphabets, and numbers.
* It should not start with a number.
* Many programmers use underscore when they don't need a name for a variable in the for loop.
```python
for _ in range(10):
print("hello")
```
* If we use `_` it won't give a warning in case we are not using it. With any other variable name, it will give a warning in Python.
* What will be the output of the following:
```python
for i in range(10):
if(i == 4):
break
print(i)
```
**Output:**
```plaintext
0
1
2
3
```
* What will be the output of the following:
```python
for i in range(6):
if(i % 2 == 0):
continue
print(i)
```
**Output:**
```plaintext
1
3
5
```
---
## Pass Statement
* It is not to be used in competitive programming or interviews. It is usually used in testing.
* The `pass` does nothing. It signifies that the programmer will later add some code to it. Right now ignore this block.
```python
for i in range(6):
if(i % 2 == 0):
pass
print(i)
```
* Pass will still print the `i`. In case of continuing it will directly begin with a new iteration.
---
## For Else Loop
* Else statement will execute if the loop terminates successfully i.e. without a break
* Write a code for the prime number in the for loop.
```python
n = int(input())
for i in range(2,n):
if(n % i == 0):
print("Not Prime")
break
else:
print("Prime")
```
---
### Question
What is the output of the following?
```python
for i in range(0,10):
if(i % 3 == 0):
continue
print(i, end = ' ')
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [ ] 0 1 2
- [ ] 0 1 2 4 5 7 8 9
- [x] 0 1 2 4 5 7 8
---
### Question
What is the output of the following?
```python
for i in range(1,10):
if(i % 3 == 0):
break
print(i, end = ' ')
```
**Choices**
- [ ] 1 2 3 4 5 6 7 8 9
- [x] 1 2
- [ ] 1 2 4 5 7 8 9
- [ ] 1 2 4 5 6 7 8
---
## Nested Loops
* If we write a loop inside a loop it is a nested loop.
* Look at the pattern below and write a code to generate this pattern.
```plaintext
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
```
If I want to print `1 to 5`, how will I write the code?
```python
for i in range(1,6):
print(1, end = " ")
```
Now if I want to do this 5 times will I do this?
```python
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
```
* No right? What principle it is not following?
* DRY (Do not repeat yourself).
* I will use a nested loop.
```python
for _ in range(5):
for i in range(1,6):
print(1, end = " ")
print()
```
* Single for loop gives 1D data, 2 loops nested will give 2D, and so on.
* Similarly we can write nested while loop
---
## Difference b/w For and While Loop
| For | While |
| :------------------------------------------------------------------------------: | :--------------: |
| It is simple to use. Initialization, condition, and updation in a single line. | Complex to use |
| Only for simple iteration | Complex tasks such as scrapper and Scissors can be performed |
**Note:** Never update the iteration variable in the for loop.
---
## Pattern Printing Problems
```plaintext
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
```
Write a code to print this pattern.
:::warning
Please take some time to think about the solution on your own before reading further.....
:::
**Solution 1**
```python
for i in range(5):
for j in range(5):
print("*", end = " ")
print()
```
**Solution 2**
We are using string to integer multiplication. The statement `print("* "*5)` will generate a line with 5 stars and a space in between.
```python
for _ in range(5):
print("* " * 5)
```
### Staircase Binding
```plaintext
*
* *
* * *
* * * *
* * * * *
```
:::warning
Please take some time to think about the solution on your own before reading further.....
:::
**Solution 1**
When `i` is `1` we print `1` star, when `i` is `2` we print `2` star, and so on.
```python
n = int(input())
for i in range(1, n + 1):
print("* " * i)
```
**Solution 2**
We can do it with the nested loop as well
```python
for i in range(1, n + 1):
for j in range(i):
print("*", end = " ")
print()
```
### Reverse Staircase
```python
*
* *
* * *
* * * *
* * * * *
```
* Can you guys do it or should I give you a hint?
**No spaces between stars**
* Assuming that there is no space between starts. What we are doing is `4 spaces 1 star`, `3 spaces 2 stars`, `2 spaces 3 stars` and so on.
```python
for i in range(1,6):
spaces = " " * (n - i)
stars = "*" * (i)
print(spaces + stars)
```
### Homework Problem
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/368/original/upload_5703b40bbef52803b280818dfa61dbff.png?1708932888)

View File

@@ -0,0 +1,936 @@
# Refresher: List 1
## Defining a List
### Definition
A list is a built-in data type that represents an ordered collection of items. It is a mutable, dynamic array, meaning you can modify its elements and size after creation.
### Syntax
```python
my_list = [element1, element2, element3, ...]
```
### Examples
- The provided code snippets demonstrate various aspects of working with lists in Python.
**Code 1**:
```python
a = [1, 2, 3]
```
- Initializes a list `a` with three integer elements.
**Code 2**:
```python
a = [1, "a"]
```
- Initializes a list `a` with two elements: an integer `1` and a string `"a"`.
**Output 2**:
```plaintext
# SyntaxError: closing parenthesis '}' does not match opening parenthesis '['
a = [1, "a"]
```
- This part of the code seems incomplete and might be causing a syntax error. The specific error is related to unmatched parentheses.
**Code 3**:
```python
a = ["a", 1, 3.14, True] # Lists can be heterogeneous
```
- Demonstrates that lists in Python can contain elements of different data types.
**Code 4**:
```python
a = list(range(10))
print(a)
```
**Output 4**:
```plaintext
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
- Uses the `list()` constructor to create a list containing elements from `0` to `9` (result of `range(10)`).
**Code 5**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students)
```
**Output 5**:
```plaintext
['Kusum', 'Shubham', 'Pooja']
```
- Prints the list of student names.
### Indexing in a List
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/375/original/upload_f402ef9034ec28e26319f0e940031598.png?1708936235)
**Code**:
```python
print(students[1])
```
**Output**:
```plaintext
Shubham
```
**Code**:
```python
print(students[5])
```
**Output**:
```plaintext
# IndexError: list index out of range
```
**Explanation**:
- Accessing elements in a list using indices.
- An IndexError occurs when trying to access an index beyond the list's length.
### Reverse Indexing
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/376/original/upload_e92b207fe616514bb9f3004786722d51.png?1708936520)
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students[-1])
```
**Output**:
```plaintext
Pooja
```
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students[-100])
```
**Output**:
```plaintext
# IndexError: list index out of range
```
### Updating an Index in A List
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students)
```
**Output**:
```python
['Kusum', 'Shubham', 'Pooja']
```
- Updating user at index 3
**Code**:
```python
students[3] = 'Ruben'
print(students)
```
**Output**:
```python
['Kusum', 'Shubham', 'Pooja', 'Ruben']
```
**Code**:
```python
students[-100]
```
**Output**:
```python
# IndexError: list index out of range
```
**Code**:
```python
print(type(students))
```
**Output**:
```python
<class 'list'>
```
- Print even numbers till 10
**Code**:
```python
a = list(range(0, 11, 2))
print(a)
```
**Output**:
```python
[0, 2, 4, 6, 8, 10]
```
- Print first 10 even numbers
**Code**:
```python
a = list(range(0, 20, 2))
print(a)
```
**Output**:
```python
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
```
**Explanation**:
- Lists can be modified by assigning new values to specific indices.
- Negative indices count from the end of the list.
### Iteration in a List
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
```
- `len()` gives you the number of elements in a list
**Code**:
```python
print(len(students))
```
**Output**:
```python
7
```
**Code**:
```python
# Solution 1
n = len(students)
for i in range(0, n):
print(students[i])
```
**Output**:
```python
Kusum
Shubham
Pooja
Ruben
Aarushi
Vinoth
Veerendra
```
**Code**:
```python
# Solution 2
for student in students:
print(student)
```
**Output**:
```python
Kusum
Shubham
Pooja
Ruben
Aarushi
Vinoth
Veerendra
```
### Quiz 1
**Code**:
```python
# quiz
li = [-1, 0, 4]
for i in li:
if i > 0:
print(i, end=' ')
```
**Output**:
```python
4
```
**Explanation**:
- Iterating through a list and printing positive numbers.
### Functions in a List
### len()
- Returns the number of elements in a list.
**Code**:
```python
a = list(range(2, 6))
print(len(a))
```
**Output**:
```plaintext
4
```
### append()
- Appends an object to the end of the list.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
students.append('Vicky')
print(students)
```
**Output**:
```plaintext
['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra', 'Vicky']
```
**Code**:
```python
a = []
a.append('Hi')
print(a)
```
**Output**:
```plaintext
['Hi']
```
### insert()
- The `insert` method is used to insert an element before the specified index in a list.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(1, 'Aakar')
print(a)
```
**Output**:
```plaintext
[1, 'Aakar', 2, 3, 4]
```
**Explanation**:
- The element 'Aakar' is inserted at index 1, shifting the original elements to the right.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(-3, 'Aakar')
print(a)
```
**Output**:
```plaintext
[1, 'Aakar', 2, 3, 4]
```
**Explanation**:
- The negative index `-3` is interpreted as counting from the end of the list, so 'Aakar' is inserted at index 2 from the end.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(100, 'Aakar')
print(a)
```
**Output 3**:
```plaintext
[1, 2, 3, 4, 'Aakar']
```
**Explanation**:
- If the specified index is greater than the length of the list, the element is inserted at the end.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(-100, 'Aakar')
print(a)
```
**Output**:
```plaintext
['Aakar', 1, 2, 3, 4]
```
**Explanation**:
- The negative index `-100` is interpreted as counting from the end of the list, so 'Aakar' is inserted at the beginning of the list.
### pop()
- Removes and returns an item at the specified index (default last).
- Raises `IndexError` if the list is empty or the index is out of range.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
print(students.pop())
print(students)
```
**Output**:
```plaintext
Veerendra
['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth']
```
**Code**:
```python
a = [1, 2, 3, 4]
print(a.pop(5))
print(a)
```
**Output**:
```plaintext
# IndexError: pop index out of range
```
**Code**:
```python
a = []
print(a.pop())
print(a)
```
**Output**:
```plaintext
# IndexError: pop from an empty list
```
**Explanation**:
- The `pop()` function removes and returns an item at a specified index.
- Raises an `IndexError` if the index is out of range.
### remove()
- Removes the first occurrence of a value.
- Raises `ValueError` if the value is not present.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
students.remove('Shubham')
print(students)
```
**Output**:
```plaintext
['Kusum', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
```
**Code**:
```python
a = [1, 2, 3, 2, 4]
a.remove(2)
print(a)
```
**Output**:
```plaintext
[1, 3, 2, 4]
```
**Code**:
```python
a = [1, 2, 3, 4]
a.remove(5)
print(a)
```
**Output**:
```plaintext
# ValueError: list.remove(x): x not in the list
```
**Explanation**:
- The `remove()` function removes the first occurrence of a specified value.
- Raises a `ValueError` if the value is not present.
### Quiz
### Quiz 1
```python
li = [1, 2, 3]
li.append('4')
print(li)
```
**Answer**: [1, 2, 3, '4']
### Quiz 2
```python
li = []
print(len(li))
```
**Answer**: 0
### Quiz 3
```python
li = [1, 2]
print(li.pop())
```
**Answer**: 2
### Quiz 4
```python
li = [1, 3, 4]
li.insert(0, 2)
print(li)
```
**Answer**: [2, 1, 3, 4]
### Quiz 5
```python
li = [1, 2]
print(li.remove(2))
```
**Answer**: None
## Reverse
**Code**:
```python
a = [1, 2, 3]
print(a.reverse())
print(a)
```
**Output**:
```plaintext
[3, 2, 1]
```
**Code**:
```python
a = []
print(a.reverse())
print(a)
```
**Output**:
```plaintext
None
[]
```
**Explanation**:
- The `reverse()` method reverses the elements of a list in place.
## + operator
- Concatenating two lists.
- Creates a new list.
**Code**:
```python
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
print(a)
print(b)
```
**Output**:
```plaintext
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
[4, 5, 6]
```
### extend()
- Extend list by appending elements from the iterable.
**Code**:
```python
a = [1,2,3]
b = [4,5,6]
a.append(b)
print(a)
print(a[-1]) # not what we want
```
**Output**:
```plaintext
[1, 2, 3, [4, 5, 6]]
[4, 5, 6]
```
**Explanation**:
- The append() method is used, but it appends the entire list b as a single element at the end of list a.
**Code**:
```python
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
print(b)
print(a[-1]) # not what we want
```
**Output**:
```plaintext
[1, 2, 3, 4, 5, 6]
[4, 5, 6]
6
```
**Explanation**:
- The extend() method is used, adding each element from list b individually to the end of list a.
**Code**:
```python
a = [1,2,3]
a.extend(a)
print(a)
```
**Output**:
```plaintext
[1, 2, 3, 1, 2, 3]
```
**Explanation**:
- The extend() method is used to add elements of list a to the end of list a, effectively doubling its content.
## in Operator
- return True or False after searching list
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Aakar', 'Veerendra']
print('Aakar' in students)
print('Kusum' in students)
```
**Output**:
```plaintext
False
True
```
**Explanation**:
- The `in` operator is used to check if an element is present in a list.
- The first print statement checks if 'Aakar' is in the list of students, resulting in `False`.
- The second print statement checks if 'Kusum' is in the list of students, resulting in `True`.
### How to take List as Input?
**Code**:
```python
n = int(input())
a = []
for i in range(n):
item = input()
a.append(item)
print(a)
```
**Output**:
```plaintext
5
a
b
c
d
e
['a', 'b', 'c', 'd', 'e']
```
**Explanation**:
- The code takes an integer `n` as input, then uses a loop to take `n` input items and appends them to a list `a`, resulting in a list of items.
## Split
**Code**:
```python
s = 'I-love-bananas'
li = s.split('-')
print(li)
print(type(li))
```
**Output**:
```plaintext
['I', 'love', 'bananas']
<class 'list'>
```
**Explanation**:
- The `split` method is used to split a string `s` into a list of substrings based on the specified delimiter ('-'), creating a list `li`.
**Code**:
```python
s = 'I--love--bananas'
li = s.split('--')
print(li)
print(type(li))
```
**Output**:
```plaintext
['I', 'love', 'bananas']
<class 'list'>
```
**Explanation**:
- Even if there are multiple consecutive delimiters, `split` correctly handles them and produces the desired list.
**Code**:
```python
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
print(li)
```
**Output**:
```plaintext
5
a b c d e
['a', 'b', 'c', 'd', 'e']
```
**Explanation**:
- The code takes an integer `n` and a space-separated string as input, then uses `split` to create a list `li` of individual items.
**Code**:
```python
# INPUT
# 5
# 12 14 15 16 17
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
new_li = []
for item in li:
new_li.append(int(item))
print(new_li)
```
**Output**:
```plaintext
5
1 2 3 4 5
[1, 2, 3, 4, 5]
```
**Explanation**:
- The code converts a space-separated string of numbers into a list of integers, demonstrating the use of `split` and conversion to integers.
**Code**:
```python
# INPUT
# 5
# 12 14 15 16 17
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
for index in range(len(li)):
li[index] = int(li[index])
print(li)
```
**Output**:
```plaintext
5
1 2 3 4 5
[1, 2, 3, 4, 5]
```
**Explanation**:
- Similar to the previous example, this code converts a space-separated string of numbers into a list of integers using a loop.**Explanation**:
### Problem
Given a List of Student Marks, Count the Number of Student Who Failed
:::info
Please take some time to think about the solution approach on your own before reading further.....
:::
**Code**:
```python
n = int(input())
s = input() # always returns string "a b c d e"
marks = s.split(' ')
for index in range(len(marks)):
marks[index] = float(marks[index])
print(marks)
# ------------------------
count = 0
for index in range(len(marks)):
if marks[index] <= 30:
count += 1
print(count)
```
**Output**:
```plaintext
5
10 20 30 40 50
[10.0, 20.0, 30.0, 40.0, 50.0]
3
```
**Explanation**:
- The code first takes an integer `n` as input, representing the number of students. Then, it takes a string `s` as input, which contains space-separated marks of students in the form of "a b c d e".
- The string of marks is split into a list of strings using the `split` method, and then each element in the list is converted to a floating-point number using a loop.
- The list of marks is printed as output.
- The code initializes a variable `count` to 0 and then iterates through the list of marks. For each mark, if it is less than or equal to 30, the `count` is incremented.
- Finally, the count of students who failed (marks <= 30) is printed as output.
**Output Explanation**:
- For the given input "5" and "10 20 30 40 50", the list of marks after conversion to float is `[10.0, 20.0, 30.0, 40.0, 50.0]`.
- Among these marks, three students have marks less than or equal to 30 (10.0, 20.0, and 30.0). Therefore, the count of students who failed is printed as `3`.

View File

@@ -0,0 +1,284 @@
# Refresher: List 2
## Builtin Functions
### Index
- Given a value and a list, find the element and print "Found" else "Not found"
**Code**:
```python
# Solution 1
li = list(map(int, input().split(' ')))
value = int(input())
for index in range(len(li)):
if li[index] == value:
print('Found at', index)
break
else:
print('Not found')
```
**Output**:
```plaintext
1 2 3 4 5 6
3
Found at 2
```
- Displaying index
**Code**:
```python
# Solution 2
li = list(map(int, input().split(' ')))
value = int(input())
if value in li:
print('Found at', li.index(value))
else:
print('Not found')
```
**Output**:
```plaintext
1 2 3 4 5 6
3
Found at 2
```
**Explaination**:
- Solution 1 uses a for loop to iterate through the list and check if each element is equal to the given value. If found, it prints the index and breaks out of the loop. If not found, it prints "Not found."
- Solution 2 uses the `in` operator to check if the value is present in the list. If found, it prints the index using the `index()` function. If not found, it prints "Not found."
### max
- Given a list, you have to find the maximum element in this list.
**Code**:
```python
li = [-13, -53, -23, -21, -55]
max_value = li[0]
for item in li:
if max_value < item:
max_value = item
print(max_value)
```
**Output**:
```plaintext
-13
```
**Code**:
```python
li = [-13, -53, -23, -21, -55]
max_value = None
for item in li:
if max_value is None or max_value < item:
max_value = item
print(max_value)
```
**Output**:
```plaintext
-13
```
**Explaination**:
- The first solution initializes `max_value` with the first element of the list and iterates through the list, updating `max_value` if a larger element is found.
- The second solution initializes `max_value` to `None` and iterates through the list, updating `max_value` if a larger element is found. The `is None` check is used to handle an empty list case.
### Printing max Value
**Code**:
```python
li = [-13, -53, -23, -21, -55]
print(max(li))
print(max(1, 2, 3, 4, 5, 3, 4, 5, 1))
```
**Output**:
```plaintext
-13
5
```
**Explaination**:
- The `max()` function is used to directly find the maximum value in the list or a set of values.
### Printing min Value
**Code**:
```python
li = [-13, -53, -23, -21, -55]
print(min(li))
print(min(1, 2, 3, 4, 5, 3, 4, 5, 1))
```
**Output**:
```plaintext
-55
1
```
**Explaination**:
- The `min()` function is used to directly find the minimum value in the list or a set of values.
### Slicing
In this section, we will learn how to slice the list `[49, 6, 71]` from the given list
**Code**:
```python
li = [2, 23, 49, 6, 71, 55]
def sub_list(li, startIndex, endIndex):
new_li = []
for i in range(startIndex, endIndex + 1):
new_li.append(li[i])
return new_li
print(sub_list(li, 2, 4))
```
**Output**:
```plaintext
[49, 6, 71]
```
**Explaination**:
- The `sub_list` function takes a list and two indices as input and returns a new list containing elements from the start index to the end index.
### More slicing examples
#### li[:end]
**Code**:
```python
a = list(range(10))
print(a)
print(a[::-2])
```
**Output**:
```plaintext
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 7, 5, 3, 1]
```
**Explanation**:
- `a[::-2]` creates a new list by slicing `a` with a step of -2, starting from the end.
- It includes every second element in reverse order, resulting in `[9, 7, 5, 3, 1]`.
#### li[start:end]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[1:5])
```
**Output**:
```plaintext
[2, 3, 9, 8]
```
**Explanation**:
- The slice `a[1:5]` extracts elements starting from index 1 up to (but not including) index 5 from list `a`.
#### li[start:]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[2:])
```
**Output**:
```python!
[3, 9, 8]
```
**Explanation**:
- The slice `a[2:]` extracts elements starting from index 2 till the end of the list `a`.
#### li[start\:end:range]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[1:4:2])
```
**Output**:
```python
[2, 9]
```
**Explanation**:
- The slice `a[1:4:2]` extracts elements starting from index 1 up to (but not including) index 4 with a step of 2.
- It includes every second element in the specified range, resulting in `[2, 9]`.
---
## Problem Solving
### Question
Right shift the given array:
**li = [2,3,4,5,6]
n = [0,n - 1]
Output = [3,4,5,6,2]**
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution 1
**Code**:
```python
li = [2,3,4,5,6]
n = int(input())
for i in range(n):
a = li.pop(0)
li.append(a)
print(li)
```
**Output**:
```python
3
[5, 6, 2, 3, 4]
```
## Solution 2
**Code**:
```python
li = [2,3,4,5,6]
n = int(input())
print(li[n:] + li[:n])
```
**Output**:
```python
3
[5, 6, 2, 3, 4]
```

View File

@@ -0,0 +1,222 @@
# Refresher: List 3
## Nested List
### Introduction
- A nested list in Python is a list that can contain other lists as elements.
- It allows you to create a two-dimensional structure, also known as a 2D list, where each element in the outer list can be a list itself.
**Code**:
```python
maths = [1, 1, 1]
science = [2, 2, 2]
history = [3, 3, 3]
subjects = [maths, science, history]
print(subjects)
```
**Output**:
```python
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
```
**Explanation of code**:
- Three separate lists, `maths`, `science`, and `history`, are created.
- These lists are then combined into a single list named `subjects`.
- The `print(subjects)` statement displays the resulting nested list.
---
## Indexing in a 2D List
- Indexing in a 2D list involves accessing elements using two indices: one for the outer list (row) and another for the inner list (column).
**Code**:
```python
print(subjects[0][2])
# row major form
print(subjects)
```
**Output**:
```python
1
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
```
**Explanation of code**:
- The expression `subjects[0][2]` accesses the element in the first row (index 0) and the third column (index 2) of the 2D list.
- The second `print(subjects)` statement displays the entire 2D list.
---
## Iterating a 2D List
### Example 1
**Code**:
```python
for row_index in range(len(subjects)):
for col_index in range(len(subjects[row_index])):
print(subjects[row_index][col_index], end = ' ')
```
**Output**:
```python
1 1 1 2 2 2 3 3 3
```
**Explanation of code**:
- Nested loops iterate through each element of the 2D list, printing them horizontally.
### Example 2
**Code**:
```python
for row_index in range(len(subjects)):
for col_index in range(len(subjects[row_index])):
print(subjects[row_index][col_index], end=' ')
print()
```
**Output**:
```python
1 1 1
2 2 2
3 3 3
```
**Explanation of code**:
- Similar to Example 1, but with an additional `print()` to create a new line after each row.
### Example 3
**Code**:
```python
for col_index in range(len(subjects[0])):
for row_index in range(len(subjects)):
print(subjects[row_index][col_index], end = ' ')
print()
```
**Output**:
```python
1 2 3
1 2 3
1 2 3
```
**Explanation of code**:
- This example transposes the 2D list by iterating through columns first and then rows.
---
### Input in a 2D List
### Example
**Code**:
```python
def take_list_as_input():
li = list(map(int, input().split()))
return li
a = []
for i in range(3):
a.append(take_list_as_input())
print(a)
```
**Output**:
```python
12 13 14
45 46 47
34 35 36
[[12, 13, 14], [45, 46, 47], [34, 35, 36]]
```
**Explanation of code**:
- The `take_list_as_input()` function reads a line of space-separated integers and converts them into a list.
- The loop collects three such lists to create a 2D list named `a`.
### Row Wise Sum
**Code**:
```python
def take_list_as_input():
li = list(map(int, input().split()))
return li
a = []
for i in range(3):
a.append(take_list_as_input())
print(a)
for row_index in range(len(a)):
row_sum = sum(a[row_index])
print(row_sum)
```
**Output**:
```python
1 1 1
2 2 2
3 3 3
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
3
6
9
```
**Explanation of code**:
- Calculates and prints the sum of each row in the 2D list.
---
## Matrix Addition
**Code**:
```python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
c = []
for row_index in range(len(a)):
temp = []
for col_index in range(len(a[row_index])):
temp.append(a[row_index][col_index] + b[row_index][col_index])
c.append(temp)
print(c)
```
**Output**:
```python
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
```
**Explanation of code**:
- Performs matrix addition on two 2D lists (`a` and `b`) and stores the result in the list `c`.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,677 @@
# Refresher: Strings 2
### Question
What is the output of the following?
```python
a = "Age:"
print(a + 23)
```
**Choices**
- [ ] Age:23
- [ ] Age:
- [x] Error
- [ ] Age: 23
In the given code, there is an attempt to concatenate a string ("Age:") with an integer (23). This operation is not allowed in Python without explicit conversion and hence will output an error.
---
### Question
What is the output of the following?
```python
a = "Hello"
b = a * 3
print(len(b) == (len(a) * 3))
```
**Choices**
- [x] True
- [ ] False
- [ ] Error
The output is True, because the length of the string `b` is compared to the result of multiplying the length of `a` by 3, and they are equal.
---
### Question
What is the output of the following?
```python
s = 'Name : {}, Age : {}'
print(s.format(25, 'John'))
```
**Choices**
- [ ] Name : John, Age : 25
- [x] Name : 25, Age : John
- [ ] Error
The `format` method replaces the `{}` placeholders in the string with the provided values in the order they appear. In this case, `25` is placed where the first `{}` is, and `'John'` is placed where the second `{}` is, resulting in the output "Name : 25, Age : John".
---
### Question
What is the output of the following?
```python
s = 'Name : {name}, Gender : {}, Age : {age}'
print(s.format('Male', age = 25, name = 'John'))
```
**Choices**
- [x] Name : John, Gender : Male, Age : 25
- [ ] Name : Male, Gender : John, Age : 25
- [ ] Error
The `format` method is used to substitute values into the placeholders `{}`, `{name}`, and `{age}` in the string `s`. The values provided in the `format` method are 'Male' for the first placeholder, 'John' for the `{name}` placeholder, and 25 for the `{age}` placeholder. The resulting string is "Name : John, Gender : Male, Age : 25".
---
## Count Uppercase Letters
## Count Number of Uppercase Letters
### Problem
Given a string, the task is to count the number of uppercase letters in the string.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution
The solution involves iterating through each character in the string and checking if its ASCII value falls within the range of uppercase letters (A-Z) using the `if` case. Specifically, it ensures that the character is greater than or equal to the ASCII value of 'A' and less than or equal to the ASCII value of 'Z'. For each uppercase letter found, a counter is incremented.
```python
def count_upper(a):
count = 0
for char in a:
if ord('A') <= ord(char) <= ord('Z'):
count += 1
return count
# Example Usage
result = count_upper("ThisIsAString")
print(result)
```
### Output
```plaintext
4
```
### Explanation
In this example, the function `count_upper` takes the input string "ThisIsAString" and iterates through each character. For each character that is an uppercase letter, the counter is incremented. The final count is returned, indicating that there are 4 uppercase letters in the input string.
---
## More Functions in Strings
## More Functions
### join()
### Explanation
The `join()` method concatenates elements of an iterable using a specified separator.
### Example
```python
# Example
separator = '.'
result = separator.join(['Hi', 'there'])
print(result) # Output: 'Hi.there'
# Example 2
result = '.'.join(['2', '31'])
print(result) # Output: '2.31'
result = '.'.join([2, 3])
print(result) # Error
```
#### Explanation
In this example, the elements 'Hi' and 'there' are joined with a dot (`.`) as the separator, resulting in the string 'Hi.there'.
### upper()
### Explanation
The `upper()` method converts all characters in a string to uppercase.
### Example
```python
# Example
a = 'ThisIsAString'
result = a.upper()
print(result) # Output: 'THISISASTRING'
# Example 2
a = 'ThisIsAString12348$#'
result = a.upper()
print(result) # Output: 'THISISASTRING12348S#'
```
### Explanation
The `upper()` function transforms all characters in the string 'ThisIsAString' to uppercase, resulting in 'THISISASTRING'.
### lower()
### Explanation
The `lower()` method converts all characters in a string to lowercase.
### Example
```python
# Example
a = 'ThisIsAString'
result = a.lower()
print(result) # Output: 'thisisastring'
# Example 2
a = 'ThisIsAString12348$#'
result = a.lower()
print(result) # Output: 'thisisastring12348$#'
```
### Explanation
The `lower()` function transforms all characters in the string 'ThisIsAString' to lowercase, resulting in 'thisisastring'.
### isupper()
### Explanation
The `isupper()` method checks if all characters in a string are uppercase.
### Example
```python
# Example
a = 'AbC1234sg'
result = a.isupper()
print(result) # Output: False
# Example 2
a = 'ABC1234SG'
result = a.isupper()
print(result) # Output: True
```
### Explanation
The `isupper()` function returns `False` because not all characters in the string 'AbC1234sg' are uppercase. Numbers and special characters are ignored.
### islower()
### Explanation
The `islower()` method checks if all characters in a string are lowercase, ignoring numbers and special characters.
### Example
```python
# Example 1
a = 'abc1234$#'
result = a.islower()
print(result) # Output: True
# Example 2
a = 'ABC1234$#'
result = a.islower()
print(result) # Output: False
```
### Explanation
The `islower()` function returns `True` because all characters in the string 'abc1234$#' are lowercase.
### isalpha()
### Explanation
The `isalpha()` method checks if all characters in a string are alphabetic.
### Example
```python
# Example
a = 'Scaler Academy'
result = a.isalpha()
print(result) # Output: False
# Example
a = 'Scal3rAcademY'
result = a.isalpha()
print(result) # Output: False
```
### Explanation
The `isalpha()` function returns `False` because the string 'Scaler Academy' contains spaces and is not purely alphabetic. The next example has a number in between and hence is not alphabetic.
### isdigit()
### Explanation
The `isdigit()` method checks if all characters in a string are digits.
### Example
```python
# Example
a = '123'
result = a.isdigit()
print(result) # Output: True
# Example
a = '1a2b3'
result = a.isdigit()
print(result) # Output: False
```
### Explanation
The `isdigit()` function returns `True` because all characters in the string '123' are digits. The next example returns `False` because of the alphabetic characters in the string.
### isalnum()
### Explanation
The `isalnum()` method checks if all characters in a string are alphanumeric.
### Example
```python
# Example
a = 'Abc1234'
result = a.isalnum()
print(result) # Output: True
# Example 2
a = 'Abc12348S#'
result = a.isalnum()
print(result) # Output: False
```
### Explanation
The `isalnum()` function returns `True` because all characters in the string 'Abc1234' are alphanumeric. The second example has special character, `#` and hence returns `False`.
### endswith()
### Explanation
The `endswith()` method checks if a string ends with a specified suffix.
### Example
```python
# Example
a = 'Scaler Academy'
result = a.endswith('Academy')
print(result) # Output: True
# Example 2
a = 'Python Programming'
result = a.endswith('Academy')
print(result) # Output: False
```
### Explanation
The `endswith()` function returns `True` because the string 'Scaler Academy' ends with the specified suffix 'Academy'.
```python
# Program to Count Alphabets and Digits in a String
# User input
s = input()
# Initialize counters
alpha_count = 0
digit_count = 0
# Iterate through each character in the input string
for char in s:
if char.isalpha():
alpha_count += 1
elif char.isdigit():
digit_count += 1
# Print the result
print(f'Alphabet count is {alpha_count} and digit count is {digit_count}')
```
### Explanation
- The program takes user input as a string `s`.
- Two counters (`alpha_count` and `digit_count`) are initialized to keep track of the number of alphabets and digits.
- The program iterates through each character in the input string using a `for` loop.
- For each character, it checks if it is an alphabet using `char.isalpha()` and increments the `alpha_count` accordingly.
- Similarly, if the character is a digit (`char.isdigit()`), the `digit_count` is incremented.
- Finally, the program prints the counts using an f-string.
### Example
**Input:**
```python
Hello123World
```
**Output:**
```plaintext
Alphabet count is 10 and digit count is 3
```
In the input string "Hello123World," there are 10 alphabets (H, e, l, l, o, W, o, r, l, d) and 3 digits (1, 2, 3).
---
### Question
What is the output of the following?
```python
a = [1, 2, 3, 4, 5]
print('|'.join(a))
```
**Choices**
- [ ] 1|2|3|4|5
- [x] Error
- [ ] |1|2|3|4|5|
The `join` method in Python is used to concatenate a list of strings with a specified delimiter. However, in the given code, the list `a` contains integers, not strings. The `join` method expects a list of strings, so attempting to join a list of integers will result in a TypeError.
---
### Question
What is the output of the following?
```python
a = 'Scaler123'
print(a.upper())
```
**Choices**
- [ ] Error
- [ ] Scaler123
- [ ] sCALER123
- [x] SCALER123
The `upper()` method in Python is used to convert all characters in a string to uppercase. In this case, the string 'Scaler123' is assigned to variable `a`, and `a.upper()` is then called, resulting in 'SCALER123' as the output.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.islower())
```
**Choices**
- [x] True
- [ ] False
The output of the given Python code is `True`. The `islower()` method checks if all the characters in the string are lowercase, and in this case, all characters in the string 'scaler123' are lowercase.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.isalpha())
```
**Choices**
- [ ] True
- [x] False
The output of the given Python code is `False`. This is because the `isalpha()` method checks if all the characters in the string are alphabetic (letters) and does not allow for numbers or other characters. In the given string 'scaler123', the presence of '123' makes the method return `False`.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.endswith('ler'))
```
**Choices**
- [ ] True
- [x] False
The output of the given Python code is `False`. This is because the string assigned to variable `a` ('scaler123') does not end with the substring 'ler'. Therefore, the `endswith()` method returns `False`.
---
## List and String Comparison
### List Comparison
List comparison in Python involves comparing two lists element-wise. The comparison starts from the first elements of both lists, and the result is determined based on the comparison of corresponding elements.
### Example 1
```python
[1, 2, 3, 4, 5] < [1, 3]
# Output: True
```
### Explanation
In this example, the comparison evaluates to `True` because the first list is considered "less than" the second list. The comparison is element-wise, and it stops as soon as a pair of elements is found where the first element is less than the second element.
### Example 2
```python
[1, 3, 0] > [1, 3]
# Output: True
```
### Explanation
Here, the comparison evaluates to `True` because the first list is considered "greater than" the second list. Again, the comparison is element-wise, and it stops as soon as a pair of elements is found where the first element is greater than the second element.
### Example 3
```python
[1, 3] == [1, 3]
# Output: True
```
### Explanation
The comparison `[1, 3] == [1, 3]` checks if both lists are equal element-wise. In this case, the result is `True` because every corresponding pair of elements is the same.
### Example 4
```python
[1, 2, 3] > [1, 1000, 2000, 3000]
# Output: True
```
### Explanation
The comparison `[1, 2, 3] > [1, 1000, 2000, 3000]` evaluates to `True` because the first list is considered "greater than" the second list. The comparison is still element-wise, and it stops as soon as a pair of elements is found where the first element is greater than the second element.
### String Comparison
String comparison in Python involves comparing two strings lexicographically, character by character. The comparison is case-sensitive, with uppercase letters considered "less than" their lowercase counterparts. The comparison stops as soon as a pair of characters is found where the condition (e.g., less than, greater than, equal to) is satisfied. The overall result of the string comparison reflects the outcome of these character-wise comparisons.
### Example 1
```python
'A' > 'a'
# Output: False
```
### Explanation
In this example, the comparison `'A' > 'a'` evaluates to `False` because, in the ASCII table, uppercase 'A' has a lower ASCII value than lowercase 'a'.
### Example 2
```python
'Aakar' > 'Sudip'
# Output: False
```
### Explanation
Here, the comparison `'Aakar' > 'Sudip'` evaluates to `False` because, in the lexicographic order, the substring 'Aakar' is considered "less than" the substring 'Sudip'. The comparison stops at the first differing character.
---
## List Comprehension
List comprehension is a concise way to create lists in Python. It offers a more readable and efficient alternative to traditional loops. The syntax involves expressing the creation of a list in a single line.
### Example 1
```python
# Create a list of squares till n-1
n = 5
li = [i ** 2 for i in range(1, n)]
print(li) # Output: [1, 4, 9, 16]
```
This example uses list comprehension to create a list of squares for values from 1 to n-1.
### Example 2
```python
# Create a list of squares for values from 1 to n
n = 5
li = [i ** 2 for i in range(1, n + 1)]
print(li) # Output: [1, 4, 9, 16, 25]
```
Here, the list comprehension creates a list of squares for values from 1 to n.
### Example 3
```python
# Create a list of all even elements
n = 5
li = [i for i in range(1, n * 2) if i % 2 == 0]
print(li) # Output: [2, 4, 6, 8, 10]
```
This example creates a list of all even elements from 1 to n*2 using list comprehension.
### Example 4
```python
# Create a list of tuples (i, j) for values of i and j in the given range
n = 3
li = [(i, j) for i in range(n) for j in range(i)]
print(li) # Output: [(1, 0), (2, 0), (2, 1)]
```
This example creates a list of tuples (i, j) using nested list comprehension. It includes pairs where j is less than i.
---
## Pattern Printing
### Pattern 1: Increasing Rows of Stars
Print the following pattern ?
```python
*
* *
* * *
* * * *
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Code
```python
n = int(input())
for i in range(1, n + 1):
print('*' * i)
```
This code takes an input `n` and uses a loop to print rows of stars. The number of stars in each row increases from 1 to `n`.
### Pattern 2: Right-aligned Triangle
Print the following pattern ?
```python
*
* *
* * *
* * * *
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
To print the given pattern, you can use two nested loops. The outer loop controls the rows, and the inner loop controls the columns. For each row, you need to print spaces followed by asterisks in a specific pattern. Consider the number of spaces needed before each asterisk to achieve the desired right-aligned triangular pattern.
### Code
```python
n = int(input())
for i in range(1, n + 1):
print(' ' * (n - i) + '* ' * i)
```
This code prints a right-aligned triangle of stars. The number of spaces before the stars decreases, and the number of stars in each row increases.
### Pattern 3: Diamond Pattern
Print the following diamond pattern ?
```python
*
***
*****
*******
*********
*******
*****
***
*
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
To print the given diamond pattern, you can follow these steps:
1. Observe the pattern carefully, especially how the number of spaces and stars change in each row.
2. Divide the pattern into two parts: the upper half and the lower half.
3. For the upper half, start with fewer spaces and more stars, incrementing the number of stars in each row.
4. For the lower half, start with fewer spaces and more stars, decrementing the number of stars in each row.
### Code
```python
n = int(input())
m = n // 2
for i in range(1, m + 1):
print(' ' * (m - i) + '*' * (2 * i - 1), sep = '')
for i in range(m, 0, -1):
print(' ' * (m - i) + '*' * (2 * i - 1), sep = '')
```
This code prints a diamond pattern. The first loop prints the upper half, and the second loop prints the lower half of the diamond.

View File

@@ -0,0 +1,684 @@
# Refresher: Tuples + Strings 1
# Introduction to Tuples
### Introduction
We delve into the fundamentals of Tuples and Strings in Python, two powerful data types that play a crucial role in various programming scenarios. Let's start by understanding the essence of Tuples.
## Planets Example
Let's start with an example using an array to store the names of all the planets in our solar system.
```python
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
```
### Adding the Sun
Now, imagine we someone is trying to include the Sun in our list of planets. Since arrays in Python are mutable, someone might be tempted to do this:
```python
planets.append("Sun")
```
However, this is where mutability can lead to errors. While the code above will add "Sun" to the list, it's not accurate to consider the Sun a planet. This illustrates a potential problem with mutable structures when trying to maintain data integrity.
## Tuples
### Definition
Now, let's explore tuples - a different kind of data structure. Tuples are similar to arrays but are immutable. This immutability provides certain advantages, especially in situations where data integrity is crucial.
### Creating Tuples with Numbers
We can create a tuple with numbers like this:
```python
# Definition
a = (1, 2, 3, 4)
print(type(a)) # Output: <class 'tuple'>
# Exception
b = (1,)
print(type(b)) # Output: <class 'tuple'>
c = (1, 2)
print(type(c)) # Output: <class 'tuple'>
d = ()
print(type(d)) # Output: <class 'tuple'>
```
#### Explanation
- In the first example, `a` is a tuple containing the numbers 1 through 4. The `type` function confirms that it's indeed a tuple.
- The second example, `b`, demonstrates the need for a comma even when creating a tuple with a single element. Without the comma, Python interprets it as a different data type.
- The third example, `c`, is a tuple with two elements.
- The fourth example, `d`, is an empty tuple.
### Creating Tuples with the range Keyword
Tuples can also be created using the `range` keyword:
```python
a = tuple(range(10))
print(type(a)) # Output: <class 'tuple'>
print(a) # Output: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
```
#### Explanation
In this example, `a` is a tuple created using the `tuple` constructor with the `range(10)` function, resulting in a tuple with the numbers 0 through 9.
### Tuples in Functions
Consider the following function that swaps the values of two variables:
```python
def swap(a, b):
return b, a
a, b = swap(2, 3)
```
#### Explanation
In this example, the `swap` function takes two parameters `a` and `b`. Then the function creates and returns a tuple. When the function is called with `swap(2, 3)`, it returns a tuple containing the values of `b` and `a`. This tuple is then unpacked into the variables `a` and `b` on the left side of the assignment statement.
After this line executes, `a` will have the value `3`, and `b` will have the value `2`. This is a powerful and elegant way to swap the values of two variables without needing a temporary variable.
### Partially Immutable Tuples
Consider the following example of a partially immutable tuple:
```python
# Partially Immutable
a = (1, 2, 3, ['a', 'b'])
a[3].append('c')
print(a)
```
### Output
The output of this code will be:
```plaintext
(1, 2, 3, ['a', 'b', 'c'])
```
### Explanation
Tuples themselves are immutable, but the elements within them may be mutable. In this case, the list inside the tuple is mutable. The line `a[3].append('c')` accesses the fourth element of the tuple (which is a list) and appends the string 'c' to it. Even though the tuple is partially immutable, the list inside it can be modified.
---
### Question
What will be the output of the following?
```python
t = (1, 2, 3)
t[0] = 4
print(t)
```
**Choices**
- [ ] (4, 2, 3)
- [ ] (1, 2, 3)
- [x] Error
Tuples in Python are immutable, meaning their elements cannot be modified after creation. In the given code, attempting to assign a new value (`4`) to the first element of the tuple (`t[0]`) will result in an error.
---
### Question
What will be the output of the following?
```python
a = 23
t = (a)
print(type(t))
```
**Choices**
- [ ] tuple
- [ ] list
- [ ] str
- [x] int
The code assigns the value 23 to the variable 'a' and then creates a tuple 't' with a single element, which is the value of 'a'. When the type of 't' is printed, it will output 'int' because the tuple contains only one integer element.
---
### Question
What will be the output of the following?
```python
t = (10, 20, 30, 40)
print(t[1:-1])
```
**Choices**
- [ ] 10, 20, 30
- [ ] Nothing
- [ ] 20, 30, 40
- [x] 20, 30
The slice `t[1:-1]` extracts elements from index 1 to one position before the last index (-1) in the tuple `t`, resulting in the elements 20 and 30 being printed.
---
## Strings in Python
## Strings
### String Literals
Strings in Python can be created using single quotes (`'`) or double quotes (`"`). Both forms are equivalent, and you can choose the one that suits your preference. Here's an example:
```python
a = "abc"
b = 'abc'
print(type(a))
print(type(b))
```
### Output
```plaintext
<class 'str'>
<class 'str'>
```
### Explanation
In this example, both `a` and `b` are strings with the content "abc." The `type` function confirms that they are indeed string objects. Python treats single and double quotes as equivalent for defining strings.
### ASCII and Related Functions
ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents each character with a unique number. Python provides `ord` and `chr` functions to work with ASCII values.
```python
print(ord('A'))
print(ord('0'))
print(ord('9'))
print(chr(129))
```
### Output
```plaintext
65
48
57
ü
```
### Explanation
- `ord('A')` returns the ASCII value of the character 'A', which is 65.
- `ord('0')` returns the ASCII value of the digit '0', which is 48.
- `ord('9')` returns the ASCII value of the digit '9', which is 57.
- `chr(129)` returns the character corresponding to the ASCII value 129, which is 'ü'.
These functions are useful for working with character encodings and converting between characters and their ASCII representations. Keep in mind that ASCII values are integers representing characters in the ASCII table.
### Properties of Strings
Strings in Python possess several important properties, including mutability, homogeneity, iterability, and case sensitivity.
```python
# Variable
a = 'Scaler Academy'
```
### Mutability
Strings in Python are **immutable**, meaning their values cannot be changed after creation.
```python
# Attempt to modify a character in the string
a[0] = 's'
```
#### Output
```plaintext
TypeError: 'str' object does not support item assignment
```
#### Explanation
The attempt to modify the first character of the string `a` raises a `TypeError`. This demonstrates the immutability of strings.
### Homogeneity
Strings are **homogeneous**, meaning they can only contain characters of the same type.
```python
# Concatenating string and integer
result = a + 42
```
#### Output
```plaintext
TypeError: can only concatenate str (not "int") to str
```
#### Explanation
Attempting to concatenate a string (`a`) with an integer (`42`) raises a `TypeError`, emphasizing the homogeneity requirement of strings.
### Iterability
Strings are **iterable**, allowing you to loop through each character.
```python
# Iterating through each character
for char in a:
print(char)
```
#### Output
```plaintext
S
c
a
l
e
r
A
c
a
d
e
m
y
```
#### Explanation
The `for` loop iterates through each character in the string `a`, printing them one by one.
### Case Sensitivity
Strings are **case-sensitive**, distinguishing between uppercase and lowercase characters.
```python
# Comparing strings
b = 'scaler academy'
print(a == b)
```
#### Output
```plaintext
False
```
#### Explanation
The comparison between `a` and `b` returns `False` because of case sensitivity. The uppercase 'S' in `a` is not equal to the lowercase 's' in `b`.
---
### Question
Which one of the following is a valid string?
**Choices**
- [ ] "ScaLer#'
- [ ] %adfa"
- [x] "^&abc#"
- [ ] 'academy'
The correct answer is "^&abc#". This is a valid string because it is enclosed in double quotation marks, and its contents consist of a combination of letters, numbers, and symbols.
---
### Question
What will be the output of the following?
```python
print(ord('c'))
```
**Choices**
- [ ] 98
- [x] 99
- [ ] 100
- [ ] 101
The correct answer is 99. The `ord` function in Python returns the Unicode code point of a given character. In this case, it prints the Unicode code point of the character 'c', which is 99.
---
### Question
What will be the output of the following?
```python
print(chr(70))
```
**Choices**
- [ ] C
- [ ] E
- [x] F
- [ ] G
The `chr()` function in Python returns a string representing a character whose Unicode code point is the integer passed to it. In this case, `chr(70)` returns the character with Unicode code point 70, which is 'F'.
---
### Question
What will be the output of the following?
```python
s = 'Scaler Academy'
print(s[0:5])
```
**Choices**
- [ ] Sae
- [ ] Scaler
- [x] Scale
- [ ] cale
The code `s[0:5]` extracts the substring from index 0 to 4 (5 exclusive) from the string 'Scaler Academy', resulting in the output 'Scale'.
---
### Question
What will be the output of the following?
```python
a = '1'
b = '2'
c = a + b
print(c)
```
**Choices**
- [ ] 3
- [ ] '3'
- [x] 12
- [ ] 1 2
The correct answer is: 12
In Python, when you use the `+` operator with two strings, it concatenates them. So, `a + b` where `a` is '1' and `b` is '2' results in the string '12', and that is what will be printed.
---
### Question
What will be the output of the following?
```python
a = 'abcd'
a += 'e'
print(len(a))
```
**Choices**
- [ ] 3
- [ ] 4
- [x] 5
- [ ] 6
The code initializes a string variable 'a' with the value 'abcd', then concatenates 'e' to it using the `+=` operator. Finally, it prints the length of the modified string 'a', which is now 'abcde'. The length of 'abcde' is 5, so the output is 5.
---
## Functions in Strings
### capitalize()
The `capitalize()` method in Python is used to capitalize the first letter of a string.
```python
# Example
'john doe'.capitalize()
```
### Output
```plaintext
'John doe'
```
### Explanation
In this example, the `capitalize()` function capitalizes the first letter of the string, transforming 'john doe' into 'John doe'.
### title()
The `title()` method capitalizes the first letter of each word in a string.
```python
# Example
'sneha sudam'.title()
```
### Output
```plaintext
'Sneha Sudam'
```
### Explanation
The `title()` function capitalizes the first letter of each word in the string, resulting in 'Sneha Sudam'.
### count(substring)
The `count(substring)` method counts the occurrences of a substring in the string.
```python
# Example
'pooja nikam'.count('ni')
```
### Output
```plaintext
2
```
### Explanation
The `count()` function counts the occurrences of the substring 'ni' in the string, returning the value `2`.
### replace(old, new)
The `replace(old, new)` method replaces occurrences of the old substring with the new substring.
```python
# Example
'Vicky Sharma'.replace('a', 'e')
```
### Output
```plaintext
'Vicky Sherme'
```
### Explanation
The `replace()` function replaces occurrences of 'a' with 'e' in the string, resulting in 'Vicky Sherme'.
### replace(old, new, count)
The `replace(old, new, count)` method replaces a specified number of occurrences of the old substring with the new substring.
```python
# Example
'Vicky Sharma'.replace('a', 'e', 1)
```
### Output
```plaintext
'Vicky Sherma'
```
### Explanation
In this example, only the first occurrence of 'a' is replaced with 'e' in the string, resulting in 'Vicky Sherma'.
### split(separator)
The `split(separator)` method splits a string into a list of substrings based on the specified separator.
```python
# Example
a = 'Aakar, Saurav, Kusum'
print(a.split(','))
```
### Output
```plaintext
['Aakar', ' Saurav', ' Kusum']
```
### Explanation
The `split()` function divides the string into a list of substrings based on the specified separator (`,` in this case), resulting in `['Aakar', ' Saurav', ' Kusum']`.
```python
# Example
a = 'There——are—-many-—places——to——visit.'
print(a.split('——'))
```
### Output
```plaintext
['There', 'are', 'many', 'places', 'to', 'visit.']
```
### Explanation
The `split()` function divides the string using the specified separator (`'——'` in this case), resulting in `['There', 'are', 'many', 'places', 'to', 'visit.']`.
### Print ASCII Letter
This example takes user input and prints the ASCII values of each letter in the input string.
```python
# Example
s = input()
for char in s:
print(ord(char), end=' ')
```
### Output (for input 'hello')
```plaintext
104 101 108 108 111
```
### Explanation
The `ord()` function is used to get the ASCII value of each character in the input string. The `end=' '` parameter ensures that the values are printed with a space in between.
### Formatted Strings
Formatted strings in Python provide a convenient way to embed variable values or expressions into a string, making it more readable and flexible.
```python
# Example
name = 'Aakar'
gender = 'Mate'
age = 25
print('Name:—', name, 'gender:—', gender, 'age:—', age)
```
### Output
```plaintext
Name:— Aakar gender:— Mate age:— 25
```
### Explanation
In this example, a formatted string is created using the variables `name`, `gender`, and `age`, resulting in the output `Name:— Aakar gender:— Mate age:— 25`.
There are several ways to achieve string formatting in Python, but one commonly used method involves the `format()` method.
```python
# Example
template = 'Name:— {}, gender:— {}, age:— {}'
print(template.format(name, gender, age))
```
### Output
```plaintext
Name:— Aakar, gender:— Mate, age:— 25
```
### Explanation
The `format()` method is used to insert the values of `name`, `gender`, and `age` into the string template, resulting in the formatted output `Name:— Aakar, gender:— Mate, age:— 25`.
```python
# Example
template = 'Name:— {0}, gender:— {1}, age:— {2}'
print(template.format(name, gender, age))
```
### Output
```plaintext
Name:— Aakar, gender:— Mate, age:— 25
```
### Explanation
In this example, positional placeholders `{0}`, `{1}`, and `{2}` are used in the template to indicate the positions of `name`, `gender`, and `age` in the `format()` method. The output is the same as the previous example.
---
### Question
What will be the output of the following?
```python
a = 'Scaler Academy'
print(a.count('a'))
```
**Choices**
- [x] 2
- [ ] 3
- [ ] 4
- [ ] 0
The output of the given Python code will be 2. This is because the `count()` method is used to count the number of occurrences of a specified substring (in this case, the letter 'a') within the given string 'Scaler Academy'.
---
### Question
What will be the output of the following?
```python
a = 'i-am-awesome'
b = a.split('-')
print(len(b))
```
**Choices**
- [ ] 2
- [x] 3
- [ ] 4
- [ ] 5
The correct answer is 3. The code splits the string 'i-am-awesome' at each occurrence of the hyphen ('-') and creates a list `b` with three elements: ['i', 'am', 'awesome']. The `len(b)` then outputs 3, indicating the number of elements in the list.