SlideShare a Scribd company logo
Stack and Queue
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Table of Contents
1. Stack - Last In First Out (LIFO)
• Stack Functionality
• Java Stack Implementation
• Overview of All Operations
2. Queue - First In First Out (FIFO)
• Queue Functionality
• Java Stack Implementation
• Overview of All Operations
3. Priority Queue
sli.do
#java-advanced
Have a Question?
 Describes performance of particular algorithm
 Runtime and memory consumption based on the input size N
 We usually care about the worst-case performance
 We measure the complexity as the Big O notation
 Numerical function depending on the input size O(N)
 We measure time as the number of simple steps
 We measure memory as input data N by it's type size
Algorithmic Complexity
 O(1) – Constant time – time does not depend on N
 O(log(N)) – Logarithmic time – grows with rate as log(N)
 O(N) – Linear time grows at the same rate as N
 O(N^2),O(N^3) – Quadratic, Cubic grows as square or cube of N
 O(2^N) – Exponential grows as N becomes the exponent worst
algorithmic complexity
 For input size of 10 - 1024 steps
 For input size of 100 – 1267650600228229401496703205376
steps
 http://bigocheatsheet.com/
Algorithmic Complexity
 Calculate maximum steps to find sum of even elements in an array
 Assume that a single step is a single CPU instruction:
 assignments, array lookups, comparisons, arithmetic operations
Get Sum Number of Steps
int getSumEven(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++)
if (array[i] % 2 == 0) sum += array[i];
return sum;
}
Solution:
T(n) = 9n + 3
Counting maximum steps is
called worst-case analysis
 Worst-case
 An upper bound on the running time
 Average-case
 Average running time
 Best-case
 The lower bound on the running time
(the optimal case)
Time Complexity
 Why don't use Stack and Queue?
 Implementation details which make unsecure usability
 In many cases those structures will decrease the performance
 Why to use ArrayDeque?
 Implementation which makes the structure more secure
 Better performance and usability
 Methods which operate as those structures suggest
Stacks And Queue vs. ArrayDeque
Stack
Last In First Out (LIFO)
 Stacks provide the following functionality:
 Pushing an element at the top of the stack
 Popping element from the top fo the stack
 Getting the topmost element without removing it
Stack Functionality
2
10
5
2
10
5
2
10
5
Push Pop Peek
ArrayDeque<E> – Java Stack Implementation
 Creating a Stack
 Adding elements at the top of the stack
 Removing elements
 Getting the value of the topmost element
stack.push(element);
ArrayDeque<Integer> stack = new ArrayDeque<>();
Integer element = stack.pop();
Integer element = stack.peek();
Stack – Utility Methods
ArrayDeque<Integer> stack = new ArrayDeque<>();
int size = stack.size();
boolean isEmpty = stack.isEmpty();
boolean exists = stack.contains(2);
012
5
3
210515
13
Stack – Overview of All Operations
size():
5
-7
45
132
push()
pop()
peek()
Stack<Integer>
 Write a program which takes 2 types of browser instructions:
 Normal navigation: a URL is set, given by a string
 The string "back" that sets the current URL to the last set URL
Problem: Browser History
https//softuni.bg/
back
https//softuni.bg/trainings/courses
back
https//softuni.bg/trainings/2056
back
https//softuni.bg/trainings/live
https//softuni.bg/trainings/live/details
Home
Input
https//softuni.bg/
no previous URLs
https//softuni.bg/trainings/courses
https//softuni.bg/
https//softuni.bg/trainings/2056
https//softuni.bg/
https//softuni.bg/trainings/live
https//softuni.bg/trainings/live/details
Output
Scanner scanner = new Scanner(System.in);
ArrayDeque<String> browser = new ArrayDeque<>();
String line = scanner.nextLine();
String current = "";
// continue…
Solution: Browser History (1)
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
while(!line.equals("Home")) {
if(line.equals("back")) {
if(!browser.isEmpty()) {current = browser.pop();
} else {
System.out.println("no previous URLs");
line = scanner.nextLine();
continue;}
} else {
if(!current.equals("")) { browser.push(current); }
current = line; }
System.out.println(current);
line = scanner.nextLine(); }
Solution: Browser History (2)
 Implement a simple calculator that can evaluate simple
expressions (only addition and subtraction)
Problem: Simple Calculator
2 + 5 + 10 - 2 - 1
Input
2 - 2 + 5
14
Output
5
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Simple Calculator (1)
Scanner scanner = new Scanner(System.in);
String[] tokens = scanner.nextLine().split("s+");
Deque<String> stack = new ArrayDeque<>();
Collections.addAll(stack, tokens);
// continues…
Split by regex
Adds a collection to
another collection
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Simple Calculator (2)
while (stack.size() > 1) {
int first = Integer.valueOf(stack.pop());
String op = stack.pop();
int second = Integer.valueOf(stack.pop());
switch (op)
case "+": stack.push(String.valueOf(first + second));
break;
case "-": stack.push(String.valueOf(first - second));
break;
}
System.out.println(stack.pop());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 Create a converter which takes a decimal number and
converts it into a binary number
Problem: Decimal To Binary Converter
10
Input
1024
1010
Output
10000000000
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Decimal To Binary Converter
Scanner scanner = new Scanner(System.in);
int decimal = Integer.valueOf(scanner.nextLine());
ArrayDeque<Integer> stack = new ArrayDeque<>();
// TODO: check if number is 0
while (decimal != 0)
stack.push(decimal % 2);
decimal /= 2;
while (!stack.isEmpty())
System.out.print(stack.pop());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 We are given an arithmetical expression with brackets (with nesting)
 Goal: extract all sub-expressions in brackets
Problem: Matching Brackets
1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5
(2 + 3)
(3 + 1)
(2 - (2 + 3) * 4 / (3 + 1))
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Matching Brackets (1)
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
Deque<Integer> stack = new ArrayDeque<>();
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Matching Brackets (2)
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == '(')
stack.push(i);
else if (ch == ')')
int startIndex = stack.pop();
String contents =
expression.substring(startIndex, i + 1);
System.out.println(contents);
}
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Queues
First In First Out (FIFO)
 First In First Out
Queue
26
210 5
 Queues provide the following functionality:
 Adding an element at the end of the queue
 Removing the first element from the queue
 Getting the first element of the queue without removing it
Queue – Abstract Data Type
210 5
210 5
210 5
 Creating a Queue
 Adding elements at the end of the queue
 add() – throws exception if queue is full
 offer() – returns false if queue is full
ArrayDeque<E> – Java Queue Implementation
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(element);
queue.offer(element);
 Removing elements
 remove() - throws exception if queue is empty
 poll() - returns null if queue is empty
 Check first element
ArrayDeque<E> – Java Queue Implementation (2)
element = queue.remove();
element = queue.poll();
element = queue.peek();
 Adds an element to the queue
add() / offer()
-315121
32104
5
size():Queue<Integer>
 Returns and removes first element
remove() / poll()
423
5
size():Queue<Integer>
-315121
 Children form a circle and pass a hot potato clockwise
 Every nth toss a child is removed until only one remains
 Upon removal the potato is passed forward
 Print the child that remains last
Problem: Hot Potato
Mimi Pepi Toshko
2
Input
Removed Pepi
Removed Mimi
Last is Toshko
Output
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Hot Potato (1)
Scanner scanner = new Scanner(System.in);
String[] children = scanner.nextLine().split("s+");
int n = Integer.valueOf(scanner.nextLine());
ArrayDeque<String> queue = new ArrayDeque<>();
for (String child : children)
queue.offer(child);
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Hot Potato (2)
while (queue.size() > 1) {
for (int i = 1; i < n; i++)
queue.offer(queue.poll());
System.out.println("Removed " + queue.poll());
}
System.out.println("Last is " + queue.poll());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 Utility Methods
 peek() - checks the value of the first element
 size() - returns queue size
 toArray() - converts the queue to an array
 contains() - checks if element is in the queue
ArrayDeque<E> – Java Queue Implementation (3)
Integer element = queue.peeк();
Integer size = queue.size();
Integer[] arr = queue.toArray();
boolean exists = queue.contains(element);
 Gets the first element without removing it
peek()
1515
2size():Queue<Integer>
121
 Rework the previous problem so that a child is removed only on
a prime cycle (cycles start from 1)
 If a cycle is not prime, just print the child's name
Problem: Math Potato
Mimi Pepi Toshko
2
Input
Removed Pepi
Prime Mimi
Prime Toshko
Removed Mimi
Last is Toshko
Output
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Math Potato
int cycle = 1;
while (queue.size() > 1) {
for (int i = 1; i < n; i++)
queue.offer(queue.poll());
if (isPrime(cycle))
System.out.println("Prime " + queue.peek());
else
System.out.println("Removed " + queue.poll());
cycle++;
}
System.out.println("Last is " + queue.poll());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Queue – Overview of All Operations
5-315
4
121
012size():Queue<Integer>
5
3
15
peek() remove()add()
 Retains a specific order to the elements
 Higher priority elements are pushed to the
beginning of the queue
 Lower priority elements are pushed to the end of the queue
Priority Queue
AC B
 …
 …
 …
Summary
41
 Stack - Last In First Out (LIFO)
 push(), pop(), peek()
 Queue - First In First Out (FIFO)
 add(), poll(), peek()
 Priority Queue
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
46

More Related Content

PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
17. Java data structures trees representation and traversal
Intro C# Book
 
PPTX
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
PPTX
Java Foundations: Methods
Svetlin Nakov
 
PPTX
Exception handling
PhD Research Scholar
 
PDF
Java ArrayList Tutorial | Edureka
Edureka!
 
PPTX
20.2 Java inheritance
Intro C# Book
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
20.3 Java encapsulation
Intro C# Book
 
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Java Foundations: Methods
Svetlin Nakov
 
Exception handling
PhD Research Scholar
 
Java ArrayList Tutorial | Edureka
Edureka!
 
20.2 Java inheritance
Intro C# Book
 

What's hot (20)

PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PDF
Array data structure
maamir farooq
 
PPTX
Java String
SATYAM SHRIVASTAV
 
PPTX
15. Streams Files and Directories
Intro C# Book
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Java Foundations: Arrays
Svetlin Nakov
 
PPTX
Java Stack Data Structure.pptx
vishal choudhary
 
PPTX
Strings in c#
Dr.Neeraj Kumar Pandey
 
PPTX
collection framework in java
MANOJ KUMAR
 
PPTX
PL/SQL - CURSORS
IshaRana14
 
PPTX
20.4 Java interfaces and abstraction
Intro C# Book
 
PDF
5 collection framework
Minal Maniar
 
PDF
Sql queries questions and answers
Michael Belete
 
PDF
Web technology lab manual
neela madheswari
 
PPT
Advanced Topics On Sql Injection Protection
amiable_indian
 
DOC
SQL practice questions - set 3
Mohd Tousif
 
PPTX
Hashing Technique In Data Structures
SHAKOOR AB
 
PPT
Collection Framework in java
CPD INDIA
 
PPTX
Exception Handling in C#
Abid Kohistani
 
PPTX
Inheritance
Sapna Sharma
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Array data structure
maamir farooq
 
Java String
SATYAM SHRIVASTAV
 
15. Streams Files and Directories
Intro C# Book
 
9. Input Output in java
Nilesh Dalvi
 
Java Foundations: Arrays
Svetlin Nakov
 
Java Stack Data Structure.pptx
vishal choudhary
 
Strings in c#
Dr.Neeraj Kumar Pandey
 
collection framework in java
MANOJ KUMAR
 
PL/SQL - CURSORS
IshaRana14
 
20.4 Java interfaces and abstraction
Intro C# Book
 
5 collection framework
Minal Maniar
 
Sql queries questions and answers
Michael Belete
 
Web technology lab manual
neela madheswari
 
Advanced Topics On Sql Injection Protection
amiable_indian
 
SQL practice questions - set 3
Mohd Tousif
 
Hashing Technique In Data Structures
SHAKOOR AB
 
Collection Framework in java
CPD INDIA
 
Exception Handling in C#
Abid Kohistani
 
Inheritance
Sapna Sharma
 
Ad

Similar to 16. Java stacks and queues (20)

PPT
Introduzione al TDD
Andrea Francia
 
PDF
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
PDF
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
Asuka Nakajima
 
PDF
New Functional Features of Java 8
franciscoortin
 
PDF
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
ODT
Java practical
william otto
 
PPT
Queue in Data Structure
Muhazzab Chouhadry
 
DOCX
object oriented programming lab manual .docx
Kirubaburi R
 
DOC
Ds lab manual by s.k.rath
SANTOSH RATH
 
PPT
05-stack_queue.ppt
Sarojkumari55
 
PPTX
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
ODP
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
PDF
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
PDF
Lazy Java
J On The Beach
 
PDF
Lazy Java
Nicola Pedot
 
PDF
Lazy java
Mario Fusco
 
PDF
A Deep Dive into Structured Streaming in Apache Spark
Anyscale
 
PPTX
DSA 103 Object Oriented Programming :: Week 4
Ferdin Joe John Joseph PhD
 
PPTX
Appium TestNG Framework and Multi-Device Automation Execution
pCloudy
 
PPT
computer notes - Data Structures - 9
ecomputernotes
 
Introduzione al TDD
Andrea Francia
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
Asuka Nakajima
 
New Functional Features of Java 8
franciscoortin
 
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
Java practical
william otto
 
Queue in Data Structure
Muhazzab Chouhadry
 
object oriented programming lab manual .docx
Kirubaburi R
 
Ds lab manual by s.k.rath
SANTOSH RATH
 
05-stack_queue.ppt
Sarojkumari55
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
Lazy Java
J On The Beach
 
Lazy Java
Nicola Pedot
 
Lazy java
Mario Fusco
 
A Deep Dive into Structured Streaming in Apache Spark
Anyscale
 
DSA 103 Object Oriented Programming :: Week 4
Ferdin Joe John Joseph PhD
 
Appium TestNG Framework and Multi-Device Automation Execution
pCloudy
 
computer notes - Data Structures - 9
ecomputernotes
 
Ad

More from Intro C# Book (20)

PPTX
Java Problem solving
Intro C# Book
 
PPTX
21. Java High Quality Programming Code
Intro C# Book
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
PPTX
14. Java defining classes
Intro C# Book
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPTX
09. Java Methods
Intro C# Book
 
PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
01. Introduction to programming with java
Intro C# Book
 
PPTX
23. Methodology of Problem Solving
Intro C# Book
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
PPTX
21. High-Quality Programming Code
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
Intro C# Book
 
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 
14. Java defining classes
Intro C# Book
 
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 

Recently uploaded (20)

PPTX
nagasai stick diagrams in very large scale integratiom.pptx
manunagapaul
 
PPTX
dns domain name system history work.pptx
MUHAMMADKAVISHSHABAN
 
PPTX
Different Generation Of Computers .pptx
divcoder9507
 
PDF
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 
PPTX
The Latest Scam Shocking the USA in 2025.pptx
onlinescamreport4
 
PPTX
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PPTX
EthicalHack{aksdladlsfsamnookfmnakoasjd}.pptx
dagarabull
 
PPTX
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PPTX
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
PDF
Cybersecurity Awareness Presentation ppt.
banodhaharshita
 
PPT
Transformaciones de las funciones elementales.ppt
rirosel211
 
PDF
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
PPTX
Crypto Recovery California Services.pptx
lionsgate network
 
PPT
Introduction to dns domain name syst.ppt
MUHAMMADKAVISHSHABAN
 
PDF
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
PDF
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
PPTX
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
PDF
5g is Reshaping the Competitive Landscape
Stellarix
 
nagasai stick diagrams in very large scale integratiom.pptx
manunagapaul
 
dns domain name system history work.pptx
MUHAMMADKAVISHSHABAN
 
Different Generation Of Computers .pptx
divcoder9507
 
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 
The Latest Scam Shocking the USA in 2025.pptx
onlinescamreport4
 
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
EthicalHack{aksdladlsfsamnookfmnakoasjd}.pptx
dagarabull
 
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
Cybersecurity Awareness Presentation ppt.
banodhaharshita
 
Transformaciones de las funciones elementales.ppt
rirosel211
 
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
Crypto Recovery California Services.pptx
lionsgate network
 
Introduction to dns domain name syst.ppt
MUHAMMADKAVISHSHABAN
 
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
5g is Reshaping the Competitive Landscape
Stellarix
 

16. Java stacks and queues

  • 1. Stack and Queue Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. Table of Contents 1. Stack - Last In First Out (LIFO) • Stack Functionality • Java Stack Implementation • Overview of All Operations 2. Queue - First In First Out (FIFO) • Queue Functionality • Java Stack Implementation • Overview of All Operations 3. Priority Queue
  • 4.  Describes performance of particular algorithm  Runtime and memory consumption based on the input size N  We usually care about the worst-case performance  We measure the complexity as the Big O notation  Numerical function depending on the input size O(N)  We measure time as the number of simple steps  We measure memory as input data N by it's type size Algorithmic Complexity
  • 5.  O(1) – Constant time – time does not depend on N  O(log(N)) – Logarithmic time – grows with rate as log(N)  O(N) – Linear time grows at the same rate as N  O(N^2),O(N^3) – Quadratic, Cubic grows as square or cube of N  O(2^N) – Exponential grows as N becomes the exponent worst algorithmic complexity  For input size of 10 - 1024 steps  For input size of 100 – 1267650600228229401496703205376 steps  http://bigocheatsheet.com/ Algorithmic Complexity
  • 6.  Calculate maximum steps to find sum of even elements in an array  Assume that a single step is a single CPU instruction:  assignments, array lookups, comparisons, arithmetic operations Get Sum Number of Steps int getSumEven(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) if (array[i] % 2 == 0) sum += array[i]; return sum; } Solution: T(n) = 9n + 3 Counting maximum steps is called worst-case analysis
  • 7.  Worst-case  An upper bound on the running time  Average-case  Average running time  Best-case  The lower bound on the running time (the optimal case) Time Complexity
  • 8.  Why don't use Stack and Queue?  Implementation details which make unsecure usability  In many cases those structures will decrease the performance  Why to use ArrayDeque?  Implementation which makes the structure more secure  Better performance and usability  Methods which operate as those structures suggest Stacks And Queue vs. ArrayDeque
  • 9. Stack Last In First Out (LIFO)
  • 10.  Stacks provide the following functionality:  Pushing an element at the top of the stack  Popping element from the top fo the stack  Getting the topmost element without removing it Stack Functionality 2 10 5 2 10 5 2 10 5 Push Pop Peek
  • 11. ArrayDeque<E> – Java Stack Implementation  Creating a Stack  Adding elements at the top of the stack  Removing elements  Getting the value of the topmost element stack.push(element); ArrayDeque<Integer> stack = new ArrayDeque<>(); Integer element = stack.pop(); Integer element = stack.peek();
  • 12. Stack – Utility Methods ArrayDeque<Integer> stack = new ArrayDeque<>(); int size = stack.size(); boolean isEmpty = stack.isEmpty(); boolean exists = stack.contains(2);
  • 13. 012 5 3 210515 13 Stack – Overview of All Operations size(): 5 -7 45 132 push() pop() peek() Stack<Integer>
  • 14.  Write a program which takes 2 types of browser instructions:  Normal navigation: a URL is set, given by a string  The string "back" that sets the current URL to the last set URL Problem: Browser History https//softuni.bg/ back https//softuni.bg/trainings/courses back https//softuni.bg/trainings/2056 back https//softuni.bg/trainings/live https//softuni.bg/trainings/live/details Home Input https//softuni.bg/ no previous URLs https//softuni.bg/trainings/courses https//softuni.bg/ https//softuni.bg/trainings/2056 https//softuni.bg/ https//softuni.bg/trainings/live https//softuni.bg/trainings/live/details Output
  • 15. Scanner scanner = new Scanner(System.in); ArrayDeque<String> browser = new ArrayDeque<>(); String line = scanner.nextLine(); String current = ""; // continue… Solution: Browser History (1) Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 16. while(!line.equals("Home")) { if(line.equals("back")) { if(!browser.isEmpty()) {current = browser.pop(); } else { System.out.println("no previous URLs"); line = scanner.nextLine(); continue;} } else { if(!current.equals("")) { browser.push(current); } current = line; } System.out.println(current); line = scanner.nextLine(); } Solution: Browser History (2)
  • 17.  Implement a simple calculator that can evaluate simple expressions (only addition and subtraction) Problem: Simple Calculator 2 + 5 + 10 - 2 - 1 Input 2 - 2 + 5 14 Output 5 Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 18. Solution: Simple Calculator (1) Scanner scanner = new Scanner(System.in); String[] tokens = scanner.nextLine().split("s+"); Deque<String> stack = new ArrayDeque<>(); Collections.addAll(stack, tokens); // continues… Split by regex Adds a collection to another collection Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 19. Solution: Simple Calculator (2) while (stack.size() > 1) { int first = Integer.valueOf(stack.pop()); String op = stack.pop(); int second = Integer.valueOf(stack.pop()); switch (op) case "+": stack.push(String.valueOf(first + second)); break; case "-": stack.push(String.valueOf(first - second)); break; } System.out.println(stack.pop()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 20.  Create a converter which takes a decimal number and converts it into a binary number Problem: Decimal To Binary Converter 10 Input 1024 1010 Output 10000000000 Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 21. Solution: Decimal To Binary Converter Scanner scanner = new Scanner(System.in); int decimal = Integer.valueOf(scanner.nextLine()); ArrayDeque<Integer> stack = new ArrayDeque<>(); // TODO: check if number is 0 while (decimal != 0) stack.push(decimal % 2); decimal /= 2; while (!stack.isEmpty()) System.out.print(stack.pop()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 22.  We are given an arithmetical expression with brackets (with nesting)  Goal: extract all sub-expressions in brackets Problem: Matching Brackets 1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5 (2 + 3) (3 + 1) (2 - (2 + 3) * 4 / (3 + 1)) Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 23. Solution: Matching Brackets (1) Scanner scanner = new Scanner(System.in); String expression = scanner.nextLine(); Deque<Integer> stack = new ArrayDeque<>(); // continue… Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 24. Solution: Matching Brackets (2) for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (ch == '(') stack.push(i); else if (ch == ')') int startIndex = stack.pop(); String contents = expression.substring(startIndex, i + 1); System.out.println(contents); } Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 25. Queues First In First Out (FIFO)
  • 26.  First In First Out Queue 26 210 5
  • 27.  Queues provide the following functionality:  Adding an element at the end of the queue  Removing the first element from the queue  Getting the first element of the queue without removing it Queue – Abstract Data Type 210 5 210 5 210 5
  • 28.  Creating a Queue  Adding elements at the end of the queue  add() – throws exception if queue is full  offer() – returns false if queue is full ArrayDeque<E> – Java Queue Implementation ArrayDeque<Integer> queue = new ArrayDeque<>(); queue.add(element); queue.offer(element);
  • 29.  Removing elements  remove() - throws exception if queue is empty  poll() - returns null if queue is empty  Check first element ArrayDeque<E> – Java Queue Implementation (2) element = queue.remove(); element = queue.poll(); element = queue.peek();
  • 30.  Adds an element to the queue add() / offer() -315121 32104 5 size():Queue<Integer>
  • 31.  Returns and removes first element remove() / poll() 423 5 size():Queue<Integer> -315121
  • 32.  Children form a circle and pass a hot potato clockwise  Every nth toss a child is removed until only one remains  Upon removal the potato is passed forward  Print the child that remains last Problem: Hot Potato Mimi Pepi Toshko 2 Input Removed Pepi Removed Mimi Last is Toshko Output Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 33. Solution: Hot Potato (1) Scanner scanner = new Scanner(System.in); String[] children = scanner.nextLine().split("s+"); int n = Integer.valueOf(scanner.nextLine()); ArrayDeque<String> queue = new ArrayDeque<>(); for (String child : children) queue.offer(child); // continue… Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 34. Solution: Hot Potato (2) while (queue.size() > 1) { for (int i = 1; i < n; i++) queue.offer(queue.poll()); System.out.println("Removed " + queue.poll()); } System.out.println("Last is " + queue.poll()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 35.  Utility Methods  peek() - checks the value of the first element  size() - returns queue size  toArray() - converts the queue to an array  contains() - checks if element is in the queue ArrayDeque<E> – Java Queue Implementation (3) Integer element = queue.peeк(); Integer size = queue.size(); Integer[] arr = queue.toArray(); boolean exists = queue.contains(element);
  • 36.  Gets the first element without removing it peek() 1515 2size():Queue<Integer> 121
  • 37.  Rework the previous problem so that a child is removed only on a prime cycle (cycles start from 1)  If a cycle is not prime, just print the child's name Problem: Math Potato Mimi Pepi Toshko 2 Input Removed Pepi Prime Mimi Prime Toshko Removed Mimi Last is Toshko Output Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 38. Solution: Math Potato int cycle = 1; while (queue.size() > 1) { for (int i = 1; i < n; i++) queue.offer(queue.poll()); if (isPrime(cycle)) System.out.println("Prime " + queue.peek()); else System.out.println("Removed " + queue.poll()); cycle++; } System.out.println("Last is " + queue.poll()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 39. Queue – Overview of All Operations 5-315 4 121 012size():Queue<Integer> 5 3 15 peek() remove()add()
  • 40.  Retains a specific order to the elements  Higher priority elements are pushed to the beginning of the queue  Lower priority elements are pushed to the end of the queue Priority Queue AC B
  • 41.  …  …  … Summary 41  Stack - Last In First Out (LIFO)  push(), pop(), peek()  Queue - First In First Out (FIFO)  add(), poll(), peek()  Priority Queue
  • 45.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 46.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 46