Data Structures and Algorithms in Python Slides
Data Structures and Algorithms in Python Slides
www.appmillers.com
Elshad Karimov
Elshad Karimov
@karimov_elshad
in/elshad-karimov
Elshad Karimov
@karimov_elshad
in/elshad-karimov
What are Data Structures?
AppMillers
www.appmillers.com
ff
ff
What are Data Structures?
AppMillers
www.appmillers.com
ff
ff
What are Data Structures?
AppMillers
www.appmillers.com
ff
ff
What is an Algorithm?
• Set of steps to accomplish a task
Step 5: Trim door casing Step 4: Determine the layout Step 3: Prepare sub ooring
AppMillers
www.appmillers.com
fl
fl
Algorithms in our daily lives
Step 3: Go to o ce
AppMillers
www.appmillers.com
ffi
Algorithms in our daily lives
Step 1 : Go to Starbucks
Step 3: Take a co ee
AppMillers
www.appmillers.com
ff
Algorithms in Computer Science
• Set of rules for a computer program to accomplish a task
Input Data
Calculation
AppMillers
www.appmillers.com
Sample algorithms that are used by big companies
• How do Google and Facebook transmit live video across the internet?
Compression algorithms
AppMillers
www.appmillers.com
Sample algorithms that are used by big companies
Compression algorithms
AppMillers
www.appmillers.com
fi
Sample algorithms that are used by big companies
Dijkstra’s algorithm
min min
B∞
Bv2
Bv 3 E∞
Ev5
Ev
2 1 4 9
min
A
Av0 6 D∞
Dv3
Dv G∞
Gv14
Gv
5 7
C∞
Cv5
Cv 8 F13
∞
Fv13
Fv
min min AppMillers
www.appmillers.com
fi
Sample algorithms that are used by big companies
AppMillers
www.appmillers.com
What makes a good algorithm?
1. Correctness
2. E ciency
AppMillers
www.appmillers.com
ffi
Why are Data Structures and Algorithms important?
AppMillers
www.appmillers.com
Why are Data Structures and Algorithms important?
Input data
Da
Output ta
Str
uc
tur
es
an
dA
lgo
rith
Processing
ms
AppMillers
www.appmillers.com
Why are Data Structures and Algorithms important?
Algorithms
COMPUTER SCIENCE
ALGORITHMS
Algorithms
AppMillers
www.appmillers.com
Why are Data Structures and Algorithms important?
AppMillers
www.appmillers.com
Why are Data Structures and Algorithms in INTERVIEWS?
AppMillers
www.appmillers.com
Types of Data Structures
Data Structures
Integer
Character Tree
Boolean
Array Linked List
Stack
Queue
AppMillers
www.appmillers.com
Primitive Data Structures
AppMillers
www.appmillers.com
Types of Algorithms
AppMillers
www.appmillers.com
Types of Algorithms
AppMillers
www.appmillers.com
Types of Algorithms
- Divide the problem into smaller subproblems of the same type, and solve these subproblems recursively
- Combine the solutions to the subproblems into a solution to the original problem
AppMillers
www.appmillers.com
Types of Algorithms
Greedy algorithms
- We hope that by choosing a local optimum solution at each step, we will end up at a global optimum solution
AppMillers
www.appmillers.com
Types of Algorithms
Randomized algorithms
- Use a random number at least once during the computation to make a decision
AppMillers
www.appmillers.com
What is Recursion?
Recursion = a way of solving a problem by having a function calling itself
AppMillers
www.appmillers.com
What is Recursion?
Recursion = a way of solving a problem by having a function calling itself
A programmer's wife tells him as he leaves the house: "While you're out, buy some milk."
He never returns home and the universe runs out of milk. 🤣 🤣 🤣 AppMillers
www.appmillers.com
ff
fi
What is Recursion?
Recursion = a way of solving a problem by having a function calling itself
def openRussianDoll(doll):
if doll == 1:
print("All dolls are opened")
else:
openRussianDoll(doll-1)
AppMillers
www.appmillers.com
Why Recursion?
1. Recursive thinking is really important in programming and it helps you break down big
problems into smaller ones and easier to use
- when to choose recursion?
‣ If you can divine the problem into similar sub problems
‣ Design an algorithm to compute nth…
‣ Write code to list the n…
‣ Implement a method to compute all.
‣ Practice
2. The prominent usage of recursion in data structures like trees and graphs.
3. Interviews
4. It is used in many algorithms (divide and conquer, greedy and dynamic programming)
AppMillers
www.appmillers.com
How Recursion works?
def recursionMethod(parameters):
if exit from condition satisfied:
return some value
else:
recursionMethod(modified parameters)
AppMillers
www.appmillers.com
fi
def firstMethod():
secondMethod()
print("I am the first Method")
def secondMethod():
thirdMethod()
print("I am the second Method")
def thirdMethod():
fourthMethod()
thirdMethod()
print("I am the third Method")
secondMethod()
def fourthMethod():
print("I am the fourth Method") rstMethod()
STACK Memory
AppMillers
www.appmillers.com
fi
def recursiveMethod(n):
if n<1:
print("n is less than 1") recursiveMethod(1)
else:
recursiveMethod(n-1) recursiveMethod(2)
print(n)
recursiveMethod(3)
recursiveMethod(4)
recursiveMethod(4) 4
recursiveMethod(3) 3
STACK Memory
recursiveMethod(2) 2
recursiveMethod(1) 1
recursiveMethod(0) n is less than 1
AppMillers
www.appmillers.com
Time efficient? No Yes In case of recursion system needs more time for pop
and push elements to stack memory which makes
recursion less time efficient
AppMillers
www.appmillers.com
- When we are ne with extra overhead (both time and space) that comes with it
1 4
When avoid it?
- Recursion uses more memory. If we use embedded memory. For example an application
that takes more memory in the phone is not e cient
AppMillers
www.appmillers.com
fi
ffi
ffi
How to write recursion in 3 steps?
Factorial
Example 1
4! = 4*3*2*1=24
Example 2
10! = 10*9*8*7*6*5*4*3*2*1=36,28,800
n! = n*(n-1)*(n-2)*…*2*1
AppMillers
www.appmillers.com
How to write recursion in 3 steps?
(n-1)!
0! = 1
1! = 1
factorial(-1) ??
factorial(1.5) ??
AppMillers
www.appmillers.com
fl
How to write recursion in 3 steps?
def factorial(n):
assert n >= 0 and int(n) == n, 'The number must be positive integer only!'
if n in [0,1]:
return 1
else:
return n * factorial(n-1)
factorial(4) = 24
factorial(4) 6
4 * factorial(3) 2
3 * factorial(2)
2 * factorial(1)
AppMillers
www.appmillers.com
bonacci(-1) ??
bonacci(1.5) ??
AppMillers
www.appmillers.com
fi
fi
fl
Fibonacci numbers - Recursion
def fibonacci(n):
assert n >=0 and int(n) == n , 'Fibonacci number cannot be negative number or non integer.'
if n in [0,1]:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
bonacci(4) =3 2 1
bonacci(3) + bonacci(2) 1 0
bonacci(1) + bonacci(0)
1 1
bonacci(2) + bonacci(1)
1 0
bonacci(1) + bonacci(0)
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
Interview Questions - 1
How to nd the sum of digits of a positive integer number using recursion ?
sumofDigits(-11) ??
sumofDigits(1.5) ??
AppMillers
www.appmillers.com
fi
fl
Interview Questions - 2
How to calculate power of a number using recursion?
xn=x*x*x*..(n times)..*x
24=2*2*2*2 xn = n * xn-1
xa * xb=xa+b
x3 * x4=x3+4
AppMillers
www.appmillers.com
fl
Interview Questions - 3
How to nd GCD ( Greatest Common Divisor) of two numbers using recursion?
GCD is the largest positive integer that divides the numbers without a remainder
b=0
Positive integers
Convert negative numbers to positive
AppMillers
www.appmillers.com
fi
fl
Interview Questions - 4
How to convert a number from Decimal to Binary using recursion
13 to binary
10 1010
1101 f(n) = n mod 2 + 10 * f(n/2)
1/2 0 1 1 * 10 + 0 = 10
AppMillers
www.appmillers.com
fl
Dynamic programing & Memoization
900 850
AppMillers
www.appmillers.com
Dynamic programing & Memoization
static int bonacci(int i) {
if (i == 0) return 0;
if (i == 1) return 0;
return bonacci(i-1)+ bonacci(i-2);
b(5)
}
b(4) b(3)
b(1) b(0)
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Dynamic programing & Memoization
static int b(int n)
{
/* Declare an array to store
Fibonacci numbers. */ b(5)
int f[] = new int[n+2]; // 1 extra
to handle case, n = 0
int i;
/* 0th and 1st number of the b(4) b(3)
series are 0 and 1*/
f[0] = 0;
f[1] = 1; b(3) b(2)
for (i = 2; i <= n; i++)
{
/* Add the previous 2 numbers b(2) b(1)
in the series
and store it */
f[i] = f[i-1] + f[i-2];
}
b(1) b(0)
return f[n];
}
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Big O
Big O is the language and metric we use to describe the e ciency of algorithms
Size : 1TB
AppMillers
www.appmillers.com
ffi
Electronic - O(s)
Physical - O(1)
Types
AppMillers
www.appmillers.com
w
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
Algorithm run time notations
AppMillers
www.appmillers.com
ffi
Algorithm run time notations
- Best case
- Average case
- Worst case
AppMillers
www.appmillers.com
Algorithm run time notations
O(N)
AppMillers
www.appmillers.com
Big O, Big Theta and Big Omega
• Big - Ω (Big-Omega) : It is a complexity that is going to be at least more than the best
case.
• Big Theta (Big - Θ) : It is a complexity that is within bounds of the worst and the best
cases.
n
5 4 10 … 8 11 68 87 12 … 90 13 77 55 9
Big O - O(N)
Big Ω - Ω(1)
Big Θ - Θ(n/2)
AppMillers
www.appmillers.com
array = [1, 2, 3, 4, 5]
array[0] // It takes constant time to access first element
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
fi
Algorithm run time complexities
Complexity Name Sample
O(1) Constant Accessing a speci c element in array
O(N) Linear Loop through array elements
O(LogN) Logarithmic Find an element in sorted array
O(N2) Quadratic Looking ar a every index in the array twice
O(2N) Exponential Double recursion in Fibonacci
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
fi
fi
Algorithm run time complexities
Complexity Name Sample
O(1) Constant Accessing a speci c element in array
O(N) Linear Loop through array elements
O(LogN) Logarithmic Find an element in sorted array
O(N2) Quadratic Looking ar a every index in the array twice
O(2N) Exponential Double recursion in Fibonacci
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
fi
Algorithm run time complexities
Complexity Name Sample
O(1) Constant Accessing a speci c element in array
O(N) Linear Loop through array elements
O(LogN) Logarithmic Find an element in sorted array
O(N2) Quadratic Looking ar a every index in the array twice
O(2N) Exponential Double recursion in Fibonacci
AppMillers
www.appmillers.com
fi
for x in array:
for y in array:
print(x,y)
AppMillers
www.appmillers.com
fi
for x in array:
for y in array:
print(x,y)
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
fi
Algorithm run time complexities
Complexity Name Sample
O(1) Constant Accessing a speci c element in array
O(N) Linear Loop through array elements
O(LogN) Logarithmic Find an element in sorted array
O(N2) Quadratic Looking ar a every index in the array twice
O(2N) Exponential Double recursion in Fibonacci
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
Space complexity
O(n) O(n2)
AppMillers
www.appmillers.com
Space complexity - example
def sum(n):
if n <= 0:
return 0
else:
return n + sum(n-1)
1 sum(3)
2 → sum(2) Space complexity : O(n)
3 → sum(1)
4 → sum(0)
AppMillers
www.appmillers.com
Space complexity - example
def pairSumSequence(n):
sum = 0
for i in range(0,n+1):
sum = sum + pairSum(i, i+1)
Space complexity : O(1)
return sum
def pairSum(a,b):
return a + b
AppMillers
www.appmillers.com
Space complexity - example
Java Python
static int sum(int n) { def sum(n):
if (n <= 0) { if n <= 0:
return 0; return 0
} else:
return n + sum(n-1); return n + sum(n-1)
}
Javascript Swift
function sum(n) {
func sum(n: Int) -> Int {
if (n <= 0) {
if n <= 0 {
return 0;
return 0
}
}
return n + sum(n-1);
return n + sum(n: n-1)
} }
AppMillers
www.appmillers.com
Drop Constants and Non Dominant Terms
Drop Constant
O(2N) O(N)
O(N2+N) O(N2)
O(N+logN) O(N)
O(2*2N+1000N100) O(2N)
AppMillers
www.appmillers.com
Why do we drop constants and non dominant terms?
- It is very possible that O(N) code is faster than O(1) code for specific inputs
- Different computers with different architectures have different constant factors.
- Different algorithms with the same basic idea and computational complexity might have slightly
different constants
AppMillers
www.appmillers.com
𝑛
Add vs Multiply
- If your algorithm is in the form “do this, then when you are all done, do that” then you add the runtimes.
- If your algorithm is in the form “do this for each time you do that” then you multiply the runtimes.
AppMillers
www.appmillers.com
Any assignment statements and if statements that are executed once regardless of the size
Rule 1 of the problem O(1)
Rule 3 A nested loop of the same type takes quadratic time complexity O(n2)
sampleArray 5 4 10 … 8 11 68 87 …
def findBiggestNumber(sampleArray):
biggestNumber = sampleArray[0] O(1)
} }
for index in range(1,len(sampleArray)): O(n)
if sampleArray[index] > biggestNumber: O(1) O(n)
biggestNumber = sampleArray[index] O(1)
O(1)
print(biggestNumber) O(1)
Explanation:
A= 11 4 12 7 n=4
AppMillers
findMaxNumRec(A,1) A[0]=11 www.appmillers.com
}
M(n)=O(1)+M(n-1)
M(n)=1+M(n-1)
M(1)=O(1) =1+(1+M((n-1)-1))
=2+M(n-2)
M(n-1)=O(1)+M((n-1)-1) =2+1+M((n-2)-1)
M(n-2)=O(1)+M((n-2)-1) =3+M(n-3)
.
.
=a+M(n-a)
=n-1+M(n-(n-1))
=n-1+1
=n
AppMillers
www.appmillers.com
def f(n):
if n <= 1:
return 1
return f(n-1) + f(n-1)
AppMillers
www.appmillers.com
Level
f(4) 0
f(3) f(3) 1
4 0 1 20 O(branchesdepth)
3 1 2 2 * previous level = 2 21
AppMillers
2 2 4 2 * previous level = 2 *21=22 22 www.appmillers.com
AppMillers
www.appmillers.com
Top 10 Big O interview Questions
in Java 😞
Java to Python 😉
AppMillers
www.appmillers.com
Interview Questions - 1
What is the runtime of the below code?
def foo(array):
sum = 0 O(1)
product = 1 O(1)
for i in array: O(n)
sum += i O(1)
for i in array: O(n)
product *= i O(1)
print("Sum = "+str(sum)+", Product = "+str(product)) O(1)
AppMillers
www.appmillers.com
Interview Questions - 2
What is the runtime of the below code?
def printPairs(array):
for i in array:
for j in array:
print(str(i)+","+str(j))
}
O(n2)
O(n)
O(1)
O(n2)
AppMillers
www.appmillers.com
Interview Questions - 3
What is the runtime of the below code?
def printUnorderedPairs(array):
for i in range(0,len(array)):
for j in range(i+1,len(array)):
print(array[i] + "," + array[j])
}
.
1 1st 10
2nd 9
(n-1)+(n-2)+(n-3)+..+2+1 . =5 10/2
.
n n/2
=1+2+…+(n-3)+(n-2)+(n-1) 1
=n(n-1)/2
=n2/2 + n n*n/2 = n2/2 O(N2)
=n2
AppMillers
www.appmillers.com
Interview Question - 4
What is the runtime of the below code?
b = len(arrayB)
a = len(arrayA)
AppMillers
www.appmillers.com
Interview Question - 5
What is the runtime of the below code?
a = len(arrayA)
b = len(arrayB)
AppMillers
www.appmillers.com
Interview Question - 6
What is the runtime of the below code?
def reverse(array):
for i in range(0, int(len(array)/2)): O(N/2) O(N)
other = len(array)-i-1 O(1)
temp = array[i] O(1)
array[i] = array[other] O(1)
array[other] = temp O(1)
print(array) O(1)
input output
1 2 3 4 5 5 4 3 2 1
AppMillers
www.appmillers.com
Interview Questions - 7
Which of the following are equivalent to O(N)? Why?
AppMillers
www.appmillers.com
Interview Question - 8
What is the runtime of the below code?
M(n-1)
n! = 1*2*3*…*n
M(n)=1+M(n-1)
3! = 1*2*3=6
=1+(1+M((n-1)-1))
}
M(n)=O(1)+M(n-1)
=2+M(n-2)
M(0)=O(1) =2+1+M((n-2)-1)
=3+M(n-3)
M(n-1)=O(1)+M((n-1)-1) .
.
M(n-2)=O(1)+M((n-2)-1) =a+M(n-a) Time Complexity : O(N)
=n+M(n-n)
=n+1
=n
AppMillers
www.appmillers.com
Interview Question - 9
What is the runtime of the below code?
def allFib(n):
for i in range(n):
print(str(i)+":, " + str(fib(i)))
def fib(n):
if n <= 0:
return 0 branchesdepth O(2N)
elif n == 1:
return 1
return fib(n-1) + fib(n-2)
b(1) 21 steps
b(2) 22 steps
b(3) 23 steps
Total work = 21+22+23+24+…+2n
b(4) 24 steps
= 2n+1-2
…
b(n) 2n steps
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
Interview Question - 10
What is the runtime of the below code?
def powersOf2(n):
}
if n < 1:
return 0
elif n == 1: O(1)
print(1)
return 1
else:
prev = powersOf2(int(n/2))
}
curr = prev*2
print(curr)
O(1)
return curr
n=50
powersOf(50) return 32
Time Complexity : O(logN)
powersOf(25) return 16
powersOf(12) return 8
powersOf(6) return 4
powersOf(3) return 2 x2
powersOf(1) return 1
AppMillers
www.appmillers.com
Arrays
AppMillers
www.appmillers.com
Arrays
- It is a box of macaroons.
- All macaroons in this box are next to each other
- Each macaroon can be identi ed uniquely based on their location
- The size of box cannot be changed
“a”
4 3 1 6 8 10
[0] [1] [2] [3] [4] [5]
AppMillers
www.appmillers.com
fi
fi
fi
fi
What is an Array?
In computer science, an array is a data structure consisting of a collection of elements , each
identi ed by at least one array index or key. An array is stored such that the position of each
element can be computed from its index by a mathematical formula.
4 3 1 6 8 10
[0] [1] [2] [3] [4] [5]
AppMillers
www.appmillers.com
fi
Types of Array
Arrays
Two dimensional
Three dimensional
Four dimensional
.
.
.
N dimensional
AppMillers
www.appmillers.com
Types of Array
One dimensional array : an array with a bunch of values having been declared with a single index.
5 4 10 11 8 11 68 87 12
[0] [1] [2] [3] [4] [5] [6] [7] [8]
Two dimensional array : an array with a bunch of values having been declared with double index.
AppMillers
www.appmillers.com
Types of Array
One dimensional array :
5 4 10 11 8 11 68 87 12
1 33 55 91 20 51 62 74 13
5 4 10 11 8 11 68 87 12
24 50 37 40 48 30 59 81 93
AppMillers
www.appmillers.com
Arrays in Memory
One Dimensional
5 4 10 11 8 11 68 87 12
Memory
5 4 10 11 8 11 68 87 12
AppMillers
www.appmillers.com
Arrays in Memory
Two Dimensional array
1 2 3
4 5 6
7 8 9
Memory
Row 1 Row 3
1 2 3 4 5 6 7 8 9
Row 2
AppMillers
www.appmillers.com
Arrays in Memory
[[[ 0, 1, 2],
[ 3, 4, 5]],
Three Dimensional array
[[ 6, 7, 8],
[ 9, 10, 11]],
Memory
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
AppMillers
www.appmillers.com
What is an Array?
I’m an
Array
AppMillers
www.appmillers.com
What is an Array?
0 1 2 3 4 5
Not allowed
AppMillers
www.appmillers.com
Creating an array
myArray =
myArray = 1 2 3
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
Insertion
myArray[3] = “d”
myArray[5] = “f”
AppMillers
www.appmillers.com
Insertion
“f”
AppMillers
www.appmillers.com
Insertion
“f”
“a”
[0]
“b”
[1]
“c”
[2]
“d”
[3]
“e”
[4]
💥
“h”
[5]
FULL❗
AppMillers
www.appmillers.com
Insertion , when an array is full.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
AppMillers
www.appmillers.com
Array traversal
myArray[0] = “a”
myArray[1] = “b”
myArray[2] = “c”
myArray[3] = “d”
myArray[4] = “e”
myArray[5] = “f”
AppMillers
www.appmillers.com
Array traversal
def traverseArray(array):
for i in array:
print(i) }
O(n)
O(1)
O(n)
AppMillers
www.appmillers.com
For example:
myArray[0] = “a”
myArray[3] = “d”
AppMillers
www.appmillers.com
Access array element
How can we tell the computer which particular value we would like to access?
INDEX
<arrayName>[index]
AppMillers
www.appmillers.com
Access an element of array
def accessElement(array, index):
}
if index >= len(array): O(1)
print('There is not any element in this index') O(1)
O(1)
else:
print(array[index]) O(1)
AppMillers
www.appmillers.com
Finding an element
myArray[2]
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Finding an element
AppMillers
www.appmillers.com
Finding an element
def searchInArray(array, value):
}
for i in array: O(n)
if i == value: O(1)
O(n) O(n^2)
return arr.index(value)
return "The element does not exist in this array" O(1)
}
O(n)
O(1)
O(n)
O(1)
O(1)
AppMillers
www.appmillers.com
Deletion
❌
“a” “b” “c” “d” “e” “h”
[0] [1] [2] [3] [4] [5]
Not allowed‼
🚫
“a” “c” “d” “e” “h”
[0] [1] [2] [3] [4] [5]
AppMillers
www.appmillers.com
Deletion
❌
“a” “b” “c” “d” “e” “h”
[0] [1] [2] [3] [4] [5]
AppMillers
www.appmillers.com
Deletion
❌
“a” “b” “c” “d” “e” “h”
[0] [1] [2] [3] [4] [5]
AppMillers
www.appmillers.com
Inserting a value to two dimensional array
AppMillers
www.appmillers.com
Array type codes in Python
AppMillers
www.appmillers.com
Time and Space Complexity in One Dimensional Arrays
AppMillers
www.appmillers.com
Two Dimensional Array
An array with a bunch of values having been declared with double index.
1 33 55 91 20 51 62 74 13
5 4 10 11 8 11 68 87 12
24 50 37 40 48 30 59 81 93
AppMillers
www.appmillers.com
1 10 11 15
5 4 10 ?
24 50 37 ?
Adding Column
3 1 10 11 3 1 10 11
6 5 4 10 6 5 4 10
9 24 50 37 9 24 50 37
AppMillers
www.appmillers.com
Insertion - Two Dimensional array
1 10 11 15
5 4 10 ?
24 50 37 ?
Adding Row
3 6 9 1 10 11 3 6 9
5 4 10 1 10 11
24 50 37 5 4 10
24 50 37
AppMillers
www.appmillers.com
Access an element of Two Dimensional Array
One dimensional array
5 4 10 11 8 11 68 87 12
[0] [1] [2] [3] [4] [5] [6] [7] [8]
a[0][4] a[2][5]
[0] [1] [2] [3] [4] [5] [6] [7] [8]
[0] 1 33 55 91 20 51 62 74 13
[1] 5 4 10 11 8 11 68 87 12
[2] 24 50 37 40 48 30 59 81 93
AppMillers
www.appmillers.com
Traversing Two Dimensional Array
1 33 55 91
5 4 10 11
24 50 37 40
1 33 55 91
5 4 10 11
24 50 37 40
AppMillers
www.appmillers.com
Traversing Two Dimensional Array
1 33 55 91
5 4 44 11
24 50 37 40
AppMillers
www.appmillers.com
Deletion - Two Dimensional array
1 10 11
5 4 10
24 50 37
Deleting Column
1
❌1 10 11 10 11
5 5 4 10 4 10
24 24 50 37 50 37
AppMillers
www.appmillers.com
Deletion - Two Dimensional array
1 10 11
5 4 10
24 50 37
Deleting Row
1 10 11
❌1 10 11
5 4 10
5 4 10
24 50 37
24 50 37
AppMillers
www.appmillers.com
Time and Space Complexity in 2D Arrays
AppMillers
www.appmillers.com
When to use/avoid Arrays
When to use
- To store multiple variables of same data type
- Random access
When to avoid
- Reserve memory
AppMillers
www.appmillers.com
Summary
• Indices start at 0
• Inserting elements
• Removing elements.
• Finding elements
AppMillers
www.appmillers.com
Python Lists
A list is a data structure that holds an ordered collection of items.
Elements or items
AppMillers
www.appmillers.com
fl
fl
Arrays vs Lists
Similarities
[10, 20, 30, 40]
Di erences
[10, 20, 30, 40]
AppMillers
www.appmillers.com
ff
Time and Space Complexity in Python Lists
AppMillers
www.appmillers.com
Array / List Project
AppMillers
www.appmillers.com
Find Number of Days Above Average Temperature
Output
Average = 1.5
1 day(s) above average
AppMillers
www.appmillers.com
Write a program to find all pairs of integers whose sum is equal to a given number.
AppMillers
www.appmillers.com
Array/List Interview Questions - 2
Write a program to find all pairs of integers whose sum is equal to a given number.
AppMillers
www.appmillers.com
1 2 3
Rotate 90 degrees
4 5 6
7 8 9
AppMillers
www.appmillers.com
Array/List Interview Questions -7
Rotate Matrix - Given an image represented by an NxN matrix write a method to rotate
the image by 90 degrees.
1 2 3 7 2 1 7 4 1
4 5 6 4 5 6 8 5 2
7 8 9 9 8 3 9 6 3
for i = 0 to n
temp = top[i]
top[i] = left[i]
left[i] = bottom[i]
bottom[i] = right[i]
right[i] = temp
AppMillers
www.appmillers.com
Dictionaries
A dictionary is a collection which is unordered, changeable and indexed.
Key Value
0 1 2
myArray = “Miller” “Programmer” “App Miller”
myArray[0] Miller
AppMillers
www.appmillers.com
Dictionaries
AppMillers
www.appmillers.com
Dictionaries
0 1 2
AppMillers
www.appmillers.com
Dictionaries
Value
AppMillers
www.appmillers.com
Dictionary in Memory
A hash table is a way of doing key-value lookups. You store the values in an array, and then use a
hash function to nd the index of the array cell that corresponds to your key-value pair.
AppMillers
www.appmillers.com
fi
Dictionary in Memory
3 one uno
4
AppMillers
www.appmillers.com
Dictionary in Memory
1 two dos
3 one uno
4
AppMillers
www.appmillers.com
Dictionary in Memory
1 two dos
3 one uno
4 three tres
AppMillers
www.appmillers.com
Dictionary in Memory
3 one uno
4 three tres
AppMillers
www.appmillers.com
Dictionary all method
AppMillers
www.appmillers.com
Dictionary any method
AppMillers
www.appmillers.com
Dictionary vs List
Dictionary List
Unordered Ordered
Preferred when you have unique key values Preferred when you have ordered data
AppMillers
www.appmillers.com
Time and Space Complexity in Python Dictionary
AppMillers
www.appmillers.com
Tuples
- What is a tuple? How can we create it ?
- Tuples in Memory
- Accessing an element of Tuple
- Traversing / Slicing a Tuple
- Search for an element in Tuple
- Tuple Operations/Functions
- Tuple vs List
- Tuple vs Dictionary
- Time and Space complexity of Tuples
AppMillers
www.appmillers.com
What is a Tuple?
A tuple is an immutable sequence of Python objects
AppMillers
www.appmillers.com
Tuples in Memory
Sample Tuple
Memory
AppMillers
www.appmillers.com
Time and Space Complexity in Python Tuples
AppMillers
www.appmillers.com
What is a Linked List?
Linked List is a form of a sequential collection and it does not have to be in order. A Linked
list is made up of independent nodes that may contain any type of data and each node has a
reference to the next node in the link.
Cars (nodes)
Head
Tail
Links
- Each car is independent
- Cars : passengers and links (nodes: data and links)
AppMillers
www.appmillers.com
What is a Linked List?
Cars (nodes)
Head
Tail
Links
Nodes Pointers
AppMillers
www.appmillers.com
Linked Lists vs Arrays
Tail 333
Array = 0 1 2 3 4 5
AppMillers
www.appmillers.com
ffi
ffi
fi
Types of Linked Lists
- Singly Linked List
- Circular Singly Linked List
- Doubly Linked List
Singly Linked List
- Circular Doubly Linked List
Head 001 1 111 2 222 4 333 5 null
Tail 333
Tail 333
AppMillers
www.appmillers.com
Circular Singly Linked List
Head 001 Player1 111 Player2 222 Player3 333 Player4 001
Tail 333
AppMillers
www.appmillers.com
Types of Linked Lists
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
Types of Linked Lists
Head 001 null S1 111 001 S2 222 111 S3 333 222 S4 null
Tail 333
AppMillers
www.appmillers.com
Types of Linked Lists
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Types of Linked Lists
Cmd+shift+tab
Head 001 333 APP1 111 001 APP2 222 111 APP3 333 222 APP4 001
Tail 333
AppMillers
www.appmillers.com
Linked List in Memory
Arrays in memory : 0 1 2 3 4 5
y
or
em
M
0 1 2 3 4 5
AppMillers
www.appmillers.com
Linked List in Memory
Linked list:
2
y
or
em
M
4
Tail 5 1 Head
AppMillers
www.appmillers.com
Creation of Singly Linked List
1 null
111
Tail 111
Create a blank Node and assign a value
to it and reference to null.
AppMillers
www.appmillers.com
Creation of Singly Linked List
AppMillers
www.appmillers.com
Insertion to Linked List in Memory
AppMillers
www.appmillers.com
Insertion to Linked List in Memory
2 0
y
or
em
M
4
5 1 ❌ Head
AppMillers
www.appmillers.com
Insertion to Linked List in Memory
3
Insert a new node after a node
2 0
y
❌
or
em
Head
M
4
5 1
3
AppMillers
www.appmillers.com
Insertion to Linked List in Memory
3 2 0
y
or
em
Head
M
4
5 1
AppMillers
www.appmillers.com
Insertion Algorithm
No
Node value - create node
head=None?
Location - assign value
Yes
- head = node
- tail = node
Yes
- node.next = head
Location = rst
- head = node
No
No
- Find location (loop)
- current.next = node
- node.next =nextNode
AppMillers
www.appmillers.com
fi
Head 444
001 1 111 2 222 4 333 5 null Tail
- node.next = head
- head = node 6
444
AppMillers
www.appmillers.com
- node.next = null
- last.next = node 6 null
- tail = node
444
AppMillers
www.appmillers.com
- nd location (loop)
- current.next = node 6 333
- node.next =nextNode
444
AppMillers
www.appmillers.com
fi
No
Terminate
AppMillers
www.appmillers.com
No
Check Yes If
Start nodeValue Head? nodeValue=currentNode
Yes
No
Terminate
AppMillers
www.appmillers.com
Singly Linked list Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
null 1 null
001
Tail 001
null
AppMillers
www.appmillers.com
fi
Singly Linked list Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
111 1 111 2 222 4 333 5 null
Tail 333
AppMillers
www.appmillers.com
fi
Singly Linked list Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
AppMillers
www.appmillers.com
fi
Singly Linked list Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
null 1 null
001
Tail 001
null
AppMillers
www.appmillers.com
fi
Singly Linked list Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
222
AppMillers
www.appmillers.com
fi
Singly Linked list Deletion Algorithm
No
Location head=None?
Yes
- head = null
- tail = null
Yes
Location = rst
- head = rst.next
No
- head = null
- tail = null
Yes
Terminate - Find node before last node Location = last
(loop)
- beforeLast.next = null
- tail = beforeLast
No
- nd location (loop)
- current.next = nextNode.next
AppMillers
www.appmillers.com
fi
fi
fi
Head 001
null 1 111 2 222 4 333 5 null
Tail 333
null
AppMillers
www.appmillers.com
Time and Space complexity of Singly Linked List
Tail 333
AppMillers
www.appmillers.com
Circular Singly Linked List
Tail 333
Tail 333
AppMillers
www.appmillers.com
Creation of Circular Singly Linked List
Head 001
1 001
001
Tail 001
Start
nodeValue - Create Blank Node
- node.next=node
- node.value=nodeValue
Terminate - head=node
- tail=node
AppMillers
www.appmillers.com
Head 001
444 1 111 2 222 3 333 4 001
444
Tail 333
AppMillers
www.appmillers.com
fi
Circular Singly Linked List - Insertion
newNode
6 001
444
Head 001
444 1 111 2 222 3 333 4 001
444
Tail 333
AppMillers
www.appmillers.com
Circular Singly Linked List - Insertion
newNode
6 222
444
Tail 333
AppMillers
www.appmillers.com
fi
Circular Singly Linked List - Insertion
newNode
7 001
555
Tail 333
555
AppMillers
www.appmillers.com
Insertion Algorithm - Circular singly linked list
No
No
No
- nd location (loop)
- newNode.next = currentNode.next
- currentNode.next = newNode
AppMillers
www.appmillers.com
fi
fi
Tail 333
print(node1.value) 1
Check Yes
Start
print(node2.value) 2 Head? print(currentNode.value)
print(node3.value) 3
print(node4.value) 4 No
Terminate
AppMillers
www.appmillers.com
Circular Singly Linked List - Searching
Tail 333
No
Check Yes
nodeValue If currentNode=node
Head?
No
Yes
Terminate
AppMillers
www.appmillers.com
Circular Singly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
null 1 null
001
001
Tail 001
null
AppMillers
www.appmillers.com
fi
Circular Singly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
111 1 111 2 222 4 333 5 111
001
Tail 333
AppMillers
www.appmillers.com
fi
Circular Singly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
AppMillers
www.appmillers.com
fi
Circular Singly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 001
null 1 null
001
001
Tail 001
null
AppMillers
www.appmillers.com
fi
Circular Singly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
222
AppMillers
www.appmillers.com
fi
Circular Singly Linked list Deletion Algorithm
No
Location head=None?
Yes
- head = none
- tail = none
- rst.next = none
Yes
Location = rst
- head = rst.next
- tail.next = head
No
- head = none
- tail = none
- rst.next = none
Yes
Terminate - Find node before last node Location = last
(loop)
- Tail = curNode
- curNode.next = head
No
- nd location (loop)
- current.next = nextNode.next
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
Tail 444
deleteNode(head, location):
if head does not exist:
return error //Linked list does not exist
if location = rstNode’s location
if this is the only node in the list
head=tail=node.next=null
else
head=head.next
tail.next = head
else if location = lastNode's location
if this is the only node in the list
head=tail=node.next=null
else
loop until lastNode location -1 (curNode)
tail=curNode
curNode.next = head
else // delete middle node
loop until location-1 (curNode)
curNode.next = curNode.next.next AppMillers
www.appmillers.com
fi
Circular Singly Linked list - Deletion Algorithm
Tail 444
deleteNode(head, location):
if head does not exist:
return error //Linked list does not exist
if location = rstNode’s location
if this is the only node in the list
head=tail=node.next=null
else
head=head.next
tail.next = head
else if location = lastNode's location
if this is the only node in the list
head=tail=node.next=null
else
loop until lastNode location -1 (curNode)
tail=curNode
curNode.next = head
else // delete middle node
loop until location-1 (curNode)
curNode.next = curNode.next.next AppMillers
www.appmillers.com
fi
Delete entire Circular Singly Linked list
Head 001
null 1 111 2 222 4 333 5 null
001
Tail 333
null
AppMillers
www.appmillers.com
Delete entire Circular Singly Linked List
Tail 444
deleteLinkedList(head, tail):
head = null
tail.next = null
Tail = null
AppMillers
www.appmillers.com
Time and Space complexity of Circular Singly Linked List
Tail 444
AppMillers
www.appmillers.com
Doubly Linked List
Singly Linked List
Tail 333
Head 001 null 1 111 001 2 222 111 3 333 222 4 null
Tail 333
AppMillers
www.appmillers.com
Creation of Doubly Linked List
Head 111
null 5 null
111
Tail 111
Start
nodeValue - Create Blank Node - node.next=Null
- node.value=nodeValue - node.prev=Null
Terminate - head=node
- tail=node
AppMillers
www.appmillers.com
Head
111
Tail
createDoublyLinkedList(nodeValue):
create a blank node
node.value = nodeValue
head = node
tail = node
node.next = node.prev = null
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
fi
Doubly Linked List - Insertion
newNode
null 10 001
002
Head 001
002 002
null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
Doubly Linked List - Insertion
newNode
111 20 222
555
Tail 333
AppMillers
www.appmillers.com
fi
Doubly Linked List - Insertion
333 20 null
444
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
444
Tail 333
444
AppMillers
www.appmillers.com
Insertion Algorithm - Doubly linked list
No
- newNode.prev = None
Yes
- newNode.next = head
location = rst ?
- head.prev = newNode
- head = newNode
No
- newNode.next = None
Yes
Terminate - newNode.prev = tail
location = last ?
- tail.next = newNode
- tail = newNode
- nd location-1 (loop)
- newNode.next = currentNode.next No
- newNode.prev = currentNode
- newNode.next.prev = newNode
- currentNode.next = newNode AppMillers
www.appmillers.com
fi
fi
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
Insertion Algorithm - Doubly Linked List
newNode
003
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
Head 001 null 1 111 001 2 222 111 3 333 222 4 null
Tail 333
print(node1.value) 1
Check Yes Loop head to tail
Start
print(node2.value) 2 Head? print(currentNode.value)
print(node3.value) 3
print(node4.value) 4 No
Terminate
AppMillers
www.appmillers.com
Head 001 null 1 111 001 2 222 111 3 333 222 4 null
Tail 333
print(node4.value) 4
Check Yes Loop tail to head
Start
print(node3.value) 3 Head? print(currentNode.value)
print(node2.value) 2
print(node1.value) 1 No
Terminate
AppMillers
www.appmillers.com
Head 001 null 1 111 001 2 222 111 3 333 222 4 null
Tail 333
No
Check Yes If
Start nodeValue=currentNode
nodeValue Head?
Yes
No
Terminate
AppMillers
www.appmillers.com
Traversal in doubly linked list
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
traversalDoublyLinkedList():
if head == null:
return //There is not any node in this list
loop head to tail:
print(currentNode.value)
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
reverseTraversalDoublyLinkedList(head):
if head == null:
return //There is not any node in this list
loop tail to head:
print(currentNode.value)
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
searchForNode(head, nodeValue):
loop head to tail:
if currentNode.value = nodeValue
print(currentNode)
return
return // nodeValue not found
node1
Head 001
null null 1 null
001
Tail null
001
AppMillers
www.appmillers.com
fi
Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 111
001 null 1 111 null
001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
fi
Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
AppMillers
www.appmillers.com
fi
Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
node1
Head 001
null null 1 null
001
Tail null
001
AppMillers
www.appmillers.com
fi
Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
222
AppMillers
www.appmillers.com
fi
Doubly Linked list Deletion Algorithm
No
Location head=None?
Yes
- head = none
- tail = none
Yes
Location = rst
- head = head.next
- head.prev = null
No
- head = none
- tail = none
Yes
Terminate Location = last
- tail = tail.prev
- tail.next = null
No
- nd location-1 (loop)
- curNode.next = curNode.next.next
- curNode.next.prev = curNode
AppMillers
www.appmillers.com
fi
fi
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
deleteNode(head, location):
if head does not exist:
return error //Linked list does not exist
if location = rstNode’s location
if this is the only node in the list Time complexity : O(n)
head=tail=null
else Space complexity : O(1)
head=head.next
head.prev = null
else if location = lastNode's location
if this is the only node in the list
head=tail=null
else
loop until lastNode location -1 (curNode)
tail=curNode
curNode.next = head
else // delete middle node
loop until location-1 (curNode)
curNode.next = curNode.next.next
curNode.next.prev = curNode AppMillers
www.appmillers.com
fi
Deleting entire doubly linked list- Algorithm
Head 001
null null 1 111 001
null 2 222 null
111 4 333 null
222 5 null
Tail 333
null
AppMillers
www.appmillers.com
Time and Space complexity of doubly linked list
Head 001 null 1 111 001 2 222 111 4 333 222 5 null
Tail 333
AppMillers
www.appmillers.com
Circular doubly linked list
Tail 333
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Creation of Circular Doubly Linked List
Head 001
001 11 001
001
Tail 001
Start
nodeValue - Create Blank Node - head=node
- node.value=nodeValue - tail=node
Terminate - node.next=node
- node.prev=node
AppMillers
www.appmillers.com
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
fi
Circular Doubly Linked List - Insertion
newNode
333 6 001
444
Head 001
444 444
333 1 111 001 2 222 111 4 333 222 5 001
444
Tail 333
AppMillers
www.appmillers.com
Circular Doubly Linked List - Insertion
newNode
111 20 222
555
Tail 333
AppMillers
www.appmillers.com
fi
Circular Doubly Linked List - Insertion
333 20 001
444
Tail 333
444
AppMillers
www.appmillers.com
Insertion Algorithm - Circular Doubly linked list
No
- newNode.prev = tail
Yes
- newNode.next = head
location = rst ?
- head.prev = newNode
- head = newNode
- tail.next = newNode
No
- newNode.next = head
- newNode.prev = tail
Yes
Terminate - head.prev = newNode location = last ?
- tail.next = newNode
- tail = newNode
- nd location-1 (loop)
- newNode.next = currentNode.next No
- newNode.prev = currentNode
- newNode.next.prev = newNode
- currentNode.next = newNode AppMillers
www.appmillers.com
fi
fi
Head 001 333 1 111 001 2 222 111 3 333 222 4 001
Tail 333
No
print(node1.value) 1
Loop head to
Check Yes tail
Start
print(node2.value) 2 Head? print(currentNode.value)
If currentNode=
tail
print(node3.value) 3
print(node4.value) 4 No
Yes
Terminate
AppMillers
www.appmillers.com
Head 001 333 1 111 001 2 222 111 3 333 222 4 001
Tail 333
No
print(node4.value) 4
Check Yes Loop tail to head
Start
print(node3.value) 3 Head? print(currentNode.value
If currentNode =
head
print(node2.value) 2
print(node1.value) 1 No
Yes
Terminate
AppMillers
www.appmillers.com
Head 001 333 1 111 001 2 222 111 3 333 222 4 001
Tail 333
No
Check Yes If
Start nodeValue=currentNode
nodeValue Head? or if currentNode = tail
Yes
No
Terminate
AppMillers
www.appmillers.com
Circular Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
node1
Head 001
null 001
null 1 001
null
001
Tail null
001
AppMillers
www.appmillers.com
fi
Circular Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Head 111
001 333 1 111 333
001 2 222 111 4 333 222 5 001
111
Tail 333
AppMillers
www.appmillers.com
fi
Circular Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
AppMillers
www.appmillers.com
fi
Circular Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
node1
Head 001
null 001
null 1 001
null
001
Tail null
001
AppMillers
www.appmillers.com
fi
Circular Doubly Linked list - Deletion
- Deleting the rst node
- Deleting any given node
- Deleting the last node
Tail 333
222
AppMillers
www.appmillers.com
fi
Circular Doubly Linked list Deletion Algorithm
No
Location head=None?
- head.prev = none No
- head.next = none
- head = none
- tail = none
Yes
Terminate - tail = tail.prev Location = last
- tail.next = head
- head.prev = tail
No
- nd location-1 (loop)
- curNode.next = curNode.next.next
- curNode.next.prev = curNode
AppMillers
www.appmillers.com
fi
fi
Head 001
null null
333 1 111 001
null 2 222 null
111 4 333 null
222 5 001
null
Tail 333
null
AppMillers
www.appmillers.com
Circular doubly linked list - creation
Head 11
001
Tail
AppMillers
www.appmillers.com
Circular doubly linked list - insertion
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Circular doubly linked list - traversal
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
traversalCircularDoublyLinkedList():
if head == null:
return //There is not any node in this list
loop head to tail:
print(currentNode.value)
if currentNode.value = tail:
terminate
AppMillers
www.appmillers.com
Circular doubly linked list - reverse traversal
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
reverseTraversalCircularDoublyLinkedList():
if head == null:
return //There is not any node in this list
loop tail to head:
print(currentNode.value)
if currentNode.value = head:
terminate
AppMillers
www.appmillers.com
Circular doubly linked list - searching for a node
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
searchForNode(head, nodeValue):
loop head to tail:
if currentNode.value = nodeValue
print(currentNode)
return
if currentNode.value = tail:
terminate
return // nodeValue not found
AppMillers
www.appmillers.com
Deleting a node in doubly linked list
- Deleting the rst node
- Deleting the last node
- Deleting any node apart from the rst and the last
node1
001
Tail 001
AppMillers
www.appmillers.com
fi
fi
fi
Deleting a node in circular doubly linked list
- Deleting the rst node
- Deleting the last node
- Deleting any node apart from the rst and the last
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
fi
fi
fi
Deleting a node in circular doubly linked list
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Deleting a node in circular doubly linked list
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Deleting a node in circular doubly linked list- Algorithm
node1 node2 node3 node4
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
deleteNode(head, location):
if head does not exist:
return error //Linked list does not exist
if location = rstNode’s location
if this is the only node in the list
head.prev=head.next=head=tail=null Time complexity : O(n)
else
head=head.next
Space complexity : O(1)
head.prev = tail
tail.next = head
else if location = lastNode's location
if this is the only node in the list
head.prev=head.next=head=tail=null
else
tail = tail.prev
tail.next = head
head.prev = tail
else // delete middle node
loop until location-1 (curNode)
curNode.next = curNode.next.next AppMillers
curNode.next.prev = curNode www.appmillers.com
fi
Deleting entire circular doubly linked list- Algorithm
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Time and Space complexity of circular doubly linked list
Head 001 333 1 111 001 2 222 111 4 333 222 5 001
Tail 333
AppMillers
www.appmillers.com
Interview Questions - 1 : Remove Duplicates
Tail 333
currentNode = node1
tempSet = {1} {1,2} {1,2,3}
AppMillers
www.appmillers.com
Interview Questions - 2 : Return Nth to Last
Implement and algorithm to nd the nth to last element of a singly linked list.
P1 P2
Tail 444
N=2 Node4
pointer1 = node1 pointer2 = node2
= node2 = node3
= node3 = node4
= node4 = node5
AppMillers
www.appmillers.com
fi
Interview Questions - 3 : Partition
Write code to partition a linked list around a value x, such that all nodes less than x
come before all nodes greater than or equal to x.
Tail 444
x = 10
node2
currentNode = node1
Tail = node1
3 null
currentNode.next = null 111
node1
001
Tail 001
AppMillers
www.appmillers.com
Interview Questions - 3 : Partition
Write code to partition a linked list around a value x, such that all nodes less than x
come before all nodes greater than or equal to x.
Tail 444
x = 10 node3
currentNode = node1
9 null
Tail = node1 222
currentNode.next = null
node2 node1
111 001
Tail 001
AppMillers
www.appmillers.com
Interview Questions - 3 : Partition
Write code to partition a linked list around a value x, such that all nodes less than x
come before all nodes greater than or equal to x.
Tail 444
node4
x = 10
10 null
currentNode = node1
Tail = node1 333
currentNode.next = null
node3 node2 node1
Tail 001
AppMillers
www.appmillers.com
Interview Questions - 3 : Partition
Write code to partition a linked list around a value x, such that all nodes less than x
come before all nodes greater than or equal to x.
Tail 444
x = 10 Node5
Tail 333
AppMillers
www.appmillers.com
Interview Questions - 3 : Partition
Write code to partition a linked list around a value x, such that all nodes less than x
come before all nodes greater than or equal to x.
Tail 444
x = 10
currentNode = node1
Tail = node1
currentNode.next = null
node3 node2 node1 node4 Node5
Tail 444
AppMillers
www.appmillers.com
Interview Questions - 4 : Sum Lists
You have two numbers represented by a linked list, where each node contains a single digit.
The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a
function that adds the two numbers and returns the sum as a linked list.
617 7 + 5 = 12
+ 295 1+9+1 = 11
6+2+1 = 9
912
7 1 6
2 1 9
5 9 2
AppMillers
www.appmillers.com
Interview Questions - 5 : Intersection
Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node.
Note that the intersection is de ned based on reference, not value. That is, if the kth node of
the rst linked list is the exact same node (by reference) as the jth node of the second linked
list, then they are intersecting.
3 1 5 9
7 2 1
2 4 6
3 1 5 9 7 2 1
2 4 6 7 2 1
AppMillers
www.appmillers.com
fi
fi
Interview Questions - 5 : Intersection
Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node.
Note that the intersection is de ned based on reference, not value. That is, if the kth node of
the rst linked list is the exact same node (by reference) as the jth node of the second linked
list, then they are intersecting.
listA 3 1 5 9
7 2 1
listB 2 4 6
len(listA) = 7
7-6=1
len(listB) = 6
AppMillers
www.appmillers.com
fi
fi
What is a Stack?
AppMillers
www.appmillers.com
What is a Stack?
LIFO method
AppMillers
www.appmillers.com
What is a Stack?
40
30
20
10
AppMillers
www.appmillers.com
Why do we need a Stack?
appmillers.com
linkedin.com Stack
gmail.com
udemy.com
AppMillers
www.appmillers.com
Stack operations
- Create Stack
- Push
- Pop customStack()
- Peek
- isEmpty
- isFull
- deleteStack
AppMillers
www.appmillers.com
Push() method
customStack = [ ]
customStack.push(1)
AppMillers
www.appmillers.com
Push() method
customStack = [1]
customStack.push(2)
customStack.push(1)
AppMillers
www.appmillers.com
Push() method
customStack = [1,2]
customStack.push(3)
customStack.push(2)
2
1
AppMillers
www.appmillers.com
Push() method
customStack = [1,2,3]
customStack.push(4)
customStack.push(3)
3
2
1
AppMillers
www.appmillers.com
Push() method
customStack = [1,2,3,4]
customStack.push(4)
4
3
2
1
AppMillers
www.appmillers.com
Pop() method
customStack = [1,2,3]
[1,2,3,4]
customStack.pop() 4
4
3
2
1
AppMillers
www.appmillers.com
Pop() method
customStack = [1,2]
[1,2,3]
customStack.pop() 3
3
2
1
AppMillers
www.appmillers.com
Pop() method
customStack = [1]
[1,2]
customStack.pop() 2
2
1
AppMillers
www.appmillers.com
Pop() method
customStack = []
[1]
customStack.pop() 1
AppMillers
www.appmillers.com
Pop() method
customStack = []
customStack.pop()
The stack is Empty
AppMillers
www.appmillers.com
Peek() method
customStack = [1,2,3,4]
customStack.peek() 4
4
3
2
1
AppMillers
www.appmillers.com
isEmpty() method
customStack = [1,2,3,4]
customStack.isEmpty() False
4
3
2
1
AppMillers
www.appmillers.com
isFull() method
customStack = [1,2,3,4]
customStack.isFull() False
4
3
2
1
AppMillers
www.appmillers.com
delete() method
customStack = [1,2,3,4]
customStack.delete()
4
3
2
1
AppMillers
www.appmillers.com
Stack creation
AppMillers
www.appmillers.com
Time and Space complexity of Stack operations with List
AppMillers
www.appmillers.com
Stack using Linked List
Create a Stack
Head null
AppMillers
www.appmillers.com
Stack using Linked List
push() Method
2 null
111
222
Head null
222
111 1 null
111
2
1
AppMillers
www.appmillers.com
Stack using Linked List
push() Method
3 null
222
333
Head 222
333 2 111 1 null
222 111 3
2
1
AppMillers
www.appmillers.com
Stack using Linked List
pop() Method
Head 333
222 3 222 2 111 1 null
AppMillers
www.appmillers.com
Stack using Linked List
pop() Method
Head 222
111 2 111 1 null
222 111
2
1
AppMillers
www.appmillers.com
Stack using Linked List
peek() Method
AppMillers
www.appmillers.com
Stack using Linked List
isEmpty() Method
AppMillers
www.appmillers.com
Stack using Linked List
delete() Method
AppMillers
www.appmillers.com
Time and Space complexity of Stack operations with Linked List
AppMillers
www.appmillers.com
When to use / avoid Stack
Use:
- LIFO functionality
- The chance of data corruption is minimum
Avoid: 4
- Random access is not possible 3
2
1
AppMillers
www.appmillers.com
What is a Queue?
End Front
50 40 30 20 10
AppMillers
www.appmillers.com
What we need Queue Data Structure?
Utilize rst coming data rst , while others wait for their turn.
AppMillers
www.appmillers.com
fi
fi
What we need Queue Data Structure?
AppMillers
www.appmillers.com
What we need Queue Data Structure?
Printer queue
AppMillers
www.appmillers.com
What we need Queue Data Structure?
AppMillers
www.appmillers.com
Queue Operations
- Create Queue
- Enqueue
- Dequeue
- Peek
- isEmpty
- isFull
- deleteQueue
AppMillers
www.appmillers.com
Queue Operations
Implementation
1. Python List
- Queue without capacity
- Queue with capacity (Circular Queue)
2. Linked List
1 2 3
Tail 333
AppMillers
www.appmillers.com
Create Queue using Python List no capacity
customQueue = [ ]
AppMillers
www.appmillers.com
Enqueue() method
customQueue = [ ]
customQueue.enqueue(1)
AppMillers
www.appmillers.com
Enqueue() method
customQueue = [1]
customQueue.enqueue(2)
customQueue.enqueue(1)
AppMillers
www.appmillers.com
Enqueue() method
customQueue = [1,2]
customQueue.enqueue(3)
customQueue.enqueue(2)
2 1
AppMillers
www.appmillers.com
Enqueue() method
customQueue = [1,2,3]
customQueue.enqueue(4)
customQueue.enqueue(3)
3 2 1
AppMillers
www.appmillers.com
Enqueue() method
customQueue = [1,2,3,4]
customQueue.enqueue(4)
4 3 2 1
AppMillers
www.appmillers.com
Dequeue() method
customQueue = [2,3,4]
[1,2,3,4]
customQueue.dequeue() 1
4 3 2 1
AppMillers
www.appmillers.com
Dequeue() method
customQueue = [3,4]
[2,3,4]
customQueue.dequeue() 2
4 3 2
AppMillers
www.appmillers.com
Dequeue() method
customQueue = [4]
[3,4]
customQueue.dequeue() 3
4 3
AppMillers
www.appmillers.com
Dequeue() method
customQueue = []
[4]
customQueue.dequeue() 4
AppMillers
www.appmillers.com
Dequeue() method
customQueue = []
customQueue.dequeue()
The queue is Empty
AppMillers
www.appmillers.com
Peek() method
customQueue = [1,2,3,4]
customQueue.peek() 1
4 3 2 1
AppMillers
www.appmillers.com
isEmpty() method
customQueue = [1,2,3,4]
customQueue.isEmpty() False
4 3 2 1
AppMillers
www.appmillers.com
isFull() method
customQueue =[1,2,3,4]
customQueue.isFull()
4 3 2 1
AppMillers
www.appmillers.com
delete() method
customQueue = [1,2,3,4]
customQueue.delete()
4 3 2 1
AppMillers
www.appmillers.com
Time and Space complexity of Queue operations with Python List
AppMillers
www.appmillers.com
Queue creation
AppMillers
www.appmillers.com
Queue with xed capacity (Circular Queue)
List relocation
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
Create Queue
Size = 6
Start = -1
Top = -1
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
enqueue(5)
Start = 0
Top = 0
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
enqueue(6)
Start = 0
Top = 10
5 6
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
enqueue(7)
Start = 0
Top = 21
5 6 7
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
enqueue(8)
Start = 0
Top = 32
5 6 7 8
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
dequeue() 5
Start = 1
0
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
dequeue() 6
Start = 2
1
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
5 6 7 8 3 1
S T
5 6 7 8 3 1
T S
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
enqueue(9)
Start = 2
Top = 05
5
9 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
Peek method
peek() 5
Start = 0
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
Peek method
peek() 6
Start = 1
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
isFull method
isFull() True
Start = 0
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
isFull method
isFull() False
Start = 1
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
isEmpty method
isEmpty() False
Start = 1
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
Delete method
delete()
Start = 1
Top = 5
5 6 7 8 3 1
S T
AppMillers
www.appmillers.com
fi
Queue with xed capacity (Circular Queue)
Delete method
delete()
Start = -1
Top = -1
AppMillers
www.appmillers.com
fi
Time and Space complexity of Circular Queue operations
AppMillers
www.appmillers.com
Queue using Linked List
Create a Queue
Head null
Tail null
AppMillers
www.appmillers.com
Queue using Linked List
enQueue() Method
Head null
111 1 null
222 2 null
111 222
2 1
Tail null
222
111
AppMillers
www.appmillers.com
Queue using Linked List
enQueue() Method
Head null
111 1 null
222 2 null
333 3 null
Tail null
222
333
111
AppMillers
www.appmillers.com
Queue using Linked List
deQueue() Method
Head 111
222 1 222 2 333 3 null
Tail 333
AppMillers
www.appmillers.com
Queue using Linked List
deQueue() Method
Head 222
333 2 333 3 null
222 333
3 2
Tail 333
AppMillers
www.appmillers.com
Queue using Linked List
peek() Method
Tail 333
peek()
return head.value
AppMillers
www.appmillers.com
Queue using Linked List
isEmpty() Method
Tail 333
isEmpty()
If head is None:
True
AppMillers
www.appmillers.com
Queue using Linked List
delete() Method
Head 111
null 1 222 2 333 3 null
Tail 333
null
delete()
head = None
tail = None
AppMillers
www.appmillers.com
Time and Space complexity of Queue operations using Linked List
AppMillers
www.appmillers.com
Time and Space complexity Queue : List vs Linked List
AppMillers
www.appmillers.com
Python Queue Modules
Collections module
Queue Module
4 2 5 3 2 1
AppMillers
www.appmillers.com
Python Collections Module
The collections.deque Class
AppMillers
www.appmillers.com
Python Queue Module
Methods
- qsize() 4 2 5 3 2 1
- empty()
- full()
- put()
- get()
- task_done()
- join()
AppMillers
www.appmillers.com
Python Queue Module
Methods
- qsize() 4 2 5 3 2 1
- empty()
- full()
- put()
- get()
- task_done()
- join()
AppMillers
www.appmillers.com
When to use / avoid Queue
Use:
- FIFO functionality
- The chance of data corruption is minimum
Avoid:
- Random access is not possible
3 2 1
AppMillers
www.appmillers.com
Interview Questions - 1 : Three in One
Describe how you could use a single Python list to implement three stacks.
AppMillers
www.appmillers.com
Interview Questions - 2 : Stack Min
How would you design a stack which, in addition to push and pop, has a function min which
returns the minimum element? Push, pop and min should all operate in O(1).
push(5) min() 5
push(6) min() 5
push(3) min() 3
push(7) min() 3
7
pop() min() 3
pop() min() 5
3
6
5
AppMillers
www.appmillers.com
Interview Questions - 3 : Stack of Plates
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real
life, we would likely start a new stack when the previous stack exceeds some threshold.
Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of
several stacks and should create a new stack once the previous one exceeds capacity,
SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is,
pop( ) should return the same values as it would if there were just a single stack).
Follow Up:
Implement a function popAt (int index) which performs a pop operation on a speci c sub - stack.
AppMillers
www.appmillers.com
fi
Interview Questions - 3 : Stack of Plates
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real
life, we would likely start a new stack when the previous stack exceeds some threshold.
Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of
several stacks and should create a new stack once the previous one exceeds capacity,
SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is,
pop() should return the same values as it would if there were just a single stack).
Follow Up:
Implement a function popAt (int index) which performs a pop operation on a speci c sub - stack.
pop( )
AppMillers
www.appmillers.com
fi
Interview Questions - 4 : Queue via Stacks
Dequeue()
Enqueue()
7
3
6
5
Stack1 Stack2
AppMillers
www.appmillers.com
Interview Questions - 5 : Animal Shelter
An animal shelter, which holds only dogs and cats, operates on a strictly " rst in, rst out"
basis. People must adopt either the "oldest" (based on arrival time) of all animals at the
shelter, or they can select whether they would prefer a dog or a cat (and will receive the
oldest animal of that type). They cannot select which speci c animal they would like. Create
the data structures to maintain this system and implement operations such as enqueue,
dequeueAny, dequeueDog, and dequeueCat.
Newest Oldest
🐈 🐕 🐈 🐈 🐈 🐕 🐈 🐕
Enqueue(Dog)
Enqueue(Cat)
AppMillers
www.appmillers.com
fi
fi
fi
Interview Questions - 5 : Animal Shelter
An animal shelter, which holds only dogs and cats, operates on a strictly " rst in, rst out"
basis. People must adopt either the "oldest" (based on arrival time) of all animals at the
shelter, or they can select whether they would prefer a dog or a cat (and will receive the
oldest animal of that type). They cannot select which speci c animal they would like. Create
the data structures to maintain this system and implement operations such as enqueue,
dequeueAny, dequeueDog, and dequeueCat.
Newest Oldest
🐈 🐕 🐈 🐈 🐈 🐕 🐈 🐕
DequeueAny()
DequeueDog()
DequeueCat()
AppMillers
www.appmillers.com
fi
fi
fi
Interview Questions - 6 : Animal Shelter
7
3
6
5
AppMillers
www.appmillers.com
What is a Tree?
A tree is a nonlinear data structure with hierarchical relationships between its elements
without having any cycle, it is basically reversed from a real life tree.
Drinks
Hot Cold
Green Black Americano Latte Cappuccino Cola Fanta Soda Wine Beer
AppMillers
www.appmillers.com
ff
What is a Tree?
A tree is a nonlinear data structure with hierarchical relationships between its elements
without having any cycle, it is basically reversed from a real life tree.
Drinks
Hot Cold
Green Black Americano Latte Cappuccino Cola Fanta Soda Wine Beer
Properties:
- Represent hierarchical data
- Each node has two components : data and a link to its sub category
- Base category and sub categories under it
AppMillers
www.appmillers.com
ff
What is a Tree?
A tree is a nonlinear data structure with hierarchical relationships between its elements
without having any cycle, it is basically reversed from a real life tree.
N1
N2 N3
N4 N5 N6
N7 N8
Tree Properties:
- Represent hierarchical data
- Each node has two components : data and a link to its sub category
- Base category and sub categories under it
AppMillers
www.appmillers.com
Why a Tree?
AppMillers
www.appmillers.com
Why a Tree?
The le system on a computer
AppMillers
www.appmillers.com
fi
Why a Tree?
AppMillers
www.appmillers.com
ff
Tree Terminology root
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent edge N2 N3
Ancestor : parent, grandparent, great grandparent of a node
N4 N5 N6
sibling
N7 N8
leaf
AppMillers
www.appmillers.com
Tree Terminology
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent
N2 N3
Ancestor : parent, grandparent, great grandparent of a node
ancestors of N7 N4 N5 N6
N7 N8
AppMillers
www.appmillers.com
Tree Terminology
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent
N2 N3
Ancestor : parent, grandparent, great grandparent of a node
Depth of node : a length of the path from root to node
Depth of N4 = 2 N4 N5 N6
N7 N8
AppMillers
www.appmillers.com
Tree Terminology
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent
N2 N3
Ancestor : parent, grandparent, great grandparent of a node
Depth of node : a length of the path from root to node
Height of node : a length of the path from the node to the deepest node
Heigh of N3 = 1 N4 N5 N6
N7 N8
AppMillers
www.appmillers.com
Tree Terminology
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent
N2 N3
Ancestor : parent, grandparent, great grandparent of a node
Depth of node : a length of the path from root to node
Height of node : a length of the path from the node to the deepest node
Depth of tree : depth of root node
N4 N5 N6
Depth of tree = 0
N7 N8
AppMillers
www.appmillers.com
Tree Terminology
N1
Root : top node without parent
Edge : a link between parent and child
Leaf : a node which does not have children
Sibling : children of same parent
N2 N3
Ancestor : parent, grandparent and great grandparent of a node
Depth of node : a length of the path from root to node
Height of node : a length of the path from the node to the deepest node
Depth of tree : depth of root node
Height of tree : height of root node N4 N5 N6
Height of tree = 3
N7 N8
AppMillers
www.appmillers.com
Binary Tree
- Binary trees are the data structures in which each node has at most two children,
often referred to as the left and right children
- Binary tree is a family of data structure (BST, Heap tree, AVL, red black trees, Syntax tree)
N1
N2 N3
N4 N5 N6
N7 N8
AppMillers
www.appmillers.com
Why Binary Tree?
- Binary trees are a prerequisite for mode advanced trees like BST, AVL, Red Black Trees
- Hu man coding problem , heap priority problem and expression parsing problems can be
solved e ciently using binary trees,
N1
N2 N3
N4 N5 N6
N7 N8
AppMillers
www.appmillers.com
ff
ffi
Types of Binary Tree
N1
N2 N3
N4 N5
N7 N8
AppMillers
www.appmillers.com
Types of Binary Tree
N1
N2 N3
N4 N5 N6 N7
AppMillers
www.appmillers.com
Types of Binary Tree
N1
N2 N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Types of Binary Tree
N1
N2 N3
N4 N5 N7
AppMillers
www.appmillers.com
Binary Tree
- Linked List
- Python List (array)
Drinks
Hot Cold
AppMillers
www.appmillers.com
ff
Binary Tree
Linked List
222 Drinks 333
111
null Tea null null Co ee null null Cola null null Fanta null
444 555 666 777
AppMillers
www.appmillers.com
ff
Binary Tree
Python List
Drinks
Hot Cold
0 1 2 3 4 5 6 7 8
AppMillers
www.appmillers.com
ff
Binary Tree
Python List
Drinks
Hot Cold
0 1 2 3 4 5 6 7 8
Drinks Hot Cold
AppMillers
www.appmillers.com
ff
Binary Tree
Python List
Drinks
Hot Cold
0 1 2 3 4 5 6 7 8
Drinks Hot Cold Tea Co ee
AppMillers
www.appmillers.com
ff
ff
Binary Tree
Python List
Drinks
Hot Cold
0 1 2 3 4 5 6 7 8
Drinks Hot Cold Tea Co ee Non alcoholic Alcoholic
AppMillers
www.appmillers.com
ff
ff
Create Binary Tree using Linked List
- Creation of Tree N1
- Insertion of a node
- Deletion of a node
- Search for a value
- Traverse all nodes N2 N3
- Deletion of tree
N4 N5 N6 N7
newTree = Tree()
N9 N10
AppMillers
www.appmillers.com
Traversal of Binary Tree
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
fi
fi
PreOrder Traversal of Binary Tree
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
N1 N2
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Tree
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
N1 N2 N4 N9 N10
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Tree
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
N1 N2 N4 N9 N10 N5 N3 N6 N7
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Tree
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
N9 N4
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
N9 N4 N10 N2 N5
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
N9 N4 N10 N2 N5 N1 N6 N3 N7
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
N9 N10
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
N9 N10 N4 N5 N2
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
N9 N10 N4 N5 N2 N6 N7 N3 N1
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree
Level 1 N1
Level 2 N2 N3
Level 3 N4 N5 N6 N7
Level 4 N9 N10
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree
Level 1 N1
Level 2 N2 N3
Level 3 N4 N5 N6 N7
Level 4 N9 N10
N1 N2 N3 N4 N5
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree
Level 1 N1
Level 2 N2 N3
Level 3 N4 N5 N6 N7
Level 4 N9 N10
N1 N2 N3 N4 N5 N6 N7 N9 N10
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree
N1
N2 N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Searching for a node in Binary Tree
N5 Success
Level 2 N2 N3
Level 3 N4 N5 N6 N7
Level 4 N9 N10
AppMillers
www.appmillers.com
Insert a node in Binary Tree
N2 N3
newNode N4 N5 N6 N7
N9 N10 new
AppMillers
www.appmillers.com
fi
Delete a node from Binary Tree
N2 N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Delete a node from Binary Tree
N2 N10
N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Delete entire Binary Tree
rootNode = None
N1
rootNode.leftChild = None
rootNode.rightChild = None
N2 N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Create Binary Tree using Python List
N1
N2 N3
N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
AppMillers
www.appmillers.com
Create Binary Tree using Python List
N1
N2 N3
N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
N1 N2 N3
AppMillers
www.appmillers.com
Create Binary Tree using Python List
N1
N2 N3
N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
N1 N2 N3 N4 N5
AppMillers
www.appmillers.com
Create Binary Tree using Python List
N1
N2 N3
N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
N1 N2 N3 N4 N5 N6 N7
AppMillers
www.appmillers.com
Create Binary Tree using Python List
N1
newBT = BTclass()
lastUsedIndex N2 N3
N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
N1 N2 N3 N4 N5 N6 N7
AppMillers
www.appmillers.com
Insert a node in Binary Tree
newNode N2 N3
N4 N5 N6 N7
N8 N9 new
0 1 2 3 4 5 6 7 8 9 10 11
N1 N2 N3 N4 N5 N6 N7 N8 N9 New
AppMillers
www.appmillers.com
fi
Searching for a node in Binary Tree (python list)
N5 Success Level 1 N1
Level 2 N2 N3
Level 3 N4 N5 N6 N7
0 1 2 3 4 5 6 7 8
N1 N2 N3 N4 N5 N6 N7
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Tree (python list)
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Tree (python list)
N1
Root Node
N2 N3
Left Subtree
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree (python list)
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
InOrder Traversal of Binary Tree (python list)
N1
Left Subtree
N2 N3
Root Node
N4 N5 N6 N7
Right Subtree
N9 N10
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree (python list)
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Tree (python list)
N1
Left Subtree
N2 N3
Right Subtree
N4 N5 N6 N7
Root Node
N9 N10
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree (python list)
Level 1 N1
Level 2 N2 N3
Level 3 N4 N5 N6 N7
Level 4 N9 N10
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Tree (python list)
N1
N2 N3
N4 N5 N6 N7
N9 N10
AppMillers
www.appmillers.com
Delete a node from Binary Tree (python list)
deepestNode = lastUsedIndex
N2 N3
N4 N5 N6 N7
N8 N9
N1 N2 N3 N4 N5 N6 N7 N8 N9
0 1 2 3 4 5 6 7 8 9 10 11
AppMillers
www.appmillers.com
Delete a node from Binary Tree (python list)
N2 N9
N3
N4 N5 N6 N7
N8 N9
N1 N2 N9
N3 N4 N5 N6 N7 N8 N9
0 1 2 3 4 5 6 7 8 9 10 11
AppMillers
www.appmillers.com
Delete entire Binary Tree (python list)
N1
customList = None
N2 N3
N4 N5 N6 N7
N9 N10
N1 N2 N3 N4 N5 N6 N7 N8 N9
0 1 2 3 4 5 6 7 8 9 10 11
AppMillers
www.appmillers.com
Binary Tree (Python List vs Linked List)
Space Space
Time complexity Time complexity
complexity complexity
AppMillers
www.appmillers.com
ffi
What is a Binary Search Tree?
- In the left subtree the value of a node is less than or equal to its parent node’s value.
- In the right subtree the value of a node is greater than its parent node’s value
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
What is a Binary Search Tree?
- In the left subtree the value of a node is less than or equal to its parent node’s value.
- In the right subtree the value of a node is greater than its parent node’s value
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Why Binary Search Tree?
- It performs faster than Binary Tree when inserting and deleting nodes
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Common Operations on Binary Search Tree
70
- Creation of Tree
- Insertion of a node
- Deletion of a node
- Search for a value 50 90
- Traverse all nodes
- Deletion of tree
30 60 80 100
20 40
AppMillers
www.appmillers.com
Create Binary Search Tree
70
50 90
30 60 80 100
newTree = BST()
20 40
AppMillers
www.appmillers.com
Insert a node to Binary Search Tree
10 70
Smaller Bigger
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Insert a node to Binary Search Tree
10 70
Smaller Bigger
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Insert a node to Binary Search Tree
95 70
Smaller Bigger
50 90
30 60 80 100
20 40
10
AppMillers
www.appmillers.com
Traversal of Binary Search Tree
30 60 80 100
20 40
AppMillers
www.appmillers.com
fi
fi
PreOrder Traversal of Binary Search Tree
70
Root Node
50 90
Left Subtree
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
PreOrder Traversal of Binary Search Tree
70
Root Node
50 90
Left Subtree
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
InOrder Traversal of Binary Search Tree
70
Left Subtree
50 90
Root Node
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
InOrder Traversal of Binary Search Tree
70
Left Subtree
50 90
Root Node
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Search Tree
70
Left Subtree
50 90
Right Subtree
30 60 80 100
Root Node
20 40
AppMillers
www.appmillers.com
PostOrder Traversal of Binary Search Tree
70
Left Subtree
50 90
Right Subtree
30 60 80 100
Root Node
20 40
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Search Tree
Level 1 70
Level 2 50 90
Level 3 30 60 80 100
Level 4 20 40
AppMillers
www.appmillers.com
LevelOrder Traversal of Binary Search Tree
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Search for a node in Binary Search Tree
40 70
50 90
30 60 80 100
20 40 Found
AppMillers
www.appmillers.com
Delete a node from Binary Search Tree
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Delete a node from Binary Search Tree
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Delete a node from Binary Search Tree
70
50 90
30 60 80 100
20
AppMillers
www.appmillers.com
Delete a node from Binary Search Tree
70
80
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Delete a node from Binary Search Tree
70
80
50 90
30 60 80 100
20 40 85
AppMillers
www.appmillers.com
Delete entire Binary Search Tree
rootNode = None
70
rootNode.leftChild = None
rootNode.rightChild = None
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Time and Space complexity of Binary Search Tree
AppMillers
www.appmillers.com
What is an AVL Tree?
An AVL tree is a self-balancing Binary Search Tree (BST) where the di erence between
heights of left and right subtrees cannot be more than one for all nodes.
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
ff
What is an AVL Tree?
An AVL tree is a self-balancing Binary Search Tree (BST) where the di erence between
heights of left and right subtrees cannot be more than one for all nodes.
70
Height of leftSubtree = 3
di erence = 1
Height of rightSubtree = 2 50 90
Height of leftSubtree = 1
di erence = 0
Height of rightSubtree = 1
30 80 100
Height of leftSubtree = 2
di erence = 2
Height of rightSubtree = 0
20 40
AppMillers
www.appmillers.com
ff
ff
ff
ff
What is an AVL Tree?
An AVL tree is a self-balancing Binary Search Tree (BST) where the di erence between
heights of left and right subtrees cannot be more than one for all nodes.
If at any time heights of left and right subtrees di er by more than one, then rebalancing is
done to restore AVL property, this process is called rotation
70
50 90
30 80 100
20 40
AppMillers
www.appmillers.com
ff
ff
Examples
Height of leftSubtree = 2
di erence = 0
Height of rightSubtree = 2
70
Height of leftSubtree = 1
di erence = 0
Height of rightSubtree = 1 50 90
Height of leftSubtree = 1
di erence = 0
Height of rightSubtree = 1
30 60 80 100
AppMillers
www.appmillers.com
ff
ff
ff
Examples
Height of leftSubtree =3
di erence =1 70
Height of rightSubtree = 2
Height of leftSubtree =2
di erence = 1
Height of rightSubtree = 1 50 90
Height of leftSubtree = 1
di erence = 0
Height of rightSubtree = 1
30 40 80 100
Height of leftSubtree = 1
di erence = 1
Height of rightSubtree = 0
20
AppMillers
www.appmillers.com
ff
ff
ff
ff
Examples
70
Height of leftSubtree = 4
di erence = 2
Height of rightSubtree = 2
50 90
30 40 80 100
20
10
AppMillers
www.appmillers.com
ff
Why do we need AVL Tree?
Search for 60
20
Time complexity is O(N)
30
40
50
60
70
AppMillers
www.appmillers.com
Why do we need AVL Tree?
10
Search for 60
20 40
40
10 30 50 70
50
60
70
AppMillers
www.appmillers.com
Common operations on AVL Trees
10 30 50 70
AppMillers
www.appmillers.com
Create AVL Tree
newAVL = AVL() 70
rooNode = None
leftChild = None
rightChild = None 50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
70
Root Node
50 90
Left Subtree
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
InOrder Traversal of AVL Tree
70
Left Subtree
50 90
Root Node
30 60 80 100
Right Subtree
20 40
AppMillers
www.appmillers.com
PostOrder Traversal of AVL Tree
70
Left Subtree
50 90
Right Subtree
30 60 80 100
Root Node
20 40
AppMillers
www.appmillers.com
LevelOrder Traversal of AVL Tree
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Search for a node in AVL Tree
80 70
50 90
30 60 80 100
Found
20 40
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60 80 100
20
10
AppMillers
www.appmillers.com
Insert a node in AVL Tree
75
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Insert a node in AVL Tree
30 60 80 100
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60 80 100
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60 80 100
Left
20
Left
10
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Right rotation 50 90
30 60 80 100
20
10
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
Left
30 60
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Right rotation - example 2
70 50
50 90 30 70
30 60 20 60 90
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Algorithm of Left Left (LL) Condition
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild None
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
20 20
30 newRoot =
newRoot =
10 10 30
20
disbalancedNode = 30
10
AppMillers
www.appmillers.com
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
AppMillers
www.appmillers.com
50 90
30 60 80 100
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
50 90
30 60 80 100
Left
20
Right
25
AppMillers
www.appmillers.com
Insert a node in AVL Tree
1. Left rotation 50 90
2. Right rotation
30 60 80 100
20
25
AppMillers
www.appmillers.com
Insert a node in AVL Tree
1. Left rotation 50 90
2. Right rotation
30 60 80 100
25
20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
LR - left right condition
1. Left rotation
2. Right rotation
70 70 70
50 90 50 90 50 90
20 25 20 30
25 20
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Algorithm of Left Right (LR) Condition
Step 1 : rotate Left disbalancedNode.leftChild
Step 2 : rotate Right disbalancedNode
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
AppMillers
www.appmillers.com
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
30
30 newRoot = 20
disbalancedNode = 20
disbalancedNode = 10
10
20 10
newRoot =
20 AppMillers
10 www.appmillers.com
20
30
20
newRoot =
newRoot =
10 30
20 10
10 disbalancedNode = 30
AppMillers
www.appmillers.com
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
40 60
65
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 60
Right
65
Right
70
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 60
Left rotation
65
70
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 65
Left rotation - example 2
60 70
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 65
Left rotation - example 2
Right
60 70
75
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 65
Left rotation - example 2
60 70
75
AppMillers
www.appmillers.com
Insert a node in AVL Tree
RR - right right condition
Left rotation
50 65
40 65 50 70
60 70 40 60 75
75
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Algorithm of Right Right (RR) Condition
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
40 40
30
newRoot =
disbalancedNode =
50
30 50
40
disbalancedNode = 30
50 AppMillers
www.appmillers.com
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
AppMillers
www.appmillers.com
40 60
70
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 60
Right
70
Left
65
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 60
1. Right rotation
2. Left rotation
70
65
AppMillers
www.appmillers.com
Insert a node in AVL Tree
40 60
1. Right rotation
2. Left rotation
65
70
AppMillers
www.appmillers.com
Insert a node in AVL Tree
Algorithm of Right Left (RL) Condition
Step 1 : rotate Right disbalancedNode.rightChild
Step 2 : rotate Left disbalancedNode
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
AppMillers
www.appmillers.com
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot 30
30 newRoot = 35
disbalancedNode = 35
disbalancedNode = 40
40
40
35
newRoot =
35 AppMillers
40 www.appmillers.com
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
35
35
30 newRoot =
newRoot =
30 40
40
35
disbalancedNode = 30
40
AppMillers
www.appmillers.com
rotateRight(disbalancedNode):
newRoot = disbalancedNode.leftChild
disbalancedNode.leftChild = disbalancedNode.leftChild.rightChild
newRoot.rightChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
rotateLeft(disbalancedNode):
newRoot = disbalancedNode.rightChild
disbalancedNode.rightChild = disbalancedNode.rightChild.leftChild
newRoot.leftChild = disbalancedNode
update height of disbalancedNode and newRoot
return newRoot
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
Left 25 35
Left 20
15
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
Left 20 35
15 25
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
Left 15 30
Left rotation
5 Right 25 35
Right rotation
10
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
10 30
Left rotation
5 15 25 35 Right
50 Right
60
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
10 30 Right
5 25 50 Right
15
35 60
70
AppMillers
www.appmillers.com
Insert a node in AVL Tree (all together)
10 50
Left rotation
5 30 60 Right
15
25 35 70 Right rotation
Left
65
AppMillers
www.appmillers.com
Delete a node from AVL Tree
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Delete a node from AVL Tree
70
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Delete a node from AVL Tree
70
50 90
30 60 80 100
20
AppMillers
www.appmillers.com
Delete a node from AVL Tree
70
80
50 90
30 60 80 100
20 40 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
50 90
30 60 80 100
20 40 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
Right rotation
50 90
Left
30 60 80 100
Left
20 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
50 90
Left
Left rotation
30 60 80 100
Right
20 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
Right rotation
50 90
30 60 80
20 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
50 90
Right
30 60 80 100
Right
70 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
50 90
Right
Right rotation
30 60 80 100
Left
55 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree
Left rotation
50 90
60 80 100
55 85
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
Right rotation
30 60 80 100
20 40 70 110
15
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
20 60 80 100
15 30 40 110
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
20 60 80 100
30 40 110
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
Left rotation
20 60 80 100
30 110
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
20 50 80 100
110
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
20 50 90 110
105
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
Right rotation
20 50 90 110
105
AppMillers
www.appmillers.com
Delete a node from AVL Tree (all together)
15
10 20
5 15
20
AppMillers
www.appmillers.com
Delete entire AVL Tree
rootNode = None
70
rootNode.leftChild = None
rootNode.rightChild = None
50 90
30 60 80 100
20 40
AppMillers
www.appmillers.com
Time and Space complexity of AVL Tree
AppMillers
www.appmillers.com
Binary Search Tree vs AVL
BST AVL
Create Tree O(1) O(1)
Insert a node Tree O(N) O(logN)
Traverse Tree O(N) O(N)
Search for a node Tree O(N) O(logN)
Delete node from Tree O(N) O(logN)
Delete Entire Tree O(1) O(1)
AppMillers
www.appmillers.com
What is a Binary Heap?
A Binary Heap is a Binary Tree with following properties.
- A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must
be minimum among all keys present in Binary Heap. The same property must be
recursively true for all nodes in Binary Tree.
- It’s a complete tree (All levels are completely lled except possibly the last level and the
last level has all keys as left as possible). This property of Binary Heap makes them
suitable to be stored in an array.
10 20
30 40 50 60
70 80
AppMillers
www.appmillers.com
fi
Why we need a Binary Heap?
Find the minimum or maximum number among a set of numbers in logN time. And also we want
to make sure that inserting additional numbers does not take more than O(logN) time
Possible Solutions
5 10 20 30 40 50
Tail 333
null
AppMillers
www.appmillers.com
Why we need a Binary Heap?
Find the minimum or maximum number among a set of numbers in logN time. And also we want
to make sure that inserting additional numbers does not take more than O(logN) time
Practical Use
- Prim’s Algorithm
- Heap Sort
- Priority Queue
AppMillers
www.appmillers.com
Types of Binary Heap
Min heap - the value of each node is less than or equal to the value of both its children.
Max heap - it is exactly the opposite of min heap that is the value of each node is more than or
equal to the value of both its children.
5 80
10 20 70 60
30 40 50 60 50 40 30 20
70 80 5 10
AppMillers
www.appmillers.com
Common operations on Binary Heap
30 40 50 60
Implementation Options
- Array Implementation
AppMillers
www.appmillers.com
Common operations on Binary Heap
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60
AppMillers
www.appmillers.com
Common operations on Binary Heap
- Creation of Binary Heap
Initialize xed size List
set size of Binary Heap to 0
0 1 2 3 4 5 6 7 8
AppMillers
www.appmillers.com
fi
Common operations on Binary Heap
- Peek of Binary Heap
5
Return List[1]
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60
AppMillers
www.appmillers.com
Common operations on Binary Heap
- Size Binary Heap
5
Return number of lled cells
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60
AppMillers
www.appmillers.com
fi
Common operations on Binary Heap
- Level Order Traversal
5
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60
AppMillers
www.appmillers.com
Insert a node to Binary Heap
5
1
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60
AppMillers
www.appmillers.com
Insert a node to Binary Heap
5
1
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
5 10 20 30
1 40 50 60 30
AppMillers
www.appmillers.com
Insert a node to Binary Heap
10 20
1 40 50 60
30
0 1 2 3 4 5 6 7 8
5 10
5 20 30
10
1 40 50 60 30
AppMillers
www.appmillers.com
Extract a node from Binary Heap
10 20
30 40 50 60
80
0 1 2 3 4 5 6 7 8
5 10 20 30 40 50 60 80
AppMillers
www.appmillers.com
Extract a node from Binary Heap
80
10 20
30 40 50 60
0 1 2 3 4 5 6 7 8
80 10 20 30 40 50 60
AppMillers
www.appmillers.com
Extract a node from Binary Heap
10
80 20
30 40 50 60
0 1 2 3 4 5 6 7 8
10 80 20 30 40 50 60
AppMillers
www.appmillers.com
Delete entire Binary Heap
customList = None 10
80 20
30 40 50 60
0 1 2 3 4 5 6 7 8
10 80 20 30 40 50 60
AppMillers
www.appmillers.com
Time and Space complexity of Binary Heap
AppMillers
www.appmillers.com
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
Properties:
I AIM
RT R L
AppMillers
www.appmillers.com
ffi
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
AIR
A
AppMillers
www.appmillers.com
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
AIT
A
RT
R
AppMillers
www.appmillers.com
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
BAR
A
AB
I A
RT
R R
AppMillers
www.appmillers.com
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
BIL
A
AB
I A
AI
RT
R R L
AppMillers
www.appmillers.com
What is a Trie?
A Trie is a tree-based data structure that organizes information in a hierarchy.
BM
A
AB
I A
AIM
AI
RT
R R L
AppMillers
www.appmillers.com
Why we need Trie?
To solve many standard problems in e cient way
- Spelling checker
- Auto completion
A
AB
I A
AIM
AI
RT
R R L
AppMillers
www.appmillers.com
ffi
Why we need Trie?
To solve many standard problems in e cient way
- Spelling checker
- Auto completion
A
AB
Map
RT
R R L
End of String
AppMillers
www.appmillers.com
ffi
Common operations on Trie
- Creation of Trie A
AB
- Insertion in Trie
- Search for a String in trie
- Deletion from Trie
I A
AIM
AI
RT
R R L
AppMillers
www.appmillers.com
Common operations on Trie
- Creation of Trie
Physically
Map
End of String
AppMillers
www.appmillers.com
Insert a string in a Trie
Case 1 : A Trie is Blank
APP
Dictionary
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
End of String = N
Characters Link to Trie Node
End of String = Y
AppMillers
www.appmillers.com
Insert a string in a Trie
Case 2: New string’s pre x is common to another strings pre x
API
Dictionary
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
End of String = N
Characters Link to Trie Node
P
I
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
AppMillers
End of String = Y www.appmillers.com
fi
fi
Insert a string in a Trie
Case 3: New string’s pre x is already present as complete string
APIS
Dictionary
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
End of String = N
Characters Link to Trie Node
P
I
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
S
Characters Link to Trie Node
AppMillers
End of String = Y www.appmillers.com
End of String = Y
fi
Insert a string in a Trie
Case 4: String to be inserted is already presented in Trie
APIS
Dictionary
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
End of String = N
Characters Link to Trie Node
P
I
Dictionary
End of String = N
Characters Link to Trie Node
Dictionary
S
Characters Link to Trie Node
AppMillers
End of String = Y www.appmillers.com
End of String = Y
Search for a string in a Trie
Case 1: String does not exist in Trie
BCD
B A
AppMillers
www.appmillers.com
Search for a string in a Trie
Case 2: String exists in Trie
API
A
Return : TRUE
AppMillers
www.appmillers.com
Search for a string in a Trie
Case 3: String is a pre x of another string, but it does not exist in a Trie
AP
A
Return : FALSE
AppMillers
www.appmillers.com
fi
Delete a string from Trie
Case 1: Some other pre x of string is same as the one that we want to delete. (API, APPLE)
I P
AppMillers
www.appmillers.com
fi
Delete a string from Trie
Case 2: The string is a pre x of another string. (API, APIS)
I P
S L
AppMillers
www.appmillers.com
fi
Delete a string from Trie
Case 3: Other string is a pre x of this string. (APIS, AP)
Dictionary
A
Characters Link to Trie Node
P End of String = N
Dictionary
I
Dictionary
End of String = N
Characters Link to Trie Node
I
S
End of String = Y
Dictionary Dictionary
A
AK Dictionary
K
P
Dictionary
End of String = N
Characters Link to Trie Node
I P
Dictionary Dictionary
End of String = N
AppMillers
www.appmillers.com
Practical use of Trie
- Auto completion
- Spelling checker
AppMillers
www.appmillers.com
What is Hashing?
Hashing is a method of sorting and indexing data. The idea behind hashing is to allow large
amounts of data to be indexed using keys commonly created by formulas
Magic function
Apple 18
Application 20
Appmillers 22
0 1 .. 18 19 20 21 22 23
.. Apple Application Appmillers
AppMillers
www.appmillers.com
Why Hashing?
It is time e cient in case of SEARCH Operation
Tree O(logN)
AppMillers
www.appmillers.com
ffi
Hashing Terminology
Hash function : It is a function that can be used to map of arbitrary size to data of xed size.
Key : Input data by a user
Hash value : A value that is returned by Hash Function
Hash Table : It is a data structure which implements an associative array abstract data type, a
structure that can map keys to values
Collision : A collision occurs when two di erent keys to a hash function produce the same
output.
Hash Function
Apple 18
0 1 .. 18 19 20 21 22 23
Hash function
ABCD 20
ABCDEF 20
ABCDEF
Collision
0 1 ..
..
18 19 💥
20
ABCD
21 22 23
AppMillers
www.appmillers.com
ff
fi
Hash Functions
Mod function
mod(400, 24) 16
mod(700, 24) 4
0 1 .. 4 5 .. 16 .. 23
.. 700 .. 400 ..
AppMillers
www.appmillers.com
Hash Functions
ASCII function
modASCII("ABC", 24) 6
A 65 65+66+67 = 198 24
192 8
B 66
6
C 67
0 1 .. 6 7 .. 16 .. 23
.. ABC .. ..
AppMillers
www.appmillers.com
Hash Functions
Hash function
ABCD 20
ABCDEF 20
ABCDEF
Collision
0 1 ..
..
18 19 💥
20
ABCD
21 22 23
AppMillers
www.appmillers.com
Hash Functions
ABCDEF
Hash function
ABC 18
Collision
0 1 ..
..
💥
18
ABCD
19 20 21 22 23
AppMillers
www.appmillers.com
Collision Resolution Techniques
Hash function
ABCD 0
2
💥
Collision
1
EFGH 2
2 ABCD EFGH
IJKLM 3
4
5
6
7
8
9
10
11
12
13
14
15
AppMillers
www.appmillers.com
Collision Resolution Techniques
Resolution Techniques
Linear Probing
Quadratic Probing
Double Hashing
AppMillers
www.appmillers.com
Collision Resolution Techniques
Direct Chaining : Implements the buckets as linked list. Colliding elements are stored in this lists
0
1
Hash function 2 111 ABCD 222
Null EFGH 333
Null IJKLM Null
ABCD 2 4
5
EFGH 2
6
IJKLM 2
7 444 Miller Null
Miller 7 444
8
9
10
11
12
13
14
15
AppMillers
www.appmillers.com
Collision Resolution Techniques
Open Addressing: Colliding elements are stored in other vacant buckets. During storage and
lookup these are found through so called probing.
Linear probing : It places new key into closest following empty cell
0
1
Hash function 2 ABCD
3 EFGH
ABCD 2 4 KLM
5
EFGH 2
6
IJKLM 2
7
8
9
10
11
12
13
14 AppMillers
www.appmillers.com
15
IJ
Collision Resolution Techniques
Open Addressing: Colliding elements are stored in other vacant buckets. During storage and
lookup these are found through so called probing.
Quadratic probing : Adding arbitrary quadratic polynomial to the index until an empty cell is found
0
1
Hash function 2 ABCD
3 2 + 4= 6
ABCD 2 4
2 + 4= 6
5
EFGH 2
6 EFGH 2 + (2*4) = 8
IJKLM 2
7
8 KLM
9
Hash 2
10
11
EFGH 4 12
13
IJKLM 4
14 AppMillers
www.appmillers.com
15
IJ
Hash Table is Full
Direct Chaining
This situation will never arise.
Hash function
222 555
IJKLM 3 2 333 ABCD Null
NOPQ 0 333
3 444 IJKLM
RSTU 1 Null
444
AppMillers
www.appmillers.com
Hash Table is Full
Open addressing
Create 2X size of current Hash Table and recall hashing for current keys
Hash function
0 NOPQ 0 NOPQ
ABCD 2
EFGH 1
1 EFGH 1 EFGH
AppMillers
www.appmillers.com
Pros and Cons of Collision resolution techniques
Direct chaining
- Hash table never gets full
- Huge Linked List causes performance leaks (Time complexity for search operation becomes O(n).)
Open addressing
- Easy Implementation
- When Hash Table is full, creation of new Hash table a ects performance (Time complexity for
search operation becomes O(n).)
AppMillers
www.appmillers.com
ff
Pros and Cons of Collision resolution techniques
Hash function
AppMillers
www.appmillers.com
Personal Computer
Practical Use of Hashing
Login : [email protected]
Password: 123456
Google Servers
Hash value: *&71283*a12
AppMillers
www.appmillers.com
fi
Practical Use of Hashing
AppMillers
www.appmillers.com
fi
Practical Use of Hashing
File system : File path is mapped to physical location on disk
Path: /Documents/Files/hashing.txt
1 /Documents/
Files/hashing.txt Physical location: sector 4
3
AppMillers
www.appmillers.com
Pros and Cons of Hashing
x When Hash function is not good enough Insertion/Deletion/Search operations take O(n) time
AppMillers
www.appmillers.com
What is Sorting?
AppMillers
www.appmillers.com
fi
What is Sorting?
AppMillers
www.appmillers.com
fi
What is Sorting?
Practical Use of Sorting
Microsoft Excel : Built in functionality to sort data
Online Stores: Online shopping websites generally have option sor sorting by price,
review, ratings..
AppMillers
www.appmillers.com
Types of Sorting?
Sorting
AppMillers
www.appmillers.com
Space used
In place sorting : Sorting algorithms which does not require any extra space for sorting
Example : Bubble Sort
70 10 80 30 20 40 60 50 90
10 20 30 40 50 60 70 80 90
Out place sorting : Sorting algorithms which requires an extra space for sorting
Example : Merge Sort
70 10 80 30 20 40 60 50 90
10 20 30 40 50 60 70 80 90
AppMillers
www.appmillers.com
Stability
Stable sorting : If a sorting algorithm after sorting the contents does not change the
sequence of similar content in which they appear, then this sorting is called stable
sorting.
70 10 80 40 20 40 60 50 90
10 20 40 40 50 60 70 80 90
UnStable sorting : If a sorting algorithm after sorting the content changes the sequence
of similar content in which they appear, then it is called unstable sort.
Example : Quick Sort
70 10 80 40 20 40 60 50 90
10 20 40 40 50 60 70 80 90
AppMillers
www.appmillers.com
Stability
UnStable sorting example
Unsorted data Sorted by name Sorted by age (stable) Sorted by age (unstable)
Name Age Name Age Name Age Name Age
Renad 7 Nick 6 Nick 6 Nick 6
Nick 6 Parker 7 Richard 6 Richard 6
{
Richard 6 Renad 7 Parker 7 Renad 7
Parker 7 Richard 6 Renad 7 Parker 7
So a 7 So a 7 So a 7 So a 7
AppMillers
www.appmillers.com
fi
fi
fi
fi
Sorting Terminology
Increasing Order
- If successive element is greater than the previous one
- Example : 1, 3, 5, 7, 9 ,11
Decreasing Order
- If successive element is less than the previous one
- Example : 11, 9, 7, 5, 3, 1
Bubble sort
Selection sort
Insertion sort
Bucket sort
Merge sort
Quick sort
Heap sort
- Stability
- Space e cient
- Time e cient
AppMillers
www.appmillers.com
ffi
ffi
Bubble Sort
5 9 3 1 2 8 4 7 6
AppMillers
www.appmillers.com
Bubble Sort
5 3 1 2 8 4 7 6 9
AppMillers
www.appmillers.com
Bubble Sort
3 1 2 5 4 7 6 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Bubble Sort
AppMillers
www.appmillers.com
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
5
1 7 4 3 8 6 1 9 2
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 7
2 4 3 8 6 5 9 2
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 4
3 3 8 6 5 9 7
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 8 6 5 9 7
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5
8 6 5 9 7
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5 6 8 9 7
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5 6 7
8 9 7
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5 6 7 9
8 8
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5 6 7 8 9
min
AppMillers
www.appmillers.com
fi
Selection Sort
- In case of selection sort we repeatedly nd the minimum element and
move it to the sorted part of array to make unsorted part sorted.
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
fi
Selection Sort
AppMillers
www.appmillers.com
ffi
Insertion Sort
- Divide the given array into two part
- Take rst element from unsorted array and nd its correct position in
sorted array
- Repeat until unsorted array is empty
3
2
5 3
4 4 7 2 8 6 9 1
AppMillers
www.appmillers.com
fi
fi
Insertion Sort
- Divide the given array into two part
- Take rst element from unsorted array and nd its correct position in
sorted array
- Repeat until unsorted array is empty
2 3 4 5 7
6 8 6 9 1
AppMillers
www.appmillers.com
fi
fi
Insertion Sort
- Divide the given array into two part
- Take rst element from unsorted array and nd its correct position in
sorted array
- Repeat until unsorted array is empty
2
1 3 4 5 6 7 8 9 1
AppMillers
www.appmillers.com
fi
fi
Insertion Sort
AppMillers
www.appmillers.com
ffi
fl
Bucket Sort
5 3 4 7 2 8 6 9 1
AppMillers
www.appmillers.com
Bucket Sort
3 4 7 2 8 6 9 1
5
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
7 2 8 6 9 1
3 5 4
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
8 6 9 1
3 2 5 4 7
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
9 1
3 2 5 4 6 7 8
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
3 2 1 5 4 6 7 8 9
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
1 2 3 4 5 6 7 8 9
Bucket 1 Bucket 2 Bucket 3
AppMillers
www.appmillers.com
Bucket Sort
AppMillers
www.appmillers.com
Merger Sort
AppMillers
www.appmillers.com
Merge Sort
6 4 3 7 5 1 2
AppMillers
www.appmillers.com
Merge Sort
6 4 3 7 5 1 2
AppMillers
www.appmillers.com
Merge Sort
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
70 10 80 30 90 40 60 20 50 10 20 30 40 50 80 60 70 90
10 30 40 20 50 80 60 70 90 10 20 30 40 50 60 70 80 90
10 20 40 30 50 80 60 70 90 10 20 30 40 50 60 70 80 90
10 20 30 40 50 80 60 70 90 10 20 30 40 50 60 70 80 90
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
3 5 8 1 2 9 4 7 6
L L R R P
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
3 5 4 1 2 9 8 7 6
L LLR R P
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
3 5 4 1 2 6 8 7 9
L L R R P
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
1 2 4 3 5 6 8 7 9
L R LPP
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
1 2 3
4 3
4 5 6 8 7 9
L R P L LRR LPP
AppMillers
www.appmillers.com
Quick Sort
- Quick sort is a divide and conquer algorithm
- Find pivot number and make sure smaller numbers located at the left of pivot
and bigger numbers are located at the right of the pivot.
- Unlike merge sort extra space is not required
1 2 3 4 5 6 7
8 7
8 9
L R P
AppMillers
www.appmillers.com
Quick Sort
AppMillers
www.appmillers.com
Heap Sort
10 20
30 40 50 60
AppMillers
www.appmillers.com
70 80
Heap Sort
15 10 40 20 50 10 30 45 5
15
10 40
20 50 10 30
AppMillers
www.appmillers.com
Heap Sort
15 10 40 20 50 10 30 45 5
10
15 10
20 50 40 30
45 5
AppMillers
www.appmillers.com
Heap Sort
5 10
10 10
15 50 40 30
45 20
AppMillers
www.appmillers.com
Heap Sort
5 10 10 15 20 30
10
15 30
20 50 40 45
AppMillers
www.appmillers.com
Heap Sort
5 10 10 15 20 30 40 45 50
40
45 50
AppMillers
www.appmillers.com
Sorting Algorithms
AppMillers
www.appmillers.com
What is a graph? Why do we need it?
Graph Terminologies
Topological Sorting
All pairs shortest path (BFS, D kstra, Bellman Ford and Floyd Warshall algorithms)
AppMillers
www.appmillers.com
ij
ij
What is Graph?
Graph consists of a nite set of Vertices(or nodes) and a set of Edges which
connect a pair of nodes.
Node
A D
Edge
B F
C
K
AppMillers
www.appmillers.com
fi
Why Graph?
AppMillers
www.appmillers.com
Graph Terminology
V1 V3
V5
V2 V4
AppMillers
www.appmillers.com
Graph Terminology
V1 V3
8 12 V5
V2 V4
AppMillers
www.appmillers.com
Graph Terminology
V1 V3
V5
V2 V4
AppMillers
www.appmillers.com
Graph Terminology
V1 V3
V5
V2
AppMillers
www.appmillers.com
Graph Terminology
V1
V2 V3
V5 AppMillers
www.appmillers.com
Graph Types
Graph
Directed Undirected
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
V1 V3
V5
V2 V4
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
2. Unweighted - directed
V1 V3
V5
V2 V4
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
2. Unweighted - directed
3. Positive - weighted - undirected
3
V1 V3
2
5
4 V5
3
V2 V4
3
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
2. Unweighted - directed
3. Positive - weighted - undirected
4. Positive - weighted - directed
3
V1 V3
2
5
4 V5
3
V2 V4
3
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
2. Unweighted - directed
3. Positive - weighted - undirected
4. Positive - weighted - directed
5. Negative - weighted - undirected
-3
V1 V3
2
-5
4 V5
3
V2 V4
3
AppMillers
www.appmillers.com
Graph Types
1. Unweighted - undirected
2. Unweighted - directed
3. Positive - weighted - undirected
4. Positive - weighted - directed
5. Negative - weighted - undirected
2
-5
4 V5
3
V2 V4
3 AppMillers
www.appmillers.com
Graph Representation
Adjacency Matrix : an adjacency matrix is a square matrix or you can say it is a 2D array. And
the elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph
A B C D E
A B
A 0 1
0 1
0 1
0 0
B 1
0 0 0 0 1
0
E
0
C 1 0 0 0
1 0
C D
0
D 1 0 0
1 0 0
1
E 0 1
0 0 1
0 0
AppMillers
www.appmillers.com
Graph Representation
Adjacency List : an adjacency list is a collection of unordered list used to represent a graph.
Each list describes the set of neighbors of a vertex in the graph.
A B C D
A B
B A E
E C A D
D A C E
C D B D
E
AppMillers
www.appmillers.com
Graph Representation
If a graph is complete or almost complete we should use Adjacency Matrix
If the number of edges are few then we should use Adjacency List
A B C D E
A B C D
A 0 1
0 1
0 1
0 0
B A E
B 1
0 0 0 0 1
0
C A D
0
C 1 0 0 0
1 0
D A C E
0
D 1 0 0
1 0 0
1
E B D
E 0 1
0 0 1
0 0
A B
AppMillers
www.appmillers.com
C D
Graph Representation
Python Dictionary implementation
A B { A : [B, C, D],
B: [A, E],
C: [A,D],
E
D: [A,C,E],
E: [B,D] }
C D
AppMillers
www.appmillers.com
Graph in Python
Dictionary implementation
{ A : [B, C],
B: [A, D, E],
B C
C: [A,E],
D: [B,E,F],
E: [C,D,F],
F: [D, E]}
D E
AppMillers
www.appmillers.com
Graph Traversal
It is a process of visiting all vertices in a given Graph
C D G
E F
AppMillers
www.appmillers.com
Breadth First Search
BFS is an algorithm for traversing Graph data structure. It starts at some arbitrary node of a
graph and explores the neighbor nodes (which are at current level) rst, before moving to the
next level neighbors.
Level 1 A B
Level 2 C D G
Level 3 E F
AppMillers
www.appmillers.com
fi
Breadth First Search Algorithm
BFS
A B
enqueue any starting vertex
while queue is not empty
p = dequeue()
if p is unvisited
mark it visited
enqueue all adjacent C D G
unvisited vertices of p
A B C D G E F
E F
Queue A B C D G E F F F
AppMillers
www.appmillers.com
A B
C D G
E F
AppMillers
www.appmillers.com
Depth First Search Algorithm
Stack
DFS A B
G
push any starting vertex
while stack is not empty
B
p = pop()
if p is unvisited
mark it visited D
Push all adjacent C D G
unvisited vertices of p G
A C E F D B G E
E F
A
AppMillers
www.appmillers.com
BFS vs DFS
Level 1 A B A B
G C D G
Level 2 C D
Level 3 E F E F
BFS DFS
AppMillers
www.appmillers.com
BFS vs DFS
BFS DFS
How does it work internally? It goes in breath rst It goes in depth rst
AppMillers
www.appmillers.com
fi
fi
Topological Sort
Topological Sort: Sorts given actions in such a way that if there is a dependency of one action
on another, then the dependent action always comes later than its parent action.
Buy
breakfast
Exercise fruits
Prepare
Breakfast
Bath
Wash
dishes
Breakfast
Work
AppMillers
www.appmillers.com
Topological Sort Algorithm
Stack
ABCDEHFG A
E
BACDEHFG C
E H F G
BDACEFGH
F
H
AppMillers
www.appmillers.com
5
London Barcelona 10
35
London Barcelona 10
Berlin
30
20 10
Berlin
10
AppMillers
www.appmillers.com
ff
ffi
ff
fi
ffi
Single Source Shortest Path Problem
- BFS
- Dijkstra’s Algorithm
- Bellman Ford
A
Level 1 A B
B C
Level 2 C D G
Level 3 E F
AppMillers
www.appmillers.com
BFS for SSSP
BFS
null
A
enqueue any starting vertex
A
while queue is not empty B
p = dequeue()
if p is unvisited
mark it visited B B
A
enqueue all adjacent unvisited vertices of p C D G
update parent of adjacent vertices to curVertex
A B C D G E F C D
E F
Queue A B C D G E F F F
AppMillers
www.appmillers.com
Unweighted - undirected OK
Unweighted - directed OK
AppMillers
www.appmillers.com
Why BFS not work with weighted graph
10 50
A B C A
30 5 9 30
B 6 B
D E F G
7 20
H I
AppMillers
www.appmillers.com
Why does DFS not work with SSSP?
DFS has the tendency to go “as far as possible” from source, hence it can never nd “Shortest Path”
B C
D E F
AppMillers
www.appmillers.com
fi
Dijkstra’s Algorithm for SSSP
min min
B∞
Bv2
Bv 3 E∞
Ev5
Ev
2 1 4 9
min
A
Av0 6 D∞
Dv3
Dv G∞
Gv14
Gv
5 7
C∞
Cv5
Cv 8 F13
∞
Fv13
Fv
min min
AppMillers
www.appmillers.com
Dijkstra’s Algorithm with negative cycle
A 3
B
4
-6 1
6
E
1 2
C D
1 + 3 + (-6) = -2
AppMillers
www.appmillers.com
Dijkstra’s Algorithm with negative cycle
3 Path from A to B = 6 + 1 = -5
A B
= -5+3+(-6)+1 = -7
4
-6 = -7+3+(-6)+1 = -9
6 1
E = -9+3+(-6)+1 = -11
1 2
C D
AppMillers
www.appmillers.com
fi
Bellman Ford Algorithm
Unweighted - undirected OK OK OK
Unweighted - directed OK OK OK
Negative Cycle X X OK
AppMillers
www.appmillers.com
Bellman Ford Algorithm
Bellman Ford algorithm is used to nd single source shortest path problem. If there is a
negative cycle it catches it and report its existence.
A 3
B
4
6 1
6
E
1 2
C D
AppMillers
www.appmillers.com
fi
Bellman Ford Algorithm
∞ ∞
A 3 B
If the distance of destination vertex > (distance of
4
6 0 source vertex + weight between source and destination
6 1 vertex):
E
Update distance of destination vertex to (distance of
1 2
C D source vertex + weight between source and destination
∞ 2 ∞ vertex)
AppMillers
www.appmillers.com
E->B 4 DD ∞ ∞ 2 E
E->D 2 EE 0 0 0 -
AppMillers
www.appmillers.com
E->B 4 D ∞
∞ 22 EE 2 E
E->D 2 E 00 00 -- 0 -
AppMillers
www.appmillers.com
E->B 4 D ∞ 2 E 2 EE 2 E
E->D 2 E 0 0 - 0 -- 0
AppMillers
www.appmillers.com
E->B 4 D ∞ 2 E 2 E 2 E 2 E
E->D 2 E 0 0 - 0 - 0 - 0 -
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
E->B 4 D ∞ 2 E
E->D 2 E 0 0 -
AppMillers
www.appmillers.com
E->B 4 D ∞ 2 E 2 E
E->D 2 E 0 0 - 0 -
AppMillers
www.appmillers.com
E->B 4 D ∞ 2 E 2 E 7+(-6)=1 A
E->D 2 E 0 0 - 0 - 0
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
Edge Weight
A->C 6
Distance Matrix
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Vertex Distance
Distance Parent Distance Parent Distance Parent Distance Parent Distance Parent
A ∞ ∞ - 4+3=7 B 3+3=6 B 6 B 4 B
B ∞ 4 E 2+1=3 D 3 D 3 D 0 D
C ∞ ∞ - 2+2=4 D 4 D 4 D 0 D
D ∞ 2 E 2 E 7+(-6)=1 A 6+(-6)=0 A 1 A
E 0 0 - 0 - 0 - 0 -
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
∞
76 ∞
43
A 3 B
A
10 20 30 40
B C D E
4
-6 0
6 1
E
60
∞ 50
∞ 30
∞ 0
1 2 10 20 30
C D A B C D
∞ 2 ∞
A->B
B->C
C->D
AppMillers
www.appmillers.com
BFS vs Dijkstra vs Bellman Ford
Unweighted - undirected OK OK OK
Unweighted - directed OK OK OK
Negative Cycle X X OK
AppMillers
www.appmillers.com
BFS vs Dijkstra vs Bellman Ford
X OK OK
Weighted graph Use as time complexity is Not use as time complexity
Not supported
better than Bellman is bad
X X OK
Negative Cycle Use this as others not
Not supported Not supported
support
AppMillers
www.appmillers.com
All pair shortest path problem
What is single source shortest path?
A single source problem is about nding a path between a given vertex (called source) to all
other vertices in a graph such that the total distance between them (source and destination) is
minimum.
5
London Barcelona 10
35
London Barcelona 10
Berlin
30
20 10
Berlin
10
AppMillers
www.appmillers.com
ff
ffi
ff
fi
ffi
All pair shortest path problem
All pair shortest path problem is about nding a path between every vertex to all other vertices
in a graph such that the total distance between them (source and destination) is minimum.
The problem:
- Five o ces in di erent cities.
- Travel costs between these cities are known.
- Find the cheapest way to reach each o ce from
every other o ce
Paris
10 Rome
5
35
London Barcelona 10
30
20
Berlin
10
AppMillers
www.appmillers.com
ffi
ffi
ff
ffi
fi
All pair shortest path problem
Paris Paris Paris
10 Rome 10 Rome 10 Rome
5 35 5 5
20 30 20
Berlin Berlin Berlin
10 10
5 35 5 35 5 35
London Barcelona 10 London Barcelona 10 London Barcelona 10
20 20 20
Berlin Berlin Berlin
AppMillers
www.appmillers.com
Dry run for All pair shortest path problem
6
∞ ∞
3
4
A 3 Source Vertex E Path
B
A E->D->B->A
4
6 0
6 1 B E->D->B
E
1 2 C E->D->C
C D
∞
2 2 ∞
2 D E->D
E -
Dijkstra
AppMillers
www.appmillers.com
Dry run for All pair shortest path problem
4
∞ ∞
1
A 3 Source Vertex E Path Source Vertex D Path
B
A E->D->B->A A D->B->A
4
6 ∞
6 1 B E->D->B B D->B
E
1 2 C E->D->C C D->C
C D
∞
2 2 0 D E->D D -
E - E N/A
Dijkstra
AppMillers
www.appmillers.com
Dry run for All pair shortest path problem
E - E N/A
Dijkstra , BFS and Bellmand Ford
A C->D->B->A A B->A A -
B C->D->B B - B A->D->B
C - C B->A->C C A->D->C
AppMillers
www.appmillers.com
Floyd Warshall
A 8 Given Iteration 1
B
A B C D via A A B C D
4 A 0 8 ∞ 1 A 0 8 ∞ 1
1 1 B ∞ 0 1 ∞ B ∞ 0 1 ∞
2 C 4 ∞ 0 ∞ C 4 4+8=12 0 4+1=5
D C D ∞ 2 9 0 D ∞ 2 9 0
9
C -> B
If D[C][B] > D[C][A] + D[A][B]:
D[C][B] = D[C][A] + D[A][B]
∞ > 4 + 8 = 12
C -> D
If D[C][D] > D[C][A] + D[A][D]:
D[C][D] = D[C][A] + D[A][D]
AppMillers
www.appmillers.com
∞ > 4 + 1 = 5
Floyd Warshall
A 8 Given Iteration 1
B
A B C D via A A B C D
4 A 0 8 ∞ 1 A 0 8 ∞ 1
1 1 B ∞ 0 1 ∞ B ∞ 0 1 ∞
2 C 4 ∞ 0 ∞ C 4 4+8=12 0 4+1=5
D C D ∞ 2 9 0 D ∞ 2 9 0
9
∞ > 8 + 1 = 9
D -> C
If D[D][C] > D[D][B] + D[B][C]:
D[D][C] = D[D][B] + D[B][C]
AppMillers
www.appmillers.com
9 > 2 + 1 = 3
Floyd Warshall
A 8 Given Iteration 1
B
A B C D via A A B C D
4 A 0 8 ∞ 1 A 0 8 ∞ 1
1 1 B ∞ 0 1 ∞ B ∞ 0 1 ∞
2 C 4 ∞ 0 ∞ C 4 4+8=12 0 4+1=5
D C D ∞ 2 9 0 D ∞ 2 9 0
9
C 4 12 0 5 C 4 12 0 5
D ∞ 2 2+1=3 0 D 3+4=7 2 3 0
C 4 12 0 5 C 4 5+2=7 0 5 C 4 7 0 5
D 3+4=7 2 3 0 D 7 2 3 0 D 7 2 3 0
A -8
B -8+1+4=-3
4
1 1
2
D C
9
- To go through cycle we need to go via negative cycle participating vertex at least twice
AppMillers
www.appmillers.com
Which algorithm to use for APSP?
Unweighted - undirected OK OK OK OK
Unweighted - directed OK OK OK OK
Negative Cycle X X OK X
AppMillers
www.appmillers.com
Which algorithm to use for APSP?
X OK OK OK
Weighted graph Not use as time Can be preferred as
Not supported Can be used complexity is bad
implementation easy
X X OK X
Negative Cycle Use this as others not
Not supported Not supported No supported
support
AppMillers
www.appmillers.com
Minimum Spanning Tree
A Minimum Spanning Tree (MST) is a subset of the edges of connected, weighted and undirected graph which :
- Connects all vertices together
- No cycle
- Minimum total edge
5 5
10 10
20 15 15
35
25
10 10
AppMillers
www.appmillers.com
fi
ff
Minimum Spanning Tree
Real life problem
10
35 20 15
25
10
5 5
10 10
15 20 15
10
AppMillers
www.appmillers.com
Disjoint Set
It is a data structure that keeps track of set of elements which are partitioned into a number of
disjoint and non overlapping sets and each sets have representative which helps in identifying
that sets.
- Make Set
- Union
- Find Set
AppMillers
www.appmillers.com
Disjoint Set
makeSet(N) : used to create initial set
union(x,y): merge two given sets
ndSet(x): returns the set name in which this element is there
A B C D E
union(A,B)
ndSet(B)
AB C D E
union(A, E)
ABE C D ndSet(E)
AppMillers
www.appmillers.com
fi
fi
fi
Kruskal’s Algorithm
It is a greedy algorithm
It nds a minimum spanning tree for weighted undirected graphs in two ways
- Add increasing cost edges at each step
- Avoid any cycle at each step
A 5 B A 5 B
15 15
E 13 10 E
8 8
20 6 6
C D C D
AppMillers
www.appmillers.com
fi
Kruskal’s Algorithm Pseudocode
Kruskal(G):
A 5 B
for each vertex:
makeSet(v) 15
sort each edge in non decreasing order by weight
E 13 10
for each edge (u, v): 8
if findSet(u) ≠ findSet(v):
union(u, v) 20 6
cost = cost + edge(u,v) C D
Cost = 0 +5 +6 +8 +15=34
A 5 B
15
E 8
6
C D
A
AB
ABCD
ABCDE B CD
C D E
AppMillers
www.appmillers.com
Kruskal(G):
for each vertex:
makeSet(v) O(v)
sort each edge in non decreasing order by weight O(eloge)
}
for each edge (u, v): O(e)
if findSet(u) ≠ findSet(v): O(1)
union(u, v) O(ev)
O(v)
cost = cost + edge(u,v) O(1)
AppMillers
www.appmillers.com
Prims Algorithm
It is a greedy algorithm
It nds a minimum spanning tree for weighted undirected graphs in following ways
1. Take any vertex as a source set its weight to 0 and all other vertices’ weight to in nity
2. For every adjacent vertices if the current weight is more than current edge then we set it
to current edge
3. Then we mark current vertex as visited
4. Repeat these steps for all vertices in increasing order of weight
10 5
∞
10 5
∞
5 B D
B D
10 0
0
30
15 A
A 8
20
6 C E
C E
6 8
∞
15
20
6 ∞
8
AppMillers
www.appmillers.com
fi
fi
Kruskal vs Prim’s
Kruskal
- Concentrates on Edges
- Finalize edge in each iteration
A 5
5 5 A 5 B
A 5 B
A B A B B
15
15
E
10 8
E 13 8
8
C
6 D 6
20 C
6 D
C D
C
6 D
Prim’s
- Concentrates on Vertices
- Finalize Vertex in each iteration
A
5 A 5 A 5 A 5 A 5
B B B B B
15 15 15 15 15
E 13 10 E 13 10 E 13 10 E 13 10 E 13 10
8 8 8 8 8
20 20 20 20 20
C
6 D C
6 D C
6 D C
6 D C
6 D
AppMillers
www.appmillers.com
Kruskal vs Prim’s
Kruskal
- Concentrates on Edges
- Finalize edge in each iteration
A 5
5 5 A 5 B
A 5 B
A B A B B
15
15
E
10 8
E 13 8
8
C
6 D 6
20 C
6 D
C D
C
6 D
Prim’s
- Concentrates on Vertices
- Finalize Vertex in each iteration
A
5 A 5 A 5 A 5 A 5
B B B B B
15 15 15 15 15
E 13 10 E 13 10 E 13 10 E 13 10 E 13 10
8 8 8 8 8
20 20 20 20 20
C
6 D C
6 D C
6 D C
6 D C
6 D
AppMillers
www.appmillers.com
Kruskal vs Prim’s
Kruskal Applications
- Landing cables
- TV Network
- Tour Operations
- LAN Networks
- A network of pipes for drinking water or natural gas.
- An electric grid
- Single-link Cluster
Prim’s Applications
- Network for roads and Rail tracks connecting all the cities.
- Irrigation channels and placing microwave towers
- Designing a ber-optic grid or ICs.
- Traveling Salesman Problem.
- Cluster analysis.
- Path nding algorithms used in AI(Arti cial Intelligence).
AppMillers
www.appmillers.com
fi
fi
fi
What is Greedy Algorithm?
- It is an algorithmic paradigm that builds the solution piece by piece
- In each step it chooses the piece that o ers most obvious and immediate bene t
- It ts perfectly for those solutions in which local optimal solutions lead to global solution
Global solution
Local solutions
AppMillers
www.appmillers.com
fi
ff
fi
What is Greedy Algorithm?
- Insertion Sort
- Selection Sort
- Topological Sort
- Prim’s Algorithm
- Kruskal Algorithm
AppMillers
www.appmillers.com
Greedy Algorithms
- Insertion Sort
- Selection Sort
- Topological Sort
- Prim’s Algorithm
- Kruskal Algorithm
AppMillers
www.appmillers.com
Greedy Algorithms
Insertion Sort
5 3 4 7 2 8 6 9 1
2 3 4 5 7 8 6 9 1
AppMillers
www.appmillers.com
Greedy Algorithms
Selection Sort
5 7 4 3 8 6 1 9 2
1 2 3 4 8 6 5 9 7
min
AppMillers
www.appmillers.com
Greedy Algorithms
Topological Sort
Stack
A
A
ACEH E
C
H
AppMillers
www.appmillers.com
Greedy Algorithms
Prims Algorithm
It is a greedy algorithm
It nds a minimum spanning tree for weighted undirected graphs in following ways
1. Take any vertex as a source set its weight to 0 and all other vertices’ weight to in nity
2. For every adjacent vertices if the current weight is more than current edge then we set it
to current edge
3. Then we mark current vertex as visited
4. Repeat these steps for all vertices in increasing order of weight
10 5
∞
10 5
∞
5 B D
B D
10 0
0
30
15 A
A 8
20
6 C E
C E
6 8
∞
15
20
6 ∞
8
AppMillers
www.appmillers.com
fi
fi
Greedy Algorithms
Kruskal’s Algorithm
It is a greedy algorithm
It nds a minimum spanning tree for weighted undirected graphs in two ways
- Add increasing cost edges at each step
- Avoid any cycle at each step
A 5 B A 5 B
15 15
E 13 10 E
8 8
20 6 6
C D C D
AppMillers
www.appmillers.com
fi
Activity selection problem
Given N number of activities with their start and end times. We need to select the maximum
number of activities that can be performed by a single person, assuming that a person can
only work on a single activity at a time.
Activity A1 A2 A3 A4 A5 A6
Start 0 3 1 5 5 8 2 Activities
Finish 6 4 2 8 7 9
Activity A3 A2 A1 A5 A4 A6
Start 1 3 0 5 5 8 4 Activities
Finish 2 4 6 7 8 9
AppMillers
www.appmillers.com
Activity selection problem
AppMillers
www.appmillers.com
You are given coins of di erent denominations and total amount of money. Find the minimum
number of coins that you need yo make up the given amount.
In nite supply of denominations : {1,2,5,10,20,50,100,1000}
Example 1
Total amount : 70
Answer: 2 —> 50 + 20 = 70
Example 2
AppMillers
www.appmillers.com
fi
ff
Coin Change Problem
You are given coins of di erent denominations and total amount of money. Find the minimum
number of coins that you need yo make up the given amount.
AppMillers
www.appmillers.com
fi
ff
Coin Change Problem
Find the biggest coin that is less than given total number
Add coin to the result and subtract coin from total number
If V is equal to zero:
Then print result
else:
Repeat Step 2 and 3
AppMillers
www.appmillers.com
10 kg, Value : 20
20 kg, Value : 10
30 kg
10 kg, Value : 30
AppMillers
www.appmillers.com
Fractional Knapsack Problem
Given a set of items, each with a weight and a value, determine the number of each item to
include in a collection so that the total weight is less than or equal to a given limit and the
total value is as large as possible.
100 / 20 = 5 120 / 30 = 4 60 / 10 = 6
AppMillers
www.appmillers.com
50 kg
Fractional Knapsack Problem
Given a set of items, each with a weight and a value, determine the number of each item to
include in a collection so that the total weight is less than or equal to a given limit and the
total value is as large as possible.
60 / 10 = 6 100 / 20 = 5 120 / 30 = 4
AppMillers
www.appmillers.com
50 kg
Fractional Knapsack Problem
Take items with the highest ratio sequentially until weight allows
AppMillers
www.appmillers.com
What is Divide and Conquer Algorithm?
Divide and conquer is an algorithm design paradigm which works by recursively breaking down a
problem into subproblems of similar type, until these become simple enough to be solved directly. The
solutions to the subproblems are then combined to give a solution to the original problem.
Website
Func 1 Func 1
Func 2 Func 2
Func 3 Func 3
Func 4 Func 4
AppMillers
www.appmillers.com
What is Divide and Conquer Algorithm?
Problem
Solution to Problem
AppMillers
www.appmillers.com
Property of Divide and Conquer Algorithm
Optimal Substructure:
If any problem’s overall optimal solution can be constructed from the optimal solutions of its
subproblem then this problem has optimal substructure
AppMillers
www.appmillers.com
ff
Common Divide and Conquer Algorithms
Merge Sort
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Merge Sort
6 4 3 7 5 1 2
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Merge Sort
6 4 3 7 5 1 2
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
3 5 8 1 2 9 4 7 6
L L R R P
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
3 5 4 1 2 9 8 7 6
L LLR R P
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
3 5 4 1 2 6 8 7 9
L L R R P
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
1 2 4 3 5 6 8 7 9
L R LPP
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
1 2 3
4 3
4 5 6 8 7 9
L R P L LRR LPP
AppMillers
www.appmillers.com
Common Divide and Conquer Algorithms
Quick Sort
1 2 3 4 5 6 7
8 7
8 9
L R P
AppMillers
www.appmillers.com
Fibonacci Series
De nition : a series of numbers in which each number is the sum of the two preceding numbers. First
two numbers by de nition are 0 and 1.
AppMillers
www.appmillers.com
fi
fi
Fibonacci Series
De nition : a series of numbers in which each number is the sum of the two preceding numbers. First
two numbers by de nition are 0 and 1.
Example : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ….
Fib(6)
Fib(4)
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2)
Fib(2) Fib(1)
AppMillers
www.appmillers.com
fi
fi
Fibonacci Series
De nition : a series of numbers in which each number is the sum of the two preceding numbers. First
two numbers by de nition are 0 and 1.
Fibonacci(N):
If n < 1 return error message
If n = 1 return 0
If n = 2 return 1
Else
return Fibonacci(N-1) + Fibonacci(N-2)
AppMillers
www.appmillers.com
fi
fi
Number Factor
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
Example 1
- N=4
- Number of ways = 4
- Explanation : There are 4 ways we can express N. {4},{1,3},{3,1},{1,1,1,1}
Example 2
- N=5
- Number of ways = 6
- Explanation : There are 6 ways we can express N. {4,1},{1,4},{1,3,1},{3,1,1},{1,1,3},{1,1,1,1,1}
AppMillers
www.appmillers.com
fi
Number Factor
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
Example:
- N=5
- Number of ways = 6
- Explanation : There are 6 ways we can express N. {4,1},{1,4},{1,3,1},{3,1,1},{1,1,3},{1,1,1,1,1}
AppMillers
www.appmillers.com
fi
Number Factor
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
NumberFactor(6)
AppMillers
www.appmillers.com
fi
Number Factor
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
NumberFactor(N):
If N in (0,1,2) return 1
If N = 3 return 2
Else
return NumberFactor(N-1) + NumberFactor(N-3) + NumberFactor(N-4)
AppMillers
www.appmillers.com
fi
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
Example 1
6 7 1 30 8 2 4
Answer
- Maximum amount = 41
- Houses that are stolen : 7, 30, 4
Option1 = 6 + f(5)
Max(Option1, Option2)
Option2 = 0 + f(6)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(0)
maxValueHouse(2) maxValueHouse(1)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(houses, currentHouse):
If currentHouse > length of houses
return 0
Else
stealFirstHouse = currentHouse + maxValueHouse(houses, currentHouse+2)
skipFirstHouse = maxValueHouse(houses, currentHouse+1)
return max(stealFirstHouse, skipFirstHouse)
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Example 1
- S1 = “catch”
- S2 = “carch”
- Output = 1
- Explanation : Replace “r” with “t”
Example 2
- S1 = “table”
- S2 = “tbres”
- Output = 3
- Explanation : Insert “a” to second position, replace “r” with “l” and delete “s”
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Example
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Else
deleteOp = 1 + findMinOperation(s1, s2, index1, index2+1)
insertOp = 1 + findMinOperation(s1, s2, index1+1, index2)
replaceOp = 1 + findMinOperation(s1, s2, index1+1, index2+1)
return min(deleteOp, insertOp, replaceOp)
AppMillers
www.appmillers.com
Example 1
🥭Mango
🍎 🍊
Apple Orange
🍌 Banana
Weight : 3 Weight : 1 Weight : 2 Weight : 5
Pro t : 31 Pro t : 26 Pro t : 17 Pro t : 72
Knapsack Capacity : 7
Answer Combinations
- Mango (W:3, P:31) + Apple (W:1,P:26) + Orange (W:2, P:17) = W:6, Pro t:74
- Orange (W:2, P:17) + Banana (W:5,P:72) = W:7, Pro t:89
- Apple (W:1,P:26) + Banana (W:5,P:72) = W:6, Pro t:98
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
Zero One Knapsack Problem
Problem Statement:
- Given the weights and pro ts of N items
- Find the maximum pro t within given capacity of C
- Items cannot be broken
Example 1
🥭Mango
🍎 🍊
Apple Orange
🍌
Banana
Weight : 3 Weight : 1 Weight : 2 Weight : 5
Pro t : 31 Pro t : 26 Pro t : 17 Pro t : 72
Knapsack Capacity : 7
Subproblems:
Option1 = 31 + f(2,3,4)
Max(Option1, Option2)
Option2 = 0 + f(2,3,4)
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
Zero One Knapsack Problem
Problem Statement:
- Given the weights and pro ts of N items
- Find the maximum pro t within given capacity of C
- Items cannot be broken
AppMillers
www.appmillers.com
fi
fi
Example
- S1 = “elephant”
- S2 = “erepat”
- Output = 5
- Longest String : “eepat”
AppMillers
www.appmillers.com
The Longest Common Subsequence (LCS)
Problem Statement:
- S1 and S2 are given strings
- Find the length of the longest subsequence which is common to both strings
- Subsequence: a sequence that can be driven from another sequence by deleting some elements
without changing the order of them
Example
- S1 = “elephant”
- S2 = “erepat”
- Output = 5
- Longest String : “eepat”
Subproblems:
AppMillers
www.appmillers.com
The Longest Common Subsequence (LCS)
Problem Statement:
- S1 and S2 are given strings
- Find the length of the longest subsequence which is common to both strings
- Subsequence: a sequence that can be driven from another sequence by deleting some elements
without changing the order of them
Example
- S1 = “elephant”
- S2 = “erepat”
- Output = 5
- Longest String : “eepat”
Else
op1 = findCLS(s1, s2, index1, index2+1)
op2 = findCLS(s1, s2, index1+1, index2)
return max(op1, op2)
AppMillers
www.appmillers.com
MADAM
Example 1
- S = “ELRMENMET”
- Output = 5
- LPS: “EMEME”
Example 2
- S = “AMEEWMEA”
- Output = 6
- LPS: “AMEEMA”
AppMillers
www.appmillers.com
The Longest Palindromic Subsequence (LPS)
Problem Statement:
- S is a given string
- Find the longest palindromic subsequence (LPS)
- Subsequence: a sequence that can be driven from another sequence by deleting some elements
without changing the order of them
- Palindrome is a string that reads the same backward as well as forward
Example 1
- S = “ELRMENMET”
- Output = 5
- LPS: “EMEME”
Subproblems:
Option1 = 2 + f(2,8)
Option3 = 0 + f(2,9)
AppMillers
www.appmillers.com
The Longest Palindromic Subsequence (LPS)
Problem Statement:
- S is a given string
- Find the longest palindromic subsequence (LPS)
- Subsequence: a sequence that can be driven from another sequence by deleting some elements
without changing the order of them
- Palindrome is a string that reads the same backward as well as forward
Example 1
- S = “ELRMENMET”
- Output = 5
- LPS: “EMEME”
Else
op1 = findCLS(s, startIndex, endIndex-1)
op2 = findCLS(s, startIndex+1, endIndex)
return max(op1, op2)
AppMillers
www.appmillers.com
Example 1
- S = “ABCCBUA”
- Output = 4
- LPS: “BCCB”
AppMillers
www.appmillers.com
The Longest Palindromic Substring (LPS)
Problem Statement:
- S is a given string
- Find the longest palindromic substring (LPS)
- Substring: contiguous sequence of characters within a string
- Palindrome is a string that reads the same backward as well as forward
Example
- S = “MAMDRDM”
- Output = 5
- LPS: “MDRDM”
Option1 = 2 + f(2,6)
Option3 = 0 + f(1,6)
AppMillers
www.appmillers.com
The Longest Palindromic Subsequence (LPS)
Problem Statement:
- S is a given string
- Find the longest palindromic subsequence (LPS)
- Subsequence: a sequence that can be driven from another sequence by deleting some elements
without changing the order of them
- Palindrome is a string that reads the same backward as well as forward
Example 1
- S = “ELRMENMET”
- Output = 5
- LPS: “EMEME”
Else
op1 = findCLS(s, startIndex, endIndex-1)
op2 = findCLS(s, startIndex+1, endIndex)
return max(op1, op2)
AppMillers
www.appmillers.com
Example
4 7 8 6 4 4 7 8 6 4
6 7 3 9 2 6 7 3 9 2
3 8 1 2 4 3 8 1 2 4
7 1 7 3 7 7 1 7 3 7
2 9 8 9 3 2 9 8 9 3
Min Cost : 36
AppMillers
www.appmillers.com
Minimum cost to reach the last cell
Problem Statement:
- 2D Matrix is given
- Each cell has a cost associated with it for accessing
- We need to start from (0.0) cell and go till (n-1,n-1) cell
- We can go only to right or down cell from current cell
- Find the way in which the cost is minimum
4 7 8 6 4
6 7 3 9 2
3 8 1 2 4
7 1 7 3 7
2 9 8 9 3
Subproblems:
Option1 = y + 9 +3 f(4,3)
Min(Option1, Option2)
Option2 = z + 7 + 3 f(3,4)
AppMillers
www.appmillers.com
Minimum cost to reach the last cell
Problem Statement:
- 2D Matrix is given
- Each cell has a cost associated with it for accessing
- We need to start from (0.0) cell and go till (n-1,n-1) cell
- We can go only to right or down cell from current cell
- Find the way in which the cost is minimum
Else
op1 = findMinCost(twoDArray, row-1, col)
op2 = findMinCost(twoDArray, row, col-1)
return cost[row][col] + min(op1, op2)
AppMillers
www.appmillers.com
Answer 1 Answer 2
4 7 1 6 4 7 1 6 4 7 1 6
5 7 3 9 5 7 3 9 5 7 3 9
3 2 1 2 3 2 1 2 3 2 1 2
7 1 6 3 7 1 6 3 7 1 6 3
AppMillers
www.appmillers.com
Number of paths to reach the last cell with given cost
Problem Statement:
- 2D Matrix is given
- Each cell has a cost associated with it for accessing
- We need to start from (0.0) cell and go till (n-1,n-1) cell
- We can go only to right or down cell from current cell
- We are given total cost to reach the last cell
- Find the number of ways to reach end of matrix with given “total cost”
4 7 1 6
5 7 3 9
3 2 1 2
7 1 6 3
Subproblems:
Option1 = y + 2 = 22 f(3,4,22)
Sum(Option1, Option2)
Option2 = z + 6 = 22 f(4,3,22)
AppMillers
www.appmillers.com
Number of paths to reach the last cell with given cost
Problem Statement:
- 2D Matrix is given
- Each cell has a cost associated with it for accessing
- We need to start from (0.0) cell and go till (n-1,n-1) cell
- We can go only to right or down cell from current cell
- We are given total cost to reach the last cell
- Find the number of ways to reach end of matrix with given “total cost”
AppMillers
www.appmillers.com
Example : 1
1 + 1 + 1 + 1 + 1 + 1 + 1 = 7
1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 9
AppMillers
www.appmillers.com
What is Dynamic Programming?
Dynamic Programming (DP) is an algorithmic technique for solving an optimization problem by
breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall
problem depends upon the optimal solution to its subproblems
Optimal Substructure:
If any problem’s overall optimal solution can be constructed from the optimal solutions of its
subproblem then this problem has optimal substructure
Overlapping Subproblem:
Subproblems are smaller versions of the original problem. Any problem has overlapping sub-problems if
nding its solution involves solving the same subproblem multiple times
Fib(4)
Fib(3) Fib(2)
Fib(1) Fib(0)
AppMillers
www.appmillers.com
fi
Top Down with Memoization
Solve the bigger problem by recursively nding the solution to smaller subproblems. Whenever we
solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple
times. This technique of storing the results of already solved subproblems is called Memoization.
Fibonacci(N):
If n < 1 return error message
If n = 1 return 0
If n = 2 return 1
Else
return Fibonacci(N-1) + Fibonacci(N-2)
AppMillers
www.appmillers.com
fi
Top Down with Memoization
Solve the bigger problem by recursively nding the solution to smaller subproblems. Whenever we
solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple
times. This technique of storing the results of already solved subproblems is called Memoization.
Fib(6)
Fib(5) Fib(4)
Fib(2) Fib(1)
AppMillers
www.appmillers.com
fi
Top Down with Memoization
Solve the bigger problem by recursively nding the solution to smaller subproblems. Whenever we
solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple
times. This technique of storing the results of already solved subproblems is called Memoization.
Fib(6)
Fib(5) Fib(4)
Fib(2) Fib(1)
AppMillers
www.appmillers.com
fi
Top Down with Memoization
Solve the bigger problem by recursively nding the solution to smaller subproblems. Whenever we
solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple
times. This technique of storing the results of already solved subproblems is called Memoization.
Fibonacci(n):
if n < 1 return error message
if n = 1 return 0
if n = 2 return 1
if not n in memo:
memo[n] = Fibonacci(n-1, memo) + Fibonacci(n-2, memo)
return memo[n]
AppMillers
www.appmillers.com
fi
Fib(6)
Fib(5) Fib(4)
Fib(2) Fib(1)
AppMillers
www.appmillers.com
fi
Top Down with Memoization
Solve the bigger problem by recursively nding the solution to smaller subproblems. Whenever we
solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple
times. This technique of storing the results of already solved subproblems is called Memoization.
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F4 + F5 0 1 1 F2 + F3 F3 + F4 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F3 + F4 F4 + F5 0 1 1 2 F3 + F4 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F2 + F3 F3 + F4 F4 + F5 0 1 1 2 3 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F1 + F2 F2 + F3 F3 + F4 F4 + F5 0 1 1 2 3 5
AppMillers
www.appmillers.com
fi
Bottom Up with Tabulation
Tabulation is the opposite of the top-down approach and avoids recursion. In this approach, we solve the
problem “bottom-up” (i.e. by solving all the related subproblems rst). This is done by lling up a table.
Based on the results in the table, the solution to the top/original problem is then computed.
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F4 + F5 0 1 1 F2 + F3 F3 + F4 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F3 + F4 F4 + F5 0 1 1 2 F3 + F4 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F2 + F3 F3 + F4 F4 + F5 0 1 1 2 3 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F1 + F2 F2 + F3 F3 + F4 F4 + F5 0 1 1 2 3 5
AppMillers
www.appmillers.com
fi
fi
Bottom Up with Tabulation
Tabulation is the opposite of the top-down approach and avoids recursion. In this approach, we solve the
problem “bottom-up” (i.e. by solving all the related subproblems rst). This is done by lling up a table.
Based on the results in the table, the solution to the top/original problem is then computed.
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 F1 + F2 0 1 1 2 F3 + F4
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 1 0 1 1 2 3
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 1 F2 + F3 0 1 1 2 3 F4 + F5
F1 F2 F3 F4 F5 F6 F1 F2 F3 F4 F5 F6
0 1 1 2 0 1 1 2 3 5
AppMillers
www.appmillers.com
fi
fi
Bottom Up with Tabulation
Tabulation is the opposite of the top-down approach and avoids recursion. In this approach, we solve the
problem “bottom-up” (i.e. by solving all the related subproblems rst). This is done by lling up a table.
Based on the results in the table, the solution to the top/original problem is then computed.
def fibonacciTab(n):
tb = [0, 1]
for i in range(2, n + 1):
tb.append(tb[i - 1] + tb[i - 2])
return tb[n-1]
AppMillers
www.appmillers.com
fi
fi
Top Down vs Bottom Up
AppMillers
www.appmillers.com
Top Down vs Bottom Up
AppMillers
www.appmillers.com
ffi
ffi
ffi
Is Merge Sort Dynamic Programming?
1.Does it have Optimal Substructure property?
2.Does it have Overlapping Subproblems property?
6 4 3 7 5 1 2
6 4 3 7 5 1 2
6 4 3 7 5 1 2
6 4 3 7 5 1
4 6 3 7 1 5 2
3 4 6 7 1 2 5
1 2 3 4 5 6 7
Where does the name of DP come from?
Dynamic Programming?
AppMillers
www.appmillers.com
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
Example 1
- N=4
- Number of ways = 4
- Explanation : There are 4 ways we can express N. {4},{1,3},{3,1},{1,1,1,1}
Example 2
- N=5
- Number of ways = 6
- Explanation : There are 6 ways we can express N. {4,1},{1,4},{1,3,1},{3,1,1},{1,1,3},{1,1,1,1,1}
AppMillers
www.appmillers.com
fi
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
NumberFactor(N):
If N in (0,1,2) return 1
If N = 3 return 2
Else
return NumberFactor(N-1) + NumberFactor(N-3) + NumberFactor(N-4)
AppMillers
www.appmillers.com
fi
NumberFactor(8)
AppMillers
www.appmillers.com
fi
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
NumberFactor(8)
AppMillers
www.appmillers.com
fi
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
NumberFactor(N):
If N in (0,1,2) return 1
If N = 3 return 2
Else
rec1 = NumberFactor(N-1)
rec2 = NumberFactor(N-3)
rec3 = NumberFactor(N-4)
AppMillers
www.appmillers.com
fi
NumberFactor(N, dp):
If N in (0,1,2) return 1
If N = 3 return 2
Else
rec1 = NumberFactor(N-1)
rec2 = NumberFactor(N-3)
rec3 = NumberFactor(N-4)
AppMillers
www.appmillers.com
fi
NumberFactor(N, dp):
If N in (0,1,2) return 1
If N = 3 return 2
Elif N in dp return dp[N]
Else
rec1 = NumberFactor(N-1)
rec2 = NumberFactor(N-3)
rec3 = NumberFactor(N-4)
AppMillers
www.appmillers.com
fi
NumberFactor(N, dp):
If N in (0,1,2) return 1
If N = 3 return 2
Elif N in dp return dp[N]
Else
rec1 = NumberFactor(N-1)
rec2 = NumberFactor(N-3)
rec3 = NumberFactor(N-4)
dp[N] = rec1 + rec2 + rec3
AppMillers
www.appmillers.com
fi
NumberFactor(N, dp):
If N in (0,1,2) return 1
If N = 3 return 2
Elif N in dp return dp[N]
Else
rec1 = NumberFactor(N-1)
rec2 = NumberFactor(N-3)
rec3 = NumberFactor(N-4)
dp[N] = rec1 + rec2 + rec3
return dp[N]
AppMillers
www.appmillers.com
fi
AppMillers
www.appmillers.com
fi
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
0 1 1 2 NF6+NF4+NF3 0 1 1 2 2+1+1=4 NF4+NF2+NF1 NF5+NF3+NF2 NF6+NF4+NF3
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
0 1 1 2 NF4+NF2+NF1 NF5+NF3+NF2 NF6+NF4+NF3 0 1 1 2 2+1+1=4 4+1+1=6 6+2+1=9 NF6+NF4+NF3
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
AppMillers
www.appmillers.com
fi
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
Bottom Up Approach
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
0 1 1 2 NF3+NF2+NF0 0 1 1 2 2+1+1=4 NF4+NF2+NF1 NF6+NF3+NF2 NF6+NF4+NF3
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
0 1 1 2 NF3+NF2+NF0 NF4+NF2+NF1 NF6+NF3+NF2 0 1 1 2 2+1+1=4 4+1+1=6 6+2+1=9 NF6+NF4+NF3
NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7) NF(0) NF(1) NF(2) NF(3) NF(4) NF(5) NF(6) NF(7)
AppMillers
www.appmillers.com
fi
Dynamic Programming - Number Factor problem
Problem Statement:
Given N, nd the number of ways to express N as a sum of 1, 3 and 4.
Bottom Up Approach
def numberFactor(n):
tb = [1,1,1,2]
for i in range(4, n+1):
tb.append(tb[i-1]+tb[i-3]+tb[i-4])
return tb[n]
AppMillers
www.appmillers.com
fi
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
Example 1
6 7 1 30 8 2 4
Answer
- Maximum amount = 41
- Houses that are stolen : 7, 30, 4
Option1 = 6 + f(5)
Max(Option1, Option2)
Option2 = 0 + f(6)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(houses, currentHouse):
If currentHouse > length of houses
return 0
Else
stealFirstHouse = currentHouse + maxValueHouse(houses, currentHouse+2)
skipFirstHouse = maxValueHouse(houses, currentHouse+1)
return max(stealFirstHouse, skipFirstHouse)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(0)
maxValueHouse(2) maxValueHouse(1)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(0)
maxValueHouse(2) maxValueHouse(1)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
maxValueHouse(houses, currentHouse):
If currentHouse > length of houses
return 0
Else
stealFirstHouse = currentHouse + maxValueHouse(houses, currentHouse+2)
skipFirstHouse = maxValueHouse(houses, currentHouse+1)
return max(stealFirstHouse, skipFirstHouse)
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
AppMillers
www.appmillers.com
House Robber
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
AppMillers
www.appmillers.com
House Robber
Top Down Approach
Problem Statement:
- Given N number of houses along the street with some amount of money
- Adjacent houses cannot be stolen
- Find the maximum amount that can be stolen
H0 H1 H2 H3 H4 H5 H5
6 7 1 30 8 2 4
HR(0) HR(1) HR(2) HR(3) HR(4) HR(5) HR(6)
max(H0+HR2, HR1)
H0 H1 H2 H3 H4 H5 H5
6 7 1 30 8 2 4
HR(0) HR(1) HR(2) HR(3) HR(4) HR(5) HR(6)
max(H0+HR2, HR1) max(H1+HR3, HR2) max(H2+HR4, HR3) max(H3+HR5, HR4) max(H4+HR6, HR5) max(H5+HR7, HR6) max(H6+HR8, HR7)
H0 H1 H2 H3 H4 H5 H5
6 7 1 30 8 2 4
Bottom Up Approach
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Example 1
- S1 = “catch”
- S2 = “carch”
- Output = 1
- Explanation : Replace “r” with “t”
Example 2
- S1 = “table”
- S2 = “tbres”
- Output = 3
- Explanation : Insert “a” to second position, replace “r” with “l” and delete “s”
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Else
deleteOp = 1 + findMinOperation(s1, s2, index1, index2+1)
insertOp = 1 + findMinOperation(s1, s2, index1+1, index2)
replaceOp = 1 + findMinOperation(s1, s2, index1+1, index2+1)
return min(deleteOp, insertOp, replaceOp)
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
minOper(0,0)
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
minOper(0,0)
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Top Down Approach
def findMinOperation(s1, s2, index1, index2, tempDict): Step 1
if index1 == len(s1):
return len(s2)-index2
if index2 == len(s2):
return len(s1)-index1
if s1[index1] == s2[index2]:
return findMinOperation(s1, s2, index1+1, index2+1, tempDict)
else:
dictKey = str(index1)+str(index2)
if dictKey not in tempDict:
Step 2
deleteOp = 1 + findMinOperation(s1, s2, index1, index2+1, tempDict)
insertOp = 1 + findMinOperation(s1, s2, index1+1, index2, tempDict)
replaceOp = 1 + findMinOperation(s1, s2, index1+1, index2+1, tempDict)
tempDict[dictKey] = min (deleteOp, insertOp, replaceOp) Step 3
return tempDict[dictKey] Step 4
AppMillers
www.appmillers.com
Convert String
Problem Statement:
- S1 and S2 are given strings
- Convert S2 to S1 using delete, insert or replace operations
- Find the minimum count of edit operations
Bottom Up Approach
def findMinOperationBU(s1, s2, tempDict):
for i1 in range(len(s1)+1):
dictKey = str(i1)+'0'
tempDict[dictKey] = i1
for i2 in range(len(s2)+1):
dictKey = '0'+str(i2)
tempDict[dictKey] = i2
AppMillers
www.appmillers.com
Example 1
🥭Mango
🍎 🍊
Apple Orange
🍌 Banana
Weight : 3 Weight : 1 Weight : 2 Weight : 5
Pro t : 31 Pro t : 26 Pro t : 17 Pro t : 72
Knapsack Capacity : 7
Answer Combinations
- Mango (W:3, P:31) + Apple (W:1,P:26) + Orange (W:2, P:17) = W:6, Pro t:74
- Orange (W:2, P:17) + Banana (W:5,P:72) = W:7, Pro t:89
- Apple (W:1,P:26) + Banana (W:5,P:72) = W:6, Pro t:98
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
Zero One Knapsack Problem
Problem Statement:
- Given the weights and pro ts of N items
- Find the maximum pro t within given capacity of C
- Items cannot be broken
Example 1
🥭Mango
🍎 🍊
Apple Orange
🍌
Banana
Weight : 3 Weight : 1 Weight : 2 Weight : 5
Pro t : 31 Pro t : 26 Pro t : 17 Pro t : 72
Knapsack Capacity : 7
Subproblems:
Option1 = 31 + f(2,3,4)
Max(Option1, Option2)
Option2 = 0 + f(2,3,4)
AppMillers
www.appmillers.com
fi
fi
fi
fi
fi
fi
Zero One Knapsack Problem
Problem Statement:
- Given the weights and pro ts of N items
- Find the maximum pro t within given capacity of C
- Items cannot be broken
AppMillers
www.appmillers.com
fi
fi
Knap(7,0)
Knap(4,1) Knap(7,1)
Base Knap(3,3)
AppMillers
www.appmillers.com
fi
fi
Zero One Knapsack Problem
Problem Statement:
- Given the weights and pro ts of N items
- Find the maximum pro t within given capacity of C
- Items cannot be broken
AppMillers
www.appmillers.com
fi
fi
Bottom Up Approach
AppMillers
www.appmillers.com
fi
fi
AppMillers
www.appmillers.com
A Recipe for Problem Solving
AppMillers
www.appmillers.com
A Recipe for Problem Solving
💣
5 STEPS FOR PROBLEM SOLVING
AppMillers
www.appmillers.com
A Recipe for Problem Solving
EXPLORE EXAMPLES
BREAK IT DOWN
SOLVE / SIMPLIFY
AppMillers
www.appmillers.com
Step 1 - UNDERSTAND THE PROBLEM
AppMillers
www.appmillers.com
Step 1 - UNDERSTAND THE PROBLEM
AppMillers
www.appmillers.com
Step 1 - UNDERSTAND THE PROBLEM
AppMillers
www.appmillers.com
Step 1 - UNDERSTAND THE PROBLEM
Write a function that takes two numbers and returns their sum
Implement addition
Yes
5. What should I label the important piece of data that are the part of a
problem?
EXPLORE EXAMPLES
AppMillers
www.appmillers.com
Step 2 - EXPLORE EXAMPLES
AppMillers
www.appmillers.com
Step 2 - EXPLORE EXAMPLES
AppMillers
www.appmillers.com
Step 2 - EXPLORE EXAMPLES
AppMillers
www.appmillers.com
Step 3 - BREAK IT DOWN
AppMillers
www.appmillers.com
SOLVE / SIMPLIFY
AppMillers
www.appmillers.com
SOLVE / SIMPLIFY
AppMillers
www.appmillers.com
fi
fi
fi
fi
LOOK BACK REFACTOR
AppMillers
www.appmillers.com
Summarize
UNDERSTAND THE PROBLEM
EXPLORE EXAMPLES
BREAK IT DOWN
SOLVE / SIMPLIFY
AppMillers
www.appmillers.com
Searching Algorithm
Searching Algorithm
Linear Search
Binary Search
Searching Algorithm
Searching Algorithm
Linear Search
Search for 7
5 9 3 1 2 8 4 7 6
No No No No No No No Yes
Linear Search
1 2 3 3
4 5 6 8 7 9
Linear Search in Python
Linear Search Pseudocode
- Create function with two parameters which are an array and a value
- Loop through the array and check if the current array element is equal
to the value
- If it is return the index at which the element is found
- If the value is never found return -1
AppMillers
www.appmillers.com
Binary Search
Binary Search
AppMillers
www.appmillers.com
Binary Search
Searching for 6
1 2 3 4 5 6 7 8 9
AppMillers
www.appmillers.com
Binary Search Pseudocode
- Create function with two parameters which are a sorted array and a value
- Create two pointers : a left pointer at the start of the array and a right
pointer at the end of the array.
- Based on left and right pointers calculate middle pointer
- While middle is not equal to the value and start<=end loop:
- if the middle is greater than the value move the right pointer down
- if the middle is less than the value move the left pointer up
- If the value is never found return -1
AppMillers
www.appmillers.com
O(log n) O(1)
AppMillers
www.appmillers.com
Binary Search Time Complexity
Searching for 12
[2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39]
Step 1 [2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39]
Step 2 [2,4,5,9,11,13,14]
Not Found
Step 3 [11,13,14] 16 elements = 4 Steps
Step 4 [11]
AppMillers
www.appmillers.com
[2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39,42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 1 [2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39,42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 2 [42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 5 [72,79]
AppMillers
www.appmillers.com
[2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39]
Step 1 [2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39]
Step 2 [2,4,5,9,11,13,14]
Not Found
Step 3 [11,13,14] 16 elements = 4 Steps
AppMillers
www.appmillers.com
[2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39,42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 1 [2,4,5,9,11,13,14,15,19,20,22,23,27,30,32,39,42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 2 [42,44,45,49,51,53,54,55,59,60,62,63,67,70,72,79]
Step 5 [72,79]
AppMillers
www.appmillers.com
AppMillers
www.appmillers.com
Cracking Tree and Graph Interview Questions
Route Between Nodes
Problem Statement:
Given a directed graph and two nodes (S and E), design an algorithm to find out whether there is a route from S to E.
E
A —> E False
F A A —> J True
A —> I True
I C D B
H G J
AppMillers
www.appmillers.com
Route Between Nodes
Problem Statement:
Given a directed graph and two nodes (S and E), design an algorithm to find out whether there is a route from S to E.
F A Pseudocode
- Create function with two parameters start and end nodes
- Create queue and enqueue start node to it
- Find all the neighbors of the just enqueued node and
I C D B enqueue them into the queue
- Repeat this process until the end of elements in graph
- If during the above process at some point in time we
encounter the destination node, we return True.
- Mark visited nodes as visited
H G J
AppMillers
www.appmillers.com
Minimal Tree
Problem Statement:
Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree
with minimal height.
Root Node
1 2 3 4 5 6 7 8 9
3 8
2 4 7 9
1 6
AppMillers
www.appmillers.com
List of Depths
Problem Statement:
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i e , if you
have a tree with depth D, you’ll have D linked lists)
Level 1 1 1 None
001
001 111
Level 3 4 5 6 7
AppMillers
www.appmillers.com
List of Depths
Problem Statement:
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i e , if you
have a tree with depth D, you’ll have D linked lists)
custDict
Pre Order Traversal Keys Values
1 3 1
001
2 3 2 2 111 3
001 111
AppMillers
www.appmillers.com
Check Balanced
Problem Statement:
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is
defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
N1
N2 N3
N4 N5 N6
AppMillers
www.appmillers.com
Check Balanced
Problem Statement:
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is
defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
N1
N2
N4 N5
AppMillers
www.appmillers.com
Check Balanced
Problem Statement:
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is
defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
N4 N5 N6
AppMillers
www.appmillers.com
Validate BST
Problem Statement:
- The left subtree of a node contains only nodes with keys less than the node’s key
- The right subtree of a node contains only nodes with keys greater than the node’s key
- These conditions are applicable for both left and right subtrees
2 4
1 4 1 3
True
2 5
AppMillers
www.appmillers.com
False
Validate BST
Problem Statement:
Min Max
-∞ <= 3 <= ∞
AppMillers
www.appmillers.com
Validate BST
Problem Statement:
Min Max
-∞ <= 3 <= ∞
AppMillers
www.appmillers.com
Successor
Problem Statement:
Write an algorithm to find the next node (i.e in-order successor) of given node in a binary search tree. You may
assume that each node has a link to its parent.
4 In-order successor of 1 is 2
In-order successor of 3 is 4
8 In-order successor of 2 is 3
2
1 3 5 9
AppMillers
www.appmillers.com
Successor
Problem Statement:
Write an algorithm to find the next node (i.e in-order successor) of given node in a binary search tree. You may
assume that each node has a link to its parent.
- If right subtree of node is not None, then successor lies in right subtree.
- If right subtree of node is None, then successor is one of the ancestors.
2 8
1 3 5 9
AppMillers
www.appmillers.com
Build Order
Problem Statement:
You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is
dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that
will allow the projects to be built. If there is no valid build order, return an error.
Input:
Projects : a, b, c, d, e, f
Dependencies: (a, d), (f, b), (b, d), (f, a), (d, c)
Output:
e, f, a, b, d, c
a b c
d e f
AppMillers
www.appmillers.com
Build Order
Problem Statement:
You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is
dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that
will allow the projects to be built. If there is no valid build order, return an error.
AppMillers
www.appmillers.com
First Common Ancestor
Problem Statement:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing
additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
55
22 99
35 88 90 95
33
54
AppMillers
www.appmillers.com
First Common Ancestor
Problem Statement:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing
additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
55
findNodeinTree()
findNodeinTree(88, left-44) True
findNodeinTree(33, left-44) True
44 77
findNodeinTree(88, left-22) True
findNodeinTree(33, left-22) False
35 88 90 95
33
54
AppMillers
www.appmillers.com
First Common Ancestor
Problem Statement:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing
additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
55
44 77
22 99
35 88 90 95
33
54 AppMillers
www.appmillers.com