Hacking a Google Interview Handout 2

Size: px
Start display at page:

Download "Hacking a Google Interview Handout 2"

Transcription

1 HackingaGoogleInterview Handout2 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin Website: ClassicQuestion#4:Reversingthewordsinastring Writeafunctiontoreversetheorderofwordsinastringinplace. Answer:Reversethestringbyswappingthefirstcharacterwiththelastcharacter, thesecondcharacterwiththesecond to lastcharacter,andsoon.then,gothrough thestringlookingforspaces,sothatyoufindwhereeachofthewordsis.reverse eachofthewordsyouencounterbyagainswappingthefirstcharacterwiththelast character,thesecondcharacterwiththesecond to lastcharacter,andsoon. Sorting Often,aspartofasolutiontoaquestion,youwillneedtosortacollectionof elements.themostimportantthingtorememberaboutsortingisthatittakeso(n logn)time.(thatis,thefastestsortingalgorithmforarbitrarydatatakeso(nlogn) time.) MergeSort: Mergesortisarecursivewaytosortanarray.First,youdividethearrayinhalfand recursivelysorteachhalfofthearray.then,youcombinethetwohalvesintoa sortedarray.soamergesortfunctionwouldlooksomethinglikethis: int[] mergesort(int[] array) { if (array.length <= 1) return array; int middle = array.length / 2; int firsthalf = mergesort(array[0..middle - 1]); int secondhalf = mergesort( array[middle..array.length - 1]); return merge(firsthalf, secondhalf); Thealgorithmreliesonthefactthatonecanquicklycombinetwosortedarraysinto asinglesortedarray.onecandosobykeepingtwopointersintothetwosorted

2 arrays.onerepeatedlyaddsthesmallerofthetwonumberspointedtotothenew arrayandadvancesthepointer. Quicksort: Quicksortisanothersortingalgorithm.IttakesO(n^2)timeintheworstcaseand O(nlogn)expectedtime. Tosortanarrayusingquicksort,onefirstselectsarandomelementofthearrayto bethe"pivot".onethendividesthearrayintotwogroups:agroupofelementsthat arelessthanthepivotandagroupofelementsthataregreaterthanthepivot.after this,therewillbeanarrayconsistingofelementslessthanthepivot,followedbythe pivot,followedbyelementsgreaterthanthepivot.then,onerecursivelysortsthe portionofthearraybeforethepivotandtheportionofthearrayafterthepivot.a quicksortfunctionwouldlooklikethis: void quicksort(int[] array, int startindex, int endindex) { if (startindex >= endindex) { // Base case (array segment has 1 or 0 elements else { int pivotindex = partition(array, startindex, endindex); quicksort(array, startindex, pivotindex - 1); quicksort(array, pivotindex + 1, endindex); Quicksortistypicallyveryfastinpractice,butrememberthatithasO(n^2)worstcaserunningtime,sobesuretomentionanothersortingalgorithm,suchasmerge sort,ifyouneedguaranteedo(nlogn)runningtime. OrderStatistics: Sometimes,aninterviewerwillaskyoutodescribeanalgorithmtoidentifythekth smallestelementinanarrayofnelements.todothis,youselectarandompivot andpartitionthearrayasyouwouldinthequicksortalgorithm.then,basedonthe indexofthepivotelement,youknowwhichhalfofthearraythedesiredelementlies in.forexample,sayk=15andn=30,andafteryouselectyourpivotandpartition thearray,thefirsthalfhas10elements(thehalfbeforethepivot).youknowthat thedesiredelementisthe4thsmallestelementinthelargerhalf.toidentifythe element,youpartitionthesecondhalfofthearrayandcontinuerecursively.the reasonthatthisisnoto(nlogn)isthattherecursivepartitioncallisonlyonone halfofthearray,sotheexpectedrunningtimeisn+(n/2)+(n/4)+(n/8)+...= O(n).

3 Notethatfindingthemedianofanarrayisaspecialcaseofthiswherek=n/2. Thisisaveryimportantpoint,asaninterviewerwilloftenaskyoutofindawayto getthemedianofanarrayofnumbers. Question:NearestNeighbor Sayyouhaveanarraycontaininginformationregardingnpeople.Eachpersonis describedusingastring(theirname)andanumber(theirpositionalonganumber line).eachpersonhasthreefriends,whicharethethreepeoplewhosenumberis nearesttheirown.describeanalgorithmtoidentifyeachperson'sthreefriends. Goodanswer:Sortthearrayinascendingorderofthepeople'snumber.Foreach person,checkthethreepeopleimmediatelybeforeandafterthem.theirthree friendswillbeamongthesesixpeople.thisalgorithmtakeso(nlogn)time,since sortingthepeopletakesthatmuchtime. LinkedLists Alinkedlistisabasicdatastructure.Eachnodeinalinkedlistcontainsanelement andapointertothenextnodeinthelinkedlist.thelastnodehasa"null"pointerto indicatethatthereisnonextnode.alistmayalsobedoublylinked,inwhichcase eachnodealsohasapointertothepreviousnode.ittakesconstant(o(1))timeto addanodetoorremoveanodefromalinkedlist(ifyoualreadyhaveapointerto thatnode).ittakeso(n)timetolookupanelementinalinkedlistifyoudon't alreadyhaveapointertothatnode. ClassicQuestion#5:CycleinaLinkedList Howcanonedeterminewhetherasinglylinkedlisthasacycle? Goodanswer:Keeptrackoftwopointersinthelinkedlist,andstartthematthe beginningofthelinkedlist.ateachiterationofthealgorithm,advancethefirst pointerbyonenodeandthesecondpointerbytwonodes.ifthetwopointersare everthesame(otherthanatthebeginningofthealgorithm),thenthereisacycle.if apointereverreachestheendofthelinkedlistbeforethepointersarethesame, thenthereisnocycle.actually,thepointersneednotmoveoneandtwonodesata time;itisonlynecessarythatthepointersmoveatdifferentrates.thistakeso(n) time.thisisatrickyanswerthatinterviewersreallylikeforsomereason. Okayanswer:Foreverynodeyouencounterwhilegoingthroughthelistonebyone, putapointertothatnodeintoao(1) lookuptimedatastructure,suchasahashset. Then,whenyouencounteranewnode,seeifapointertothatnodealreadyexistsin yourhashset.thisshouldtakeo(n)time,butalsotakeso(n)space.

4 Okayanswer:Gothroughtheelementsofthelist."Mark"eachnodethatyoureach. Ifyoureachamarkednodebeforereachingtheend,thelisthasacycle;otherwise,it doesnot.thisalsotakeso(n)time. Notethatthisquestionistechnicallyill posed.anordinarylinkedlistwillhaveno cycles.whattheyactuallymeanisforyoutodeterminewhetheryoucanreacha cyclefromanodeinagraphconsistingofnodesthathaveatmostoneoutgoing edge. StacksandQueues Aninterviewerwillprobablyexpectyoutoknowwhatqueuesandstacksare. Queuesareabstractdatatypes.Aqueueisjustlikealineofpeopleatanamusement park.aqueuetypicallyhastwooperations:enqueueanddequeue.enqueueingan elementaddsittothequeue.dequeueinganelementremovesandreturnsthe elementthatwasaddedleastrecently.aqueueissaidtobefifo(first in,first out). Astackisanotherabstractdatatypewithtwocommonoperations:pushandpop. Pushinganelementaddsittothestack.Poppinganelementremovesandreturns theelementthatwasaddedmostrecently.astackissaidtobelifo(last in,firstout).astackoperateslikeastackofcafeteriatrays. HashTables Ahashtableisusedtoassociatekeyswithvalues,sothateachkeyisassociatedwith oneorzerovalues.eachkeyshouldbeabletocomputea"hash"function,which takessomeorallofitsinformationanddigestsitintoasingleinteger.thehash tableconsistsofanarrayofhashbuckets.toaddakey valuepairtoahashtable, onecomputesthekey'shashcodeandusesittodecidethehashbucketinwhichthe mappingbelongs.forexample,ifthehashvalueis53andthereare8hashbuckets, onemightusethemodfunctiontodecidetoputthemappinginbucket53mod8, whichisbucket5.tolookupthevalueforagivenkey,onecomputesthebucketin whichthekeywouldresideandcheckswhetherthekeyisthere;ifso,onecan returnthevaluestoredinthatbucket.toremovethemappingforagivenkey,one likewiselocatesthekey'smappingandremovesitfromtheappropriatebucket. Notethatthehashfunctionisgenerallydecidedoninadvance. Aproblemariseswhentwokeyshashtothesamebucket.Thiseventiscalleda "collision".thereareseveralwaystodealwiththis.onewayistostorealinkedlist ofkey valuepairsforeachbucket. Insertion,removal,andlookuptakeexpectedO(1)time,providedthatthehash functionissufficiently"random".intheworst case,eachkeyhashestothesame bucket,soeachoperationtakeso(n)time.inpractice,itiscommontoassume constanttime.

5 Hashtablescanoftenbeusedassmallercomponentsofanswerstoquestions.In ourexperience,someinterviewerslikehashtablesandsomedon't.thatis,some interviewerswillallowyoutoassumeconstanttime,whileotherswillnot.ifyou wanttouseahashtable,werecommendsubtlytryingtofigureoutwhichcategory yourinterviewerbelongsto.youmight,forexample,saysomethinglike,"well,i couldusedahashtable,butthatwouldhavebadworst caseperformance."the interviewermightthenindicatethathe'llallowyoutouseahashtable. ClassicQuestion#6:Datastructureforanagrams GivenanEnglishwordintheformofastring,howcanyouquicklyfindallvalid anagramsforthatstring(allvalidrearrangementsofthelettersthatformvalid Englishwords)?Youareallowedtopre computewhateveryouwanttoandstore whateveryouoptionallypre computeondisk. Answer:Wewanttouseahashtable!Ifyourinterviewerreallyhateshashtables (whichtheysometimesdoforsomereason),youcanuseatreeinstead.butlet's assumeyoucanuseahashtable.thenforthepre computingstep,gothrougheach wordinthedictionary,sortthelettersofthewordinalphabeticalorder(so "hacking"wouldbecome"acghikn")andaddthesortedlettersasakeyinthetable andtheoriginalwordasoneofthevaluesinalistofvaluesforthatkey.for example,theentryfor"opst"wouldbethelist["opts","post","stop","pots","tops", "spot"].then,wheneveryougetastring,yousimplysortthelettersofthestring andlookupthevalueinthehashtable.therunningtimeiso(nlogn)forsorting thestring(whichisrelativelysmall)andapproximatelyo(1)forthelookupinthe hashtable. Thereareseveralotherpossibleanswerstothisquestion,butwefeelthatthe answeraboveisconsideredanoptimalsolution. Question:FactorialZeros Withoutusingacalculator,howmanyzerosareattheendof"100!"?(that's 100*99*98*...*3*2*1) Answer:Whatyoudon'twanttodoisstartmultiplyingitallout!Thetrickis rememberingthatthenumberofzerosattheendofanumberisequaltothe numberoftimes"10"(or"2*5")appearswhenyoufactorthenumber.therefore thinkabouttheprimefactorizationof100!andhowmany2sand5sthereare. Thereareabunchmore2sthan5s,sothenumberof5sisalsothenumberof10sin thefactorization.thereisone5foreveryfactorof5inourfactorialmultiplication (1*2*...*5*...*10*...*15*...)andanextra5for25,50,75,and100.Thereforewehave 20+4=24zerosattheendof100!.

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park Sorting Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Overview Comparison sort Bubble sort Selection sort Tree sort Heap sort Quick sort Merge

More information

6. Standard Algorithms

6. Standard Algorithms 6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

More information

Hacking a Google Interview Handout 3

Hacking a Google Interview Handout 3 HackingaGoogleInterview Handout3 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin32 124 Website:http://courses.csail.mit.edu/iap/interview Question:DeckShuffling

More information

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)! The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n >

More information

Biostatistics 615/815

Biostatistics 615/815 Merge Sort Biostatistics 615/815 Lecture 8 Notes on Problem Set 2 Union Find algorithms Dynamic Programming Results were very ypositive! You should be gradually becoming g y g comfortable compiling, debugging

More information

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic 1 Algorithm Analysis []: if-else statements, recursive algorithms COSC 011, Winter 004, Section N Instructor: N. Vlajic Algorithm Analysis for-loop Running Time The running time of a simple loop for (int

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

Binary Heap Algorithms

Binary Heap Algorithms CS Data Structures and Algorithms Lecture Slides Wednesday, April 5, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks [email protected] 2005 2009 Glenn G. Chappell

More information

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Sorting Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Sorting Let elem be a type with a operation, which is a total order A vector

More information

Introduction to Stacks

Introduction to Stacks Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack. What is a Stack? Stack is a data structure in which data is added

More information

The following program is aiming to extract from a simple text file an analysis of the content such as:

The following program is aiming to extract from a simple text file an analysis of the content such as: Text Analyser Aim The following program is aiming to extract from a simple text file an analysis of the content such as: Number of printable characters Number of white spaces Number of vowels Number of

More information

Big O and Limits Abstract Data Types Data Structure Grand Tour. http://gcc.gnu.org/onlinedocs/libstdc++/images/pbds_different_underlying_dss_1.

Big O and Limits Abstract Data Types Data Structure Grand Tour. http://gcc.gnu.org/onlinedocs/libstdc++/images/pbds_different_underlying_dss_1. Big O and Limits Abstract Data Types Data Structure Grand Tour http://gcc.gnu.org/onlinedocs/libstdc++/images/pbds_different_underlying_dss_1.png Consider the limit lim n f ( n) g ( n ) What does it

More information

What Is Recursion? Recursion. Binary search example postponed to end of lecture

What Is Recursion? Recursion. Binary search example postponed to end of lecture Recursion Binary search example postponed to end of lecture What Is Recursion? Recursive call A method call in which the method being called is the same as the one making the call Direct recursion Recursion

More information

Analysis of Binary Search algorithm and Selection Sort algorithm

Analysis of Binary Search algorithm and Selection Sort algorithm Analysis of Binary Search algorithm and Selection Sort algorithm In this section we shall take up two representative problems in computer science, work out the algorithms based on the best strategy to

More information

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting CSC148 Lecture 8 Algorithm Analysis Binary Search Sorting Algorithm Analysis Recall definition of Big Oh: We say a function f(n) is O(g(n)) if there exists positive constants c,b such that f(n)

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara CMPSC 24: Lecture 13 Recursion Divyakant Agrawal Department of Computer Science UC Santa Barbara 5/12/10 1 Lecture Plan Recursion General structure of recursive soluions Why do recursive soluions terminate?

More information

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Questions 1 through 25 are worth 2 points each. Choose one best answer for each. Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in

More information

Converting a Number from Decimal to Binary

Converting a Number from Decimal to Binary Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive

More information

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015 Data Structures Jaehyun Park CS 97SI Stanford University June 29, 2015 Typical Quarter at Stanford void quarter() { while(true) { // no break :( task x = GetNextTask(tasks); process(x); // new tasks may

More information

7. Solving Linear Inequalities and Compound Inequalities

7. Solving Linear Inequalities and Compound Inequalities 7. Solving Linear Inequalities and Compound Inequalities Steps for solving linear inequalities are very similar to the steps for solving linear equations. The big differences are multiplying and dividing

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2016S-05 Abstract Data Types and Lists David Galles Department of Computer Science University of San Francisco 05-0: Abstract Data Types Recall that an Abstract Data

More information

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists Simple sorting algorithms and their complexity Bubble sort Selection sort Insertion sort Bubble sort void bubblesort(int arr[]){ int i; int j; int temp; for(i = arr.length-1; i > 0; i--){ for(j = 0; j

More information

DATA STRUCTURE - QUEUE

DATA STRUCTURE - QUEUE DATA STRUCTURE - QUEUE http://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm Copyright tutorialspoint.com Queue is an abstract data structure, somewhat similar to stack. In contrast to

More information

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays. Arrays Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html 1 Grid in Assignment 2 How do you represent the state

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

Computer Science 210: Data Structures. Searching

Computer Science 210: Data Structures. Searching Computer Science 210: Data Structures Searching Searching Given a sequence of elements, and a target element, find whether the target occurs in the sequence Variations: find first occurence; find all occurences

More information

4.2 Sorting and Searching

4.2 Sorting and Searching Sequential Search: Java Implementation 4.2 Sorting and Searching Scan through array, looking for key. search hit: return array index search miss: return -1 public static int search(string key, String[]

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Algorithms. Margaret M. Fleck. 18 October 2010

Algorithms. Margaret M. Fleck. 18 October 2010 Algorithms Margaret M. Fleck 18 October 2010 These notes cover how to analyze the running time of algorithms (sections 3.1, 3.3, 4.4, and 7.1 of Rosen). 1 Introduction The main reason for studying big-o

More information

Binary search algorithm

Binary search algorithm Binary search algorithm Definition Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than

More information

Data Structures and Algorithms Lists

Data Structures and Algorithms Lists Data Structures and Algorithms Lists Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/19 5-0: Abstract Data Types An

More information

Overview. What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test?

Overview. What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test? Testing CMSC 202 Overview What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test? 2 What is Software Testing? Software testing is any activity aimed at evaluating

More information

Data Structures in the Java API

Data Structures in the Java API Data Structures in the Java API Vector From the java.util package. Vectors can resize themselves dynamically. Inserting elements into a Vector whose current size is less than its capacity is a relatively

More information

Analysis of a Search Algorithm

Analysis of a Search Algorithm CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,

More information

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Software Testing Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Testing can only reveal the presence of errors and not the

More information

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD 1 Slides 1. Table of Contents 2. Definitions 3. Simple 4. Recursive Execution Trace 5. Attributes 6. Recursive Array Summation 7. Recursive Array Summation Trace 8. Coding Recursively 9. Recursive Design

More information

Introducing Variance into the Java Programming Language DRAFT

Introducing Variance into the Java Programming Language DRAFT Introducing Variance into the Java Programming Language A Quick Tutorial DRAFT Christian Plesner Hansen Peter von der Ahé Erik Ernst Mads Torgersen Gilad Bracha June 3, 2003 1 Introduction Notice: This

More information

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and: Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

More information

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

Two-Dimensional Arrays. 15-110 Summer 2010 Margaret Reid-Miller

Two-Dimensional Arrays. 15-110 Summer 2010 Margaret Reid-Miller Two-Dimensional Arrays 15-110 Margaret Reid-Miller Two-Dimensional Arrays Arrays that we have consider up to now are onedimensional arrays, a single line of elements. Often data come naturally in the form

More information

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Brad Rippe CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Recursion Recursion CHAPTER 14 Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively

More information

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION 2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION A world-coordinate area selected for display is called a window. An area on a display device to which a window is mapped is called a viewport. The window

More information

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees Binary Search Trees Last lecture: Tree terminology Kinds of binary trees Size and depth of trees This time: binary search tree ADT Java implementation Keys and records So far most examples assumed that

More information

Practical Session 4 Java Collections

Practical Session 4 Java Collections Practical Session 4 Java Collections Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack The Collections class Wrapper classes Collection A group

More information

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: 15.1-15.3. Data Structures

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: 15.1-15.3. Data Structures 1.00 Lecture 35 Data Structures: Introduction Stacks, Queues Reading for next time: Big Java: 15.1-15.3 Data Structures Set of reusable classes used in algorithms, simulations, operating systems, applications

More information

DATA STRUCTURE - STACK

DATA STRUCTURE - STACK DATA STRUCTURE - STACK http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright tutorialspoint.com A stack is an abstract data type ADT, commonly used in most programming

More information

Ordered Lists and Binary Trees

Ordered Lists and Binary Trees Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0:

More information

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) 3 4 4 7 5 9 6 16 7 8 8 4 9 8 10 4 Total 92.

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) 3 4 4 7 5 9 6 16 7 8 8 4 9 8 10 4 Total 92. Name: Email ID: CSE 326, Data Structures Section: Sample Final Exam Instructions: The exam is closed book, closed notes. Unless otherwise stated, N denotes the number of elements in the data structure

More information

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

GPGPU Parallel Merge Sort Algorithm

GPGPU Parallel Merge Sort Algorithm GPGPU Parallel Merge Sort Algorithm Jim Kukunas and James Devine May 4, 2009 Abstract The increasingly high data throughput and computational power of today s Graphics Processing Units (GPUs), has led

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

Lecture Notes on Linear Search

Lecture Notes on Linear Search Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is

More information

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers To My Parents -Laxmi and Modaiah To My Family Members To My Friends To IIT Bombay To All Hard Workers Copyright 2010 by CareerMonk.com All rights reserved. Designed by Narasimha Karumanchi Printed in

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015 CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Linda Shapiro Today Registration should be done. Homework 1 due 11:59 pm next Wednesday, January 14 Review math essential

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative

More information

Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap

Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap Singly linked list (1) Data about exam results are stored into a singly linked list. Each list

More information

Shortest Path Algorithms

Shortest Path Algorithms Shortest Path Algorithms Jaehyun Park CS 97SI Stanford University June 29, 2015 Outline Cross Product Convex Hull Problem Sweep Line Algorithm Intersecting Half-planes Notes on Binary/Ternary Search Cross

More information

Conditionals (with solutions)

Conditionals (with solutions) Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;

More information

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction Lecture 11 Dynamic Programming 11.1 Overview Dynamic Programming is a powerful technique that allows one to solve many different types of problems in time O(n 2 ) or O(n 3 ) for which a naive approach

More information

Java Server Pages and Java Beans

Java Server Pages and Java Beans Java Server Pages and Java Beans Java server pages (JSP) and Java beans work together to create a web application. Java server pages are html pages that also contain regular Java code, which is included

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity

More information

Database Management Systems Comparative Study: Performances of Microsoft SQL Server Versus Oracle

Database Management Systems Comparative Study: Performances of Microsoft SQL Server Versus Oracle Database Management Systems Comparative Study: Performances of Microsoft SQL Server Versus Oracle Cătălin Tudose*, Carmen Odubăşteanu** * - ITC Networks, Bucharest, Romania, e-mail: [email protected]

More information

Priority Queues and Heapsort

Priority Queues and Heapsort CHR NIN riority Queues and Heapsort MNY LICION RQUIR that we process records with keys in order, but not necessarily in full sorted order and not necessarily all at once. Often, we collect a set of records,

More information

Searching Algorithms

Searching Algorithms Searching Algorithms The Search Problem Problem Statement: Given a set of data e.g., int [] arr = {10, 2, 7, 9, 7, 4}; and a particular value, e.g., int val = 7; Find the first index of the value in the

More information

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11 Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11 In this lab, you will first learn how to use pointers to print memory addresses of variables. After that, you will learn

More information

Data Structures and Algorithms Written Examination

Data Structures and Algorithms Written Examination Data Structures and Algorithms Written Examination 22 February 2013 FIRST NAME STUDENT NUMBER LAST NAME SIGNATURE Instructions for students: Write First Name, Last Name, Student Number and Signature where

More information

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions. Abstract Data Types and Data Structures Often, these terms are used as synonyms. But it s better to think of them this way: ADTs and Data Structures An Abstract Data Type (ADT) represents a particular

More information

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17 CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17 System Calls for Processes Ref: Process: Chapter 5 of [HGS]. A program in execution. Several processes are executed concurrently by the

More information

From Pseudocode to Real Code

From Pseudocode to Real Code From to Real Code Once we have expressed an algorithm in pseudocode, we need one more step to turn it into something that machines can do for us: conversion into an actual programming language, or real

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A

More information

Visualising Java Data Structures as Graphs

Visualising Java Data Structures as Graphs Visualising Java Data Structures as Graphs John Hamer Department of Computer Science University of Auckland [email protected] John Hamer, January 15, 2004 ACE 2004 Visualising Java Data Structures

More information

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1 topics: recursion searching cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1 recursion recursion is defining something in terms of itself there are many examples in nature and

More information

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES TECHNICAL UNIVERSITY OF CRETE DEPT OF ELECTRONIC AND COMPUTER ENGINEERING DATA STRUCTURES AND FILE STRUCTURES Euripides G.M. Petrakis http://www.intelligence.tuc.gr/~petrakis Chania, 2007 E.G.M. Petrakis

More information

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever! ECE 551 C++ Programming, Data structures, and Algorithms Abstract Data Type: Stack Last In First Out (LIFO) 1 2 2 1 4 3 1 3 4 Stacks in Programming Worst line ever! 5 3 1 5 Stacks are not useful for waiting

More information

THIS CHAPTER studies several important methods for sorting lists, both contiguous

THIS CHAPTER studies several important methods for sorting lists, both contiguous Sorting 8 THIS CHAPTER studies several important methods for sorting lists, both contiguous lists and linked lists. At the same time, we shall develop further tools that help with the analysis of algorithms

More information

Winter 2002 MID-SESSION TEST Friday, March 1 6:30 to 8:00pm

Winter 2002 MID-SESSION TEST Friday, March 1 6:30 to 8:00pm University of Calgary Department of Electrical and Computer Engineering ENCM 369: Computer Organization Instructors: Dr. S. A. Norman (L01) and Dr. S. Yanushkevich (L02) Winter 2002 MID-SESSION TEST Friday,

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

Abstraction and Abstract Data Types

Abstraction and Abstract Data Types Abstraction and Abstract Data Types Abstraction: o Whatever is visible to the user? Examples: Variable names & real numbers. o How real numbers are implemented? o How arrays are implemented? The abstraction

More information

Collections.sort(population); // Método de ordenamiento

Collections.sort(population); // Método de ordenamiento import java.util.collections; import java.util.linkedlist; import java.util.random; public class GeneticAlgorithms static long BEGIN; static final boolean _DEBUG = true; LinkedList population

More information

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited Hash Tables Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited We ve considered several data structures that allow us to store and search for data

More information

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q QUEUES A queue is simply a waiting line that grows by adding elements to its end and shrinks by removing elements from the. Compared to stack, it reflects the more commonly used maxim in real-world, namely,

More information

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009 STORM Simulation TOol for Real-time Multiprocessor scheduling Designer Guide V3.3.1 September 2009 Richard Urunuela, Anne-Marie Déplanche, Yvon Trinquet This work is part of the project PHERMA supported

More information