CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis ad stregthe ituitio for applyig it to ew problems. Practice usig stacks ad queues to accomplish a variety of tasks. Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture. Each is characterized by a specific way of removig elemets ad has a set of supported operatios. Stack Queue LIFO (last-i-first-out the most recet elemet that has bee added to the stack will be removed first. Supported operatios: push pop peek isempty size FIFO (first-i-first-out the least recet elemet that has bee added to the queue will be removed first. Supported operatios: equeue dequeue peek isempty size Implemetatio Details Stacks ad queues ca be implemeted uder the hood with almost ay data structure. I this course, we will implemet stacks ad queues usig expadable arrays. The rules we will use for icreasig or decreasig the size of a stack or queue s uderlyig array are as follows:. If the array of size is full, create a ew array of size, ad copy all elemets ito the ew array.. If the array of size has elemets i it, create a ew array of size, ad copy all elemets ito the ew array. Problems Problem : Sortig Usig Stacks Give: A full stack S of size ad a empty stack S of size. Objective: Sort the elemets i ascedig order i S. You may oly use the give stacks S ad S (each of size ad O( additioal space. What is the ruig time of your sortig procedure? Example:
Hit: Start with a simpler example: Solutio To solve this problem, we will use the two give stacks, S ad S, ad two extra variables max ad size. Algorithm: Iitialize max to ad size to 0.. pop all elemets from S ad push them oto S. While pop ig, keep track of the maximum elemet we have see so far i max. Oce we have push ed all elemets ito S, the absolute maximum elemet will be stored i max.. pop all elemets from S ad push all except the maximum elemet max back ito S.. push the maximum elemet (stored i max ito S. Now S cotais usorted elemets, ad S cotais sorted elemet.. Icremet size by. We will use size to keep track of the umber of sorted elemets i S so that we do t pop them.. Repeat steps - util size =. I Step, take care to oly pop elemets from S util S cotais exactly size elemets. (The bottom size elemets i S have already bee sorted. Whe the procedure termiates, S will be empty, ad S cotais the elemets i o-decreasig order. Time complexity: The ruig time of our sortig procedure is O(, sice for each elemet that we sort, we must push ad pop at most elemets. Problem : Level-Order traversal of Biary Tree Give: A biary tree of size Objective: Prit out the level order traversal of the biary tree Example: see below Figure : For this tree, your fuctio should prit,,, 7, 6,,.
Solutio Algorithm: We use a queue to hold odes that are to be visited. We first start with the queue cotaiig the root ode of the tree. While the queue is ot empty, we dequeue a elemet from the queue, mark it as visited, ad the equeue its childre ito the queue. for the tree above, we first start with ode i the queue. We remove, mark it as visited, ad add, to the queue. We the remove ad 7, 6 to the queue. We remove ad add, to the queue. Sice all odes i the queue at this poit are leaves, we remove each ode oe by oe util the queue is empty. Problem : Spiral Order Tree Traversal Give: A biary tree T. Objective: Prit the spiral order traversal of the tree T. Example: Hit: Try usig stacks. Solutio Figure : For this tree, your fuctio should prit,,,,, 6, 7. We will use two stacks, S ad S. We will use S to hold elemets i the same level that are beig prited from left to right, ad we will use S to hold elemets i the same level that are beig prited from right to left. We observe that these stacks are disjoit (i.e., they cotai o overlappig elemets, ad if a give ode i T is i S, the its two childre should be i S (ad vice versa. Algorithm: First, push the root of the tree T oto stack S. The followig procedure will loop util both S ad S are empty. While S is ot empty, pop the top elemet from S. Prit. If has a right child, push it oto the other stack S. The, if has a left child, push it oto S. Cotiue this step util S is empty. While S is ot empty, pop the top elemet from S. Prit. If has a left child, push it oto the other stack S. The, if has a right child, push it oto S. Cotiue this step util S is empty. Time ad space complexity: If the tree T cotais odes, this solutio takes O( time ad O( extra space.
Amortized Aalysis Amortized aalysis refers to fidig the time-averaged cost for a sequece of operatios. I other words, it is the time required to perform a sequece of operatios averaged over all the operatios performed. Sice amortized aalysis for the stack push operatio was covered i lecture, we are goig to take a closer look at the stack pop operatio. The worst case ruig time for a sigle pop operatio is O(, sice we may eed to resize the array ad copy the elemets ito it. Based o this ruig time, we might coclude that a tight boud for the worst case ruig time for pop operatios is O(, sice there are operatios ad each operatio takes worst case O( time; however, we ca fid a tighter boud through some careful aalysis. If we start from a full stack of size, what is the total cost of a sequece of pop operatios? Iitially, the array is of size ad cotais elemets. To make our aalysis simpler, let s immediately pop the first elemets. Each of these pops takes O( time. Now our array is of size but cotais oly elemets. I accordace with our rules, we ca pop more elemets before resizig the array. Each of these pops takes O( time. Oce we have pop d those elemets (leavig us with elemets i our array, we must reduce the size of our array to, ad copy the remaiig elemets ito the ew array. Thus, the total cost for the first pop operatios is T ( = + + +. We ca apply idetical aalysis to the ew array of size that cotais elemets. We get ( = ( 8 pops for free, after which we resize the array to be of size = ad copy the remaiig ( = 8 elemets ( ito the smaller array. Thus, the total cost for the first 7 8 pop operatios is T ( 7 8 = + + + + 8 + + 8. Are you oticig a patter? Let s rewrite the expressio slightly ad cotiue to expad it: T ( = + ( 0 + 0 + ( 0 + + ( + We ca ow calculate the total cost of pop operatios: T ( + i=0 = + = + = O( i=0 + + + + + + ( i + i + i i ( ( + ( + ( (The first term i the summatio is the cost of the iitial pops, the secod term is the cost of allocatig a ew array, ad the third term is the cost of copyig the remaiig elemets ito the ew array. Thus, the amortized time complexity of a pop operatio is = O(, eve though the worst case time complexity of a sigle pop operatio is O(. Problem : Queue With Two Stacks Give: Two stacks S ad S, each of size. Objective: Implemet a queue usig S ad S. Your queue s equeue ad dequeue methods should be implemeted usig oly your stacks push, pop, ad/or peek methods. What are the ruig times of your ew queue s equeue ad dequeue methods?
Solutio equeue(x:. push x ito S. dequeue:. If S is empty, pop all elemets from S ad push them ito S.. If S is still empty, retur Nil.. Else pop a elemet from S ad retur it. Time complexity: The ruig time of equeue(x is clearly O(. The ruig time for dequeue is a bit trickier. If we cosider that each elemet will be i each Stack exactly oce, the we realize that each elemet will be pushed exactly twice ad popped exactly twice. Thus, the amortized ruig time of dequeue is O(.