SlideShare a Scribd company logo
1 of 88
Download to read offline
Stacks
Rodrigo Villarreal && Paulo Almeida
Auckland Data Structures and
Algorithms
Agenda
● Introduction to Stacks
○ Design
○ Real-world applications
● Practice
○ Examples
○ Let’s get our hands dirty!
● What’s next?
What is a Stack ?
A stack is an abstract data type that serves as a collection of
elements, with two principal operations:
1 1 2 3 5 6bottom top
What is a Stack ?
A stack is an abstract data type that serves as a collection of
elements, with two principal operations:
1 1 2 3 5
6
pop()bottom
What is a Stack ?
A stack is an abstract data type that serves as a collection of
elements, with two principal operations:
1 1 2 3 5
8
push(x)
bottom
What is a Stack ?
A stack is an abstract data type that serves as a collection of
elements, with two principal operations:
1 1 2 3 5 8
Both operations change the top of the stack.
bottom top
What is a Stack ?
This behaviour is sometimes referred as LIFO (Last in, First
out).
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1
push(x)
bottom top
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1
push(x)
1
bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1
push(x)
2
1bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1
push(x)
3
1 2bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1 31 2bottom top
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1 pop()
3
1 2bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1 pop()
2
1bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1 pop()
1
bottom
What is a Stack ?
This behaviour is sometimes referred to as LIFO (Last in, First
out).
1
pop()
bottom top
What is a Stack ?
Like in a stack of books. One can
only add or remove from the
top of the stack.
….
(Or push/pop respectively)
Big O
Time Complexity (Avg/Worst)
Search: O(n)
Access: O(n)
Insertion: O(1)
Deletion: O(1)
Space Complexity (Worst): O(n)
Where would I use Stacks in the real world ?
I’m glad you asked :)
Real life examples
Parsing mathematical expressions
String expr = ( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(
push(x)
bottom top
( 9 + ( 4 / 2 ) ) * 2
String expr =
(bottom top
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom
push(x)
9
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9
push(x)
+
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 +
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 +
push(x)
(
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + (
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + (
push(x)
4
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
push(x)
/
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
/
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
/
push(x)
2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
/ 2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 + ( 4
( 9 + ( 4 / 2 ) ) * 2
/ 2
pop()pop()pop()pop()
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 +
( 9 + ( 4 / 2 ) ) * 2
push(x)
2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 +
( 9 + ( 4 / 2 ) ) * 2
2
Real life examples
Parsing mathematical expressions
String expr =
(bottom 9 +
( 9 + ( 4 / 2 ) ) * 2
2
pop()pop()pop()pop()
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11
push(x)
top
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11 top
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11
push(x)
*
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11 *
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11 *
push(x)
2
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11 * 2
Real life examples
Parsing mathematical expressions
String expr =
bottom
( 9 + ( 4 / 2 ) ) * 2
11 * 2
pop()pop()pop()
Real life examples
Parsing mathematical expressions
String expr = ( 9 + ( 4 / 2 ) ) * 2
bottom 22
push(x)
top
Real life examples
Parsing mathematical expressions
Using Stacks in Java
Declare stack:
Stack<Type> stack = new Stack<>();
Push element:
stack.push(element);
Pop element:
stack.pop();
Valid Parentheses (L #20)
Given a string containing just the characters
determine if the input string is valid.
An input string is valid if:
● Open brackets must be closed by the same type of brackets.
● Open brackets must be closed in the correct order.
( ) { } [ ]
Valid Parentheses (L #20)
Test cases
Example Output
“()” true
“()[]{}” true
“(]” false
“([)]” false
“{[]}” true
DIVISORIA
DIVISORIA
Valid Parentheses (L #20)
Time Complexity = O(n)
Space Complexity = O(n)
Still not convinced… where else would I use
stacks?
Can you relate to this example?
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.comcurrent
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.comcurrent
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.com
current www.twitter.com
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.com
current
www.twitter.com
www.meetup.com
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.com
current
www.twitter.com
www.meetup.com
www.linkedin.com
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.com
current
www.twitter.com
www.meetup.com
www.linkedin.com
Real life examples
Back / Forward Browser Button
Back Stack Forward Stack
www.google.com
www.facebook.com
current www.twitter.com
www.meetup.com
www.linkedin.com
Real life examples
Back / Forward Browser Button
Real life examples
Back / Forward Browser Button
What happens if I write a new URL while I am in Twitter?
Back Stack Forward Stack
www.google.com
www.facebook.com
current www.twitter.com
www.meetup.com
www.linkedin.com
Real life examples
Back / Forward Browser Button
Forward Stack gets cleared
Back Stack Forward Stack
www.google.com
www.facebook.com
current
www.twitter.com
www.gmail.com
Remove All Adjacent Duplicates In String (L
#1047)
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal
letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is
unique.
Input: "abbaca"
Output: "ca"
Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal,
and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is
possible, so the final string is "ca".
Remove All Adjacent Duplicates In String (L
#1047)
Test cases
Input: "abbaca"
Output: "ca"
Input: "abcdeedcba"
Output: ""
Input: "abcdefg"
Output: "abcdefg"
Remove All Adjacent Duplicates In String (L
#1047)
Approach #1
Iterate the string and remove the adjacents. If we find a pair, we set a flag to true indicating we
need to iterate again (since we have created a new string)
Input: "abcdeedcba"
Iteration #1: "abcddcba" Iteration #5: "abba"
Iteration #2: "abccba" Iteration #6: "aa"
Iteration #3: "abccba" Iteration #7 : ""
Iteration #4: "abccba"
Remove All Adjacent Duplicates In String (L
#1047)
Approach #1
Time Complexity = O(n^2)
Space Complexity = O(n)
Remove All Adjacent Duplicates In String (L
#1047)
Approach #2
We’ll use a stack this time as our support tool to solve this problem. We’ll iterate the string and
we’ll check if the stack has elements and if top of the stack (the previous char) is equal to the
element we’re currently checking.
If the previous statement is false, add the char to the stack
If the previous statement is true, pop the previous char and don’t add the current to the stack
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a b
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a b
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
a
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
c
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
c
Remove All Adjacent Duplicates In String (L
#1047)
a b b a c a
Input
Stack
c a
Remove All Adjacent Duplicates In String (L
#1047)
Final Result
c a
Remove All Adjacent Duplicates In String (L
#1047)
Approach #1
Time Complexity = O(n^2)
Space Complexity = O(n)
Approach #2
Time Complexity = O(n)
Space Complexity = O(n)
Remove All Adjacent Duplicates In String (L
#1047)
Approach #1
Time Complexity = O(n^2)
Space Complexity = O(n)
Approach #2 ← Winner!
Time Complexity = O(n)
Space Complexity = O(n)
Leetcode Problems
Easy
Remove All Adjacent Duplicates In String (Leetcode #1047)
Valid Parentheses (Leetcode #20)
Min Stack (Leetcode #155)
Decode String (Leetcode #394)
Medium
Design Browser History (Leetcode #1472)
Remove K Digits (Leetcode #402)
Online Stock Span (Leetcode #901)
Hard
Basic Calculator (Leetcode #224)
What next?
The next session will be about Trees!

More Related Content

What's hot

Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languagePawel Szulc
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]Baruch Sadogursky
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basicsLuigi De Russis
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Alamgir Hossain
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentationNimrita Koul
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talkJohn Stevenson
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporationHenryk Konsek
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 

What's hot (19)

Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.
 
Python
PythonPython
Python
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 
LL Parsing
LL ParsingLL Parsing
LL Parsing
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporation
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 

Similar to Auckland Programming Algorithms and Performance Meetup about Stacks & LeetCode Problems

computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problemecomputernotes
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Searchecomputernotes
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32ecomputernotes
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 

Similar to Auckland Programming Algorithms and Performance Meetup about Stacks & LeetCode Problems (20)

computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Stack
StackStack
Stack
 
Stacks
Stacks Stacks
Stacks
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Stacks
StacksStacks
Stacks
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Search
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32
 
7 stacksqueues
7 stacksqueues7 stacksqueues
7 stacksqueues
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Auckland Programming Algorithms and Performance Meetup about Stacks & LeetCode Problems

  • 1. Stacks Rodrigo Villarreal && Paulo Almeida Auckland Data Structures and Algorithms
  • 2. Agenda ● Introduction to Stacks ○ Design ○ Real-world applications ● Practice ○ Examples ○ Let’s get our hands dirty! ● What’s next?
  • 3. What is a Stack ? A stack is an abstract data type that serves as a collection of elements, with two principal operations: 1 1 2 3 5 6bottom top
  • 4. What is a Stack ? A stack is an abstract data type that serves as a collection of elements, with two principal operations: 1 1 2 3 5 6 pop()bottom
  • 5. What is a Stack ? A stack is an abstract data type that serves as a collection of elements, with two principal operations: 1 1 2 3 5 8 push(x) bottom
  • 6. What is a Stack ? A stack is an abstract data type that serves as a collection of elements, with two principal operations: 1 1 2 3 5 8 Both operations change the top of the stack. bottom top
  • 7. What is a Stack ? This behaviour is sometimes referred as LIFO (Last in, First out).
  • 8. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 push(x) bottom top
  • 9. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 push(x) 1 bottom
  • 10. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 push(x) 2 1bottom
  • 11. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 push(x) 3 1 2bottom
  • 12. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 31 2bottom top
  • 13. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 pop() 3 1 2bottom
  • 14. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 pop() 2 1bottom
  • 15. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 pop() 1 bottom
  • 16. What is a Stack ? This behaviour is sometimes referred to as LIFO (Last in, First out). 1 pop() bottom top
  • 17. What is a Stack ? Like in a stack of books. One can only add or remove from the top of the stack. …. (Or push/pop respectively)
  • 18. Big O Time Complexity (Avg/Worst) Search: O(n) Access: O(n) Insertion: O(1) Deletion: O(1) Space Complexity (Worst): O(n)
  • 19. Where would I use Stacks in the real world ? I’m glad you asked :)
  • 20. Real life examples Parsing mathematical expressions String expr = ( 9 + ( 4 / 2 ) ) * 2
  • 21. Real life examples Parsing mathematical expressions String expr = ( push(x) bottom top ( 9 + ( 4 / 2 ) ) * 2
  • 22. String expr = (bottom top ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 23. String expr = (bottom push(x) 9 ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 24. String expr = (bottom 9 ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 25. String expr = (bottom 9 push(x) + ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 26. String expr = (bottom 9 + ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 27. String expr = (bottom 9 + push(x) ( ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 28. String expr = (bottom 9 + ( ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 29. String expr = (bottom 9 + ( push(x) 4 ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 30. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 Real life examples Parsing mathematical expressions
  • 31. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 push(x) / Real life examples Parsing mathematical expressions
  • 32. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 / Real life examples Parsing mathematical expressions
  • 33. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 / push(x) 2 Real life examples Parsing mathematical expressions
  • 34. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 / 2 Real life examples Parsing mathematical expressions
  • 35. String expr = (bottom 9 + ( 4 ( 9 + ( 4 / 2 ) ) * 2 / 2 pop()pop()pop()pop() Real life examples Parsing mathematical expressions
  • 36. String expr = (bottom 9 + ( 9 + ( 4 / 2 ) ) * 2 push(x) 2 Real life examples Parsing mathematical expressions
  • 37. String expr = (bottom 9 + ( 9 + ( 4 / 2 ) ) * 2 2 Real life examples Parsing mathematical expressions
  • 38. String expr = (bottom 9 + ( 9 + ( 4 / 2 ) ) * 2 2 pop()pop()pop()pop() Real life examples Parsing mathematical expressions
  • 39. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 push(x) top Real life examples Parsing mathematical expressions
  • 40. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 top Real life examples Parsing mathematical expressions
  • 41. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 push(x) * Real life examples Parsing mathematical expressions
  • 42. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 * Real life examples Parsing mathematical expressions
  • 43. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 * push(x) 2 Real life examples Parsing mathematical expressions
  • 44. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 * 2 Real life examples Parsing mathematical expressions
  • 45. String expr = bottom ( 9 + ( 4 / 2 ) ) * 2 11 * 2 pop()pop()pop() Real life examples Parsing mathematical expressions
  • 46. String expr = ( 9 + ( 4 / 2 ) ) * 2 bottom 22 push(x) top Real life examples Parsing mathematical expressions
  • 47. Using Stacks in Java Declare stack: Stack<Type> stack = new Stack<>(); Push element: stack.push(element); Pop element: stack.pop();
  • 48. Valid Parentheses (L #20) Given a string containing just the characters determine if the input string is valid. An input string is valid if: ● Open brackets must be closed by the same type of brackets. ● Open brackets must be closed in the correct order. ( ) { } [ ]
  • 49. Valid Parentheses (L #20) Test cases Example Output “()” true “()[]{}” true “(]” false “([)]” false “{[]}” true
  • 52. Valid Parentheses (L #20) Time Complexity = O(n) Space Complexity = O(n)
  • 53. Still not convinced… where else would I use stacks? Can you relate to this example?
  • 54. Real life examples Back / Forward Browser Button Back Stack Forward Stack
  • 55. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.comcurrent
  • 56. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.comcurrent
  • 57. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com
  • 58. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.meetup.com
  • 59. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.meetup.com www.linkedin.com
  • 60. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.meetup.com www.linkedin.com
  • 61. Real life examples Back / Forward Browser Button Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.meetup.com www.linkedin.com
  • 62. Real life examples Back / Forward Browser Button
  • 63. Real life examples Back / Forward Browser Button What happens if I write a new URL while I am in Twitter? Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.meetup.com www.linkedin.com
  • 64. Real life examples Back / Forward Browser Button Forward Stack gets cleared Back Stack Forward Stack www.google.com www.facebook.com current www.twitter.com www.gmail.com
  • 65. Remove All Adjacent Duplicates In String (L #1047) Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. Input: "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
  • 66. Remove All Adjacent Duplicates In String (L #1047) Test cases Input: "abbaca" Output: "ca" Input: "abcdeedcba" Output: "" Input: "abcdefg" Output: "abcdefg"
  • 67. Remove All Adjacent Duplicates In String (L #1047) Approach #1 Iterate the string and remove the adjacents. If we find a pair, we set a flag to true indicating we need to iterate again (since we have created a new string) Input: "abcdeedcba" Iteration #1: "abcddcba" Iteration #5: "abba" Iteration #2: "abccba" Iteration #6: "aa" Iteration #3: "abccba" Iteration #7 : "" Iteration #4: "abccba"
  • 68. Remove All Adjacent Duplicates In String (L #1047) Approach #1 Time Complexity = O(n^2) Space Complexity = O(n)
  • 69. Remove All Adjacent Duplicates In String (L #1047) Approach #2 We’ll use a stack this time as our support tool to solve this problem. We’ll iterate the string and we’ll check if the stack has elements and if top of the stack (the previous char) is equal to the element we’re currently checking. If the previous statement is false, add the char to the stack If the previous statement is true, pop the previous char and don’t add the current to the stack
  • 70. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack
  • 71. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack
  • 72. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a
  • 73. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a
  • 74. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a b
  • 75. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a b
  • 76. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a
  • 77. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack a
  • 78. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack
  • 79. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack
  • 80. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack c
  • 81. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack c
  • 82. Remove All Adjacent Duplicates In String (L #1047) a b b a c a Input Stack c a
  • 83. Remove All Adjacent Duplicates In String (L #1047) Final Result c a
  • 84. Remove All Adjacent Duplicates In String (L #1047) Approach #1 Time Complexity = O(n^2) Space Complexity = O(n) Approach #2 Time Complexity = O(n) Space Complexity = O(n)
  • 85. Remove All Adjacent Duplicates In String (L #1047) Approach #1 Time Complexity = O(n^2) Space Complexity = O(n) Approach #2 ← Winner! Time Complexity = O(n) Space Complexity = O(n)
  • 86.
  • 87. Leetcode Problems Easy Remove All Adjacent Duplicates In String (Leetcode #1047) Valid Parentheses (Leetcode #20) Min Stack (Leetcode #155) Decode String (Leetcode #394) Medium Design Browser History (Leetcode #1472) Remove K Digits (Leetcode #402) Online Stock Span (Leetcode #901) Hard Basic Calculator (Leetcode #224)
  • 88. What next? The next session will be about Trees!