SlideShare a Scribd company logo
programming workshop
What will be covered
•Time complexity
•Dynamic Programming
• Backtracking
Time complexity of For loop
For (idx = 0; idx < N ; idx = idx + 1 )
{
print(idx)
}
Time complexity
is O(N)
Time complexity of For loop
For (idx = 1; idx < N ; idx = idx * 2)
{
print(idx)
}
Time complexity
is O(log2
(N))
idx = 1, 2, 4, 8, 16, 32…
N = 8, number of steps = 3
N = 32, number of steps = 5
Time complexity of For loops
For (idx = 1; idx < N ; idx = idx + 1)
{
aList.Append(idx)
}
Time complexity
is O(N2
)
1 2 N-5 N
Elements before you = 1 + 2 + 3 + 4 + … + N = N(N-1)/2
Time complexity of For loops
For (idx = 1; idx < N ; idx = idx + 1)
{
aList.Append(idx)
}
Time complexity
is O(N)
1 2 N-5 N
If you had a tail pointer ? Then 1 + 1 + 1 = N
Tail Pointer
Time complexity of For loops
For (idx = 1; idx < N ; idx = idx + 1)
{
binaryTree.Insert(idx)
}
Time complexity
is O(N . log2
(N))
A
K
Z S
T
E
Cost of one insert into Binary tree
= go down the depth of binary Tree
= log2
(N)
Time complexity of two For loops
For (i = 0; i < N ; i = i + 1)
for (j = 0; j < N ; j = j + 1)
{
print(i + j)
}
Time complexity
is O(N2
)
Time complexity of two For loops
for (i = 0; i < N ; i = i + 1)
for (j = 0; j < i ; j = j + 1)
{
print(i + j)
}
for (i = 0; i < N ; i = i + 1)
for (j = i; j < N ; j = j + 1)
{
print(i + j)
}
Left loop = 1 + 2 + 3 + 4 + … + N
= N(N-1)/2
Time complexity
is O(N2
)
Right loop = N + (N-1) + … + 2 + 1
Mark each algorithm on this chart
N2
N N3
exp(N)1
1
N
N.log2
(N)
N.log2
(N)
Exp(N)
TIME
SPAC
E
Double
For Loop
Single For
Loop
Tree
insert
List insert
List insert
with Tail
pointer
Many ways of solving a given problem
N2
N N3
exp(N)1
1
N
N.log2
(N)
N.log2
(N)
Exp(N)
TIME
SPAC
E
Time
efficient
Space
efficient
Space and
time
optimal
Cannot do better than Lower bound.
This depends on constraints of problem
Four ways to get home
Backtracking : Explore every point from current position. If you
don’t reach home, return to previous position and retry.
Divide and Conquer : Find way to get to Metro, then Majestic,
then home.
Dynamic Programming : Go home at lowest cost using Bus,
Metro, Cab and Rickshaw
Greedy : Find best next point in home-ward direction
Dynamic Programming
Get home via Dynamic Programming
Office Home
Jayanagar
Majestic
Cubbon
Park
TravelCost (Home) =
Min ( TravelCost(Majestic), TravelCost(Cubbon Park) )
TravelCost (Cubbon Park) =
Min ( TravelCost (Direct), TravelCost(Jayanagar) )
Silk Board Jn
Dynamic Programming - subset sum
4 7
7
5
3
3
5
3
3
Either add this element OR not
4 7 5 3
Find subset whose sum is 14
5
3
DP - Subset Sum – recursive
Boolean hasSubsetSum(int curIdx, int curSum)
{
// either you add this element OR not add it
return hasSubsetSum(curIdx - 1, curSum)
|| hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1])
}
DP - Subset Sum – recursive
Boolean hasSubsetSum(int curIdx, int curSum)
{
if (curSum == 0) return True
// either you add this element OR not add it
return hasSubsetSum(curIdx - 1, curSum)
|| hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1])
}
DP - Subset Sum – recursive
Boolean hasSubsetSum(int curIdx, int curSum)
{
if (curSum == 0) return True
if (curIdx == 0) || (curSum != 0) return False
// either you add this element OR not add it
return hasSubsetSum(curIdx - 1, curSum)
|| hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1])
}
DP - Subset Sum – recursive to iterative
• REMEMBER : When the Recursion is a function of 2 variables, your iterative solution
requires a 2-dim matrix
….hasSubsetSum(curIdx - 1, curSum)
|| hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1])
0
1
…
last array element n-1
0 1 expectedSum
DP - Subset sum – iterative
Boolean hasSubsetSum(int expectedSum)
{
for (i = 1; i < n; i ++)
for (j = 1; j < expectedSum; j ++ )
{
subset[ i ][ j ] = subset[i - 1][ j ]
|| subset[i -1][ j – array[curIdx]]
}
}
Backtracking
How to get home via backtracking
Boolean PathToHome(current position)
{
if (reachedHome(current position))
return True
for (all available Lanes starting from current position)
{
gotHome = PathToHome(current position + lane)
if (gotHome = false)
Go back to previous position
}
return False
}
Backtracking program template
Backtracking - subset sum
4 7
7
5
3
3
5
3
3
Either add this element OR not
4 7 5 3
Find subset whose sum is 14
5
3
Backtracking – subset sum
Backtracking – subset sum - Complexity
•Each element is either added or Not
•Number of such subsets = 2 * 2 * 2... (N times) = 2N
•Each subset has to be summed = sum of (roughly) N elements
Hence, time complexity
= number of elements in each subset x number of subsets
= O(N . 2N
)
Knights tour
Position = 2, 2
0,1 1,0 0,3 1,4 3,0 4,1 3,4 4,3
Each cell has 8 options
Depth of tree = 64
Check for all 64 cells
Time = O(864
)
Backtracking – Knights tour
Backtracking program template
Recap : Four ways to get home
Backtracking : Explore every point from current position. If you
don’t reach home, return to previous position and retry.
Divide and Conquer : Find way to get to Baiyappanahalli Metro,
then Majestic, then home.
Dynamic Programming : Go home at lowest cost using Bus,
Metro, Cab and Rickshaw
Greedy : Find best next point in home-ward direction
Difference between algorithm types
•“Greedy Algorithm” first makes choice and then solves sub-problem
•“Divide and conquer” generates non-overlapping sub-problems
•“Dynamic programming” finds optimal solution to sub-problem; but it
can generate overlapping sub-problems – hence “memoization”
•“Backtracking” can reach an invalid solution – that’s why its called
backtracking
Conclusion
To write good code…
•You have to read good code
•Work through many problems
•Memorize elegant patterns & tricks
Dynamic Programming - Rabbits
If rabbits die after 4 days, only those younger than 4 days are alive
Int getNumRabbits(int numDays)
{
if (n == 0) return 1
alive = [3 x getNumRabbits(numOfDays – 1) ]
- getNumOfRabbits[numOfDays – 4]
}
Invariants in an algorithm
•Invariants ensure that each step in your algorithm is correct
•Convert invariants into Assertions
•https://yourbasic.org/algorithms/loop-invariants-explained/
•Example : Take 2-3 algorithms and define one invariant in them
Think of the simplest cases
•Given a complicated problem
•E.g. In array of 100 elements, rearrange in positive & negative
Too hard to think of all combinations !
1. Lets reduce it to simplest possible examples
2. Take an array with 3 entries
3. Find a technique to solve this
4. Then expand it to solve larger problem
Think of the simplest cases
-3 -3 -3 4 4 4
-3 5 6
5 -3 6
5 -36
-3 -5 6
-3 -56
-3 -56
USE
SYMMETRY

More Related Content

What's hot

Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Gopi Saiteja
 
Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Traian Rebedea
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
Amrinder Arora
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
Arvind Krishnaa
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Amit Kumar Rathi
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Shakil Ahmed
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
Sahil Kumar
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
Krish_ver2
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
Rajendran
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
Madhu Bala
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Melaku Bayih Demessie
 
Dynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain MultiplicationDynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain Multiplication
Pecha Inc.
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
Dr. Rajdeep Chatterjee
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesign
Respa Peter
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
Amrinder Arora
 
Daa unit 4
Daa unit 4Daa unit 4
Daa unit 4
Abhimanyu Mishra
 
Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Traian Rebedea
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSGayathri Gaayu
 

What's hot (20)

Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Dynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain MultiplicationDynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain Multiplication
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesign
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Daa unit 4
Daa unit 4Daa unit 4
Daa unit 4
 
Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMS
 

Similar to Programming workshop

Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
Nv Thejaswini
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
KokilaK25
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
smruti sarangi
 
AAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxAAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptx
HarshitSingh334328
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
Krish_ver2
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
Krish_ver2
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
jannatulferdousmaish
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
MuhammadSheraz836877
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Shiwani Gupta
 
Algorithms - Rocksolid Tour 2013
Algorithms  - Rocksolid Tour 2013Algorithms  - Rocksolid Tour 2013
Algorithms - Rocksolid Tour 2013Gary Short
 
Finite elements : basis functions
Finite elements : basis functionsFinite elements : basis functions
Finite elements : basis functions
Tarun Gehlot
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
S. M. Risalat Hasan Chowdhury
 
Aaex4 group2(中英夾雜)
Aaex4 group2(中英夾雜)Aaex4 group2(中英夾雜)
Aaex4 group2(中英夾雜)
Shiang-Yun Yang
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
SairaAtta5
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
Amrinder Arora
 
Recursion
RecursionRecursion
Recursion
Malainine Zaid
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
Nagasuri Bala Venkateswarlu
 

Similar to Programming workshop (20)

algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
AAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxAAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptx
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
 
Algorithms - Rocksolid Tour 2013
Algorithms  - Rocksolid Tour 2013Algorithms  - Rocksolid Tour 2013
Algorithms - Rocksolid Tour 2013
 
Finite elements : basis functions
Finite elements : basis functionsFinite elements : basis functions
Finite elements : basis functions
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
 
Aaex4 group2(中英夾雜)
Aaex4 group2(中英夾雜)Aaex4 group2(中英夾雜)
Aaex4 group2(中英夾雜)
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
 
Recursion
RecursionRecursion
Recursion
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 

More from Sandeep Joshi

Block ciphers
Block ciphersBlock ciphers
Block ciphers
Sandeep Joshi
 
Synthetic data generation
Synthetic data generationSynthetic data generation
Synthetic data generation
Sandeep Joshi
 
How to build a feedback loop in software
How to build a feedback loop in softwareHow to build a feedback loop in software
How to build a feedback loop in software
Sandeep Joshi
 
Hash function landscape
Hash function landscapeHash function landscape
Hash function landscape
Sandeep Joshi
 
Android malware presentation
Android malware presentationAndroid malware presentation
Android malware presentation
Sandeep Joshi
 
Doveryai, no proveryai - Introduction to tla+
Doveryai, no proveryai - Introduction to tla+Doveryai, no proveryai - Introduction to tla+
Doveryai, no proveryai - Introduction to tla+
Sandeep Joshi
 
Apache spark undocumented extensions
Apache spark undocumented extensionsApache spark undocumented extensions
Apache spark undocumented extensions
Sandeep Joshi
 
Lockless
LocklessLockless
Lockless
Sandeep Joshi
 
Rate limiters in big data systems
Rate limiters in big data systemsRate limiters in big data systems
Rate limiters in big data systems
Sandeep Joshi
 
Virtualization overheads
Virtualization overheadsVirtualization overheads
Virtualization overheads
Sandeep Joshi
 
Data streaming algorithms
Data streaming algorithmsData streaming algorithms
Data streaming algorithms
Sandeep Joshi
 

More from Sandeep Joshi (11)

Block ciphers
Block ciphersBlock ciphers
Block ciphers
 
Synthetic data generation
Synthetic data generationSynthetic data generation
Synthetic data generation
 
How to build a feedback loop in software
How to build a feedback loop in softwareHow to build a feedback loop in software
How to build a feedback loop in software
 
Hash function landscape
Hash function landscapeHash function landscape
Hash function landscape
 
Android malware presentation
Android malware presentationAndroid malware presentation
Android malware presentation
 
Doveryai, no proveryai - Introduction to tla+
Doveryai, no proveryai - Introduction to tla+Doveryai, no proveryai - Introduction to tla+
Doveryai, no proveryai - Introduction to tla+
 
Apache spark undocumented extensions
Apache spark undocumented extensionsApache spark undocumented extensions
Apache spark undocumented extensions
 
Lockless
LocklessLockless
Lockless
 
Rate limiters in big data systems
Rate limiters in big data systemsRate limiters in big data systems
Rate limiters in big data systems
 
Virtualization overheads
Virtualization overheadsVirtualization overheads
Virtualization overheads
 
Data streaming algorithms
Data streaming algorithmsData streaming algorithms
Data streaming algorithms
 

Recently uploaded

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 

Recently uploaded (20)

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 

Programming workshop

  • 2. What will be covered •Time complexity •Dynamic Programming • Backtracking
  • 3. Time complexity of For loop For (idx = 0; idx < N ; idx = idx + 1 ) { print(idx) } Time complexity is O(N)
  • 4. Time complexity of For loop For (idx = 1; idx < N ; idx = idx * 2) { print(idx) } Time complexity is O(log2 (N)) idx = 1, 2, 4, 8, 16, 32… N = 8, number of steps = 3 N = 32, number of steps = 5
  • 5. Time complexity of For loops For (idx = 1; idx < N ; idx = idx + 1) { aList.Append(idx) } Time complexity is O(N2 ) 1 2 N-5 N Elements before you = 1 + 2 + 3 + 4 + … + N = N(N-1)/2
  • 6. Time complexity of For loops For (idx = 1; idx < N ; idx = idx + 1) { aList.Append(idx) } Time complexity is O(N) 1 2 N-5 N If you had a tail pointer ? Then 1 + 1 + 1 = N Tail Pointer
  • 7. Time complexity of For loops For (idx = 1; idx < N ; idx = idx + 1) { binaryTree.Insert(idx) } Time complexity is O(N . log2 (N)) A K Z S T E Cost of one insert into Binary tree = go down the depth of binary Tree = log2 (N)
  • 8. Time complexity of two For loops For (i = 0; i < N ; i = i + 1) for (j = 0; j < N ; j = j + 1) { print(i + j) } Time complexity is O(N2 )
  • 9. Time complexity of two For loops for (i = 0; i < N ; i = i + 1) for (j = 0; j < i ; j = j + 1) { print(i + j) } for (i = 0; i < N ; i = i + 1) for (j = i; j < N ; j = j + 1) { print(i + j) } Left loop = 1 + 2 + 3 + 4 + … + N = N(N-1)/2 Time complexity is O(N2 ) Right loop = N + (N-1) + … + 2 + 1
  • 10. Mark each algorithm on this chart N2 N N3 exp(N)1 1 N N.log2 (N) N.log2 (N) Exp(N) TIME SPAC E Double For Loop Single For Loop Tree insert List insert List insert with Tail pointer
  • 11. Many ways of solving a given problem N2 N N3 exp(N)1 1 N N.log2 (N) N.log2 (N) Exp(N) TIME SPAC E Time efficient Space efficient Space and time optimal Cannot do better than Lower bound. This depends on constraints of problem
  • 12. Four ways to get home Backtracking : Explore every point from current position. If you don’t reach home, return to previous position and retry. Divide and Conquer : Find way to get to Metro, then Majestic, then home. Dynamic Programming : Go home at lowest cost using Bus, Metro, Cab and Rickshaw Greedy : Find best next point in home-ward direction
  • 14. Get home via Dynamic Programming Office Home Jayanagar Majestic Cubbon Park TravelCost (Home) = Min ( TravelCost(Majestic), TravelCost(Cubbon Park) ) TravelCost (Cubbon Park) = Min ( TravelCost (Direct), TravelCost(Jayanagar) ) Silk Board Jn
  • 15. Dynamic Programming - subset sum 4 7 7 5 3 3 5 3 3 Either add this element OR not 4 7 5 3 Find subset whose sum is 14 5 3
  • 16. DP - Subset Sum – recursive Boolean hasSubsetSum(int curIdx, int curSum) { // either you add this element OR not add it return hasSubsetSum(curIdx - 1, curSum) || hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1]) }
  • 17. DP - Subset Sum – recursive Boolean hasSubsetSum(int curIdx, int curSum) { if (curSum == 0) return True // either you add this element OR not add it return hasSubsetSum(curIdx - 1, curSum) || hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1]) }
  • 18. DP - Subset Sum – recursive Boolean hasSubsetSum(int curIdx, int curSum) { if (curSum == 0) return True if (curIdx == 0) || (curSum != 0) return False // either you add this element OR not add it return hasSubsetSum(curIdx - 1, curSum) || hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1]) }
  • 19. DP - Subset Sum – recursive to iterative • REMEMBER : When the Recursion is a function of 2 variables, your iterative solution requires a 2-dim matrix ….hasSubsetSum(curIdx - 1, curSum) || hasSubsetSum(curIdx - 1, curSum - array[curIdx - 1]) 0 1 … last array element n-1 0 1 expectedSum
  • 20. DP - Subset sum – iterative Boolean hasSubsetSum(int expectedSum) { for (i = 1; i < n; i ++) for (j = 1; j < expectedSum; j ++ ) { subset[ i ][ j ] = subset[i - 1][ j ] || subset[i -1][ j – array[curIdx]] } }
  • 22. How to get home via backtracking Boolean PathToHome(current position) { if (reachedHome(current position)) return True for (all available Lanes starting from current position) { gotHome = PathToHome(current position + lane) if (gotHome = false) Go back to previous position } return False }
  • 24. Backtracking - subset sum 4 7 7 5 3 3 5 3 3 Either add this element OR not 4 7 5 3 Find subset whose sum is 14 5 3
  • 26. Backtracking – subset sum - Complexity •Each element is either added or Not •Number of such subsets = 2 * 2 * 2... (N times) = 2N •Each subset has to be summed = sum of (roughly) N elements Hence, time complexity = number of elements in each subset x number of subsets = O(N . 2N )
  • 27. Knights tour Position = 2, 2 0,1 1,0 0,3 1,4 3,0 4,1 3,4 4,3 Each cell has 8 options Depth of tree = 64 Check for all 64 cells Time = O(864 )
  • 30. Recap : Four ways to get home Backtracking : Explore every point from current position. If you don’t reach home, return to previous position and retry. Divide and Conquer : Find way to get to Baiyappanahalli Metro, then Majestic, then home. Dynamic Programming : Go home at lowest cost using Bus, Metro, Cab and Rickshaw Greedy : Find best next point in home-ward direction
  • 31. Difference between algorithm types •“Greedy Algorithm” first makes choice and then solves sub-problem •“Divide and conquer” generates non-overlapping sub-problems •“Dynamic programming” finds optimal solution to sub-problem; but it can generate overlapping sub-problems – hence “memoization” •“Backtracking” can reach an invalid solution – that’s why its called backtracking
  • 32. Conclusion To write good code… •You have to read good code •Work through many problems •Memorize elegant patterns & tricks
  • 33. Dynamic Programming - Rabbits If rabbits die after 4 days, only those younger than 4 days are alive Int getNumRabbits(int numDays) { if (n == 0) return 1 alive = [3 x getNumRabbits(numOfDays – 1) ] - getNumOfRabbits[numOfDays – 4] }
  • 34. Invariants in an algorithm •Invariants ensure that each step in your algorithm is correct •Convert invariants into Assertions •https://yourbasic.org/algorithms/loop-invariants-explained/ •Example : Take 2-3 algorithms and define one invariant in them
  • 35. Think of the simplest cases •Given a complicated problem •E.g. In array of 100 elements, rearrange in positive & negative Too hard to think of all combinations ! 1. Lets reduce it to simplest possible examples 2. Take an array with 3 entries 3. Find a technique to solve this 4. Then expand it to solve larger problem
  • 36. Think of the simplest cases -3 -3 -3 4 4 4 -3 5 6 5 -3 6 5 -36 -3 -5 6 -3 -56 -3 -56 USE SYMMETRY