CS210 Study Guide Swami Iyer. 1 Programming Model (Algorithms 1.1) 2. 2 Data Abstraction (Algorithms 1.2) 4

Size: px
Start display at page:

Download "CS210 Study Guide Swami Iyer. 1 Programming Model (Algorithms 1.1) 2. 2 Data Abstraction (Algorithms 1.2) 4"

Transcription

1 Contents 1 Programming Model (Algorithms 1.1) 2 2 Data Abstraction (Algorithms 1.2) 4 3 Analysis of Algorithms (Algorithms 1.4) 7 4 Basic Data Structures (Algorithms 1.3) 9 5 Union-find (Algorithms 1.5) 11 6 Elementary Sorts (Algorithms 2.1) 12 7 Merge Sort (Algorithms 2.2) 13 8 Quick Sort (Algorithms 2.3) 13 9 Priority Queues (Algorithms 2.4) Sorting Applications (Algorithms 2.5) Symbol Tables (Algorithms 3.1) Binary Search Trees (Algorithms 3.2) Balanced Search Trees (Algorithms 3.3) Hash Tables (Algorithms 3.4) Searching Applications (Algorithms 3.5) Undirected Graphs (Algorithms 4.1) Directed Graphs (Algorithms 4.2) Minimum Spanning Trees (Algorithms 4.3) Shortest Paths (Algorithms 4.4) String Sorts (Algorithms 5.1) Tries (Algorithms 5.2) Substring Search (Algorithms 5.3) Regular Expressions (Algorithms 5.4) Data Compression (Algorithms 5.5) 29 1 of 29

2 1 Programming Model (Algorithms 1.1) Problem 1. Consider the following method: public static int mystery ( int [] a) { int x = 0; for ( int i = 0; i < a. length ; i ++) { x += a[i] * a[i]; return x; a. What does mystery() compute and return in general? b. What will mystery() return if the argument a is an integer array containing the values 1, 2, 3, 4, and 5? Problem 2. Consider the following method: public static int [][] mystery ( int n, int k) { int [][] a = new int [n][n]; for ( int i = 0; i < n; i ++) { for ( int j = 0; j < n; j ++) { a[i][j] = (i > j)? 0 : k; return a; a. What does mystery() compute and return in general? b. What will mystery() return if the arguments are n = 4 and k = 5? Problem 3. Consider the following recursive method: public static int mystery ( int a, int b) { if (b == 0) { return 0; if ( a == 0) { return mystery ( b - 1, a); return b + mystery (b, a - 1); a. What will mystery(0, 10) return? b. What will mystery(10, 3) return? c. What will mystery(200, 300) return? d. What does mystery(a, b) return in general about a and b? Problem 4. Consider the following program: // Circle. java import edu. princeton.cs. algs4. StdOut ; public class Circle { public static void main ( String [] args ) { double r = Double. parsedouble ( args [0]); double c = 2 * Math. PI * r; double a = Math. PI * r * r; StdOut. printf (" radius = %.2f, circumference = %.2f, area = %.2 f\ n", r, c, a); 2 of 29

3 a. What does Circle compute and print in general? b. What will Circle write when run with the command-line argument 5? Problem 5. Write a program RandomInts.java that takes command-line arguments n, a, and b as integers and writes n random integers (one per line) from the range [a, b]. For example $ java RandomInts Problem 6. Write a program Stats.java that reads integers from standard input, and computes and writes their mean, variance, and standard deviation, each up to 3 decimal places. For example $ java Stats <ctrl -d> mean = 3.000, var = 2.000, std = Problem 7. a. What is the command for generating random integers from the interval [1, 24] using the RandomInts program from Problem 5? b. What is the command for generating random integers from the interval [1, 24] and saving the output in a file called numbers.txt? c. What is the command for using the Stats program from Problem 6 to calculate stats for the numbers in numbers.txt? d. What is the command to perform the last two tasks in one shot? a. The sum of squares of the integers in a. b. 55 Solution 2. a. An n-by-n matrix in which the elements below the main diagonal are zeros and the rest of the elements are k. b. {{5, 5, 5, 5, {0, 5, 5, 5, {0, 0, 5, 5, {0, 0, 0, 5 Solution 3. a. 0 b. 30 c d. a * b Solution 4. a. Reads a command-line argument r as a double, computes the circumference c and area a of a circle with radius r, and prints the values of r, c, and a up to 2 decimal places. 3 of 29

4 b. radius = 5.00, circumference = 31.42, area = Solution 5. # RandomInts. java import edu. princeton.cs. algs4. StdOut ; import edu. princeton.cs. algs4. StdRandom ; public class RandomInts { public static void main ( String [] args ) { int n = Integer. parseint ( args [0]); int a = Integer. parseint ( args [1]); int b = Integer. parseint ( args [2]); for ( int i = 0; i < n; i ++) { int r = StdRandom. uniform (a, b + 1); StdOut. println (r); Solution 6. # Stats. java import edu. princeton.cs. algs4. StdIn ; import edu. princeton.cs. algs4. StdOut ; public class Stats { public static void main ( String [] args ) { int a[] = StdIn. readallints (); double mean = 0.0, var = 0.0, std = 0.0; for ( int x : a) { mean += x; mean /= a. length ; for ( int x : a) { var += (x - mean ) * (x - mean ); var /= a. length ; std = Math. pow (var, 0.5); StdOut. printf (" mean = %.3f, var = %.3f, std = %.3 f\ n", mean, var, std ); Solution 7. a. java RandomInts b. java RandomInts > numbers.txt c. java Stats < numbers.txt d. java RandomInts java Stats 2 Data Abstraction (Algorithms 1.2) Problem 1. Implement an immutable and comparable data type Card that represents a playing card. Each card is represented using an integer rank (0 for 2, 1 for 3,..., 11 for King, and 12 for Ace) and an integer suit (0 for Clubs, 1 for Diamonds, 2 for Hearts, and 3 for Spades). Your data type must support the following API: 4 of 29

5 method/class Card(int suit, int rank) boolean equals(card that) String tostring() int compareto(card that) static class SuitOrder static class ReverseRankOrder description construct a card given its suit and rank is this card the same as that a string representation of the card; for example Ace of Hearts is this card less than, equal to, or greater than that card a comparator for comparing cards based on their suits a comparator for comparing cards based on the reverse order of their ranks A card c 1 is less than a card c 2 if either the suit of c 1 is less than the suit of c 2 or c 1 and c 2 are of the same suit and the denomination of c 1 is less than the denomination of c 2. We refer to this as the natural order. Problem 2. Suppose deck is an array of Card (the data type from Problem 1) objects. a. Write down a statement that uses Arrays.sort() to sort deck by the natural order. b. Write down a statement that uses Arrays.sort() to sort deck by suit order. c. Write down a statement that uses Arrays.sort() to sort deck by reverse rank order. Problem 3. Complete the implementation of the iterable data type Range that allows clients to iterate over a range of integers from the interval [lo, hi] in increments specified by step. For example, the following code for ( int i : new Range (1, 10, 3)) { StdOut. println (i); should output import java. util. Iterator ; public class Range implements Iterable < Integer > { private int lo; private int hi; private int step ; // Construct a range given the bounds and the step size. public Range ( int lo, int hi, int step ) {... // A range iterator. public Iterator < Integer > iterator () {... // Helper range iterator. private class RangeIterator implements Iterator < Integer > { private int i; public RangeIterator () {... public boolean hasnext () {... public Integer next () {... 5 of 29

6 // Card. java import java. util. Comparator ; public class Card implements Comparable <Card > { private static String [] RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", " Jack ", " Queen ", " King ", " Ace "; private static String [] SUITS = {" Clubs ", " Diamonds ", " Hearts ", " Spades "; private final int suit ; private final int rank ; public Card ( int suit, int rank ) { this. suit = suit ; this. rank = rank ; public boolean equals ( Card other ) { return compareto ( other ) == 0; public String tostring () { return RANKS [ rank ] + " of " + SUITS [ suit ]; public int compareto ( Card that ) { if ( suit < that. suit suit == that. suit && rank < that. rank ) { return -1; else if ( suit == that. suit && rank == that. rank ) { return 0; else { return 1; public static class SuitOrder implements Comparator <Card > { public int compare ( Card c1, Card c2) { return c1. suit - c2. suit ; public static class ReverseRankOrder implements Comparator <Card > { public int compare ( Card c1, Card c2) { return c2. rank - c1. rank ; Solution 2. a. Arrays. sort ( deck ); b. Arrays. sort (deck, new Card. SuitOrder ()); c. Arrays. sort ( deck, new Card. ReverseRankOrder ()); 6 of 29

7 Solution 3. // Range. java import java. util. Iterator ; public class Range implements Iterable < Integer > { private int lo; private int hi; private int step ; public Range ( int lo, int hi, int step ) { this. lo = lo; this. hi = hi; this. step = step ; public Iterator < Integer > iterator () { return new RangeIterator (); private class RangeIterator implements Iterator < Integer > { private int i; public RangeIterator () { i = lo; public boolean hasnext () { return i <= hi; public Integer next () { int r = i; i += step ; return r; 3 Analysis of Algorithms (Algorithms 1.4) Problem 1. Consider an array a[] with 10 4 integers. a. Roughly how many comparisons are involved if one performs 10 6 linear search operations on a? b. Roughly how many comparisons (sorting and searching included) are involved if one performs 10 6 binary search operations on a? Problem 2. Consider the following table, which gives the running time T (N) in seconds for a program for various values of the input size N: What is the order of growth of T (N)? N T (N) ,599 Problem 3. Provide the order-of-growth classification (constant, logarithmic, linear, linearithmic, quadratic, cubic, or exponential) for the following tasks: 7 of 29

8 a. Adding two N-by-N matrices. b. Enumerating the subsets of a set with N items. c. Finding the average of N numbers. d. Finding distinct triples (a, b, c) in a collection of N positive integers such that a 2 + b 2 = c 2. e. Finding the maximum key in a maximum-oriented heap-ordered binary tree with N items. f. Inserting a new key into a heap-ordered binary tree with N items. g. Multiplying two numbers. h. Sorting an array of N items using quick sort. i. Sorting an array of N items using insertion sort. j. Summing up the diagonal elements of an N-by-N matrix. Problem 4. Give the order of growth (as a function of N) of the running times of each of the following code fragments: a. int sum = 0; for ( int n = N; n > 0; n /= 2) { for ( int i = 0; i < n; i ++) { sum ++; b. int sum = 0; for ( int i = 1; i < N; i *= 2) { for ( int j = 0; j < i; j ++) { sum ++; c. int sum = 0; for ( int i = 1; i < N; i *= 2) { for ( int j = 0; j < N; j ++) { sum ++; Problem 5. Consider a data type Planet with the attributes String name and int moons. What is the memory footprint (in bytes) of the array planets of Planet objects, created and initialized in the following manner? Planet [] planets = new Planet [8]; planets [0] = new Planet (" Mercury ", 0); planets [1] = new Planet (" Venus ", 0); planets [2] = new Planet (" Earth ", 1); planets [3] = new Planet (" Mars ", 2); planets [4] = new Planet (" Jupiter ", 67); planets [5] = new Planet (" Saturn ", 62); planets [6] = new Planet (" Uranus ", 27); planets [7] = new Planet (" Neptune ", 14); a = b lg 10 4 = of 29

9 Solution 2. T (N) N 3 (cubic) Solution 3. a. Quadratic b. Exponential c. Linear d. Cubic e. Constant f. Logarithmic g. Constant h. Linearithmic i. Quadratic j. Linear Solution 4. a. Linear b. Linear c. Linearithmic Solution ( ) = 430 bytes 4 Basic Data Structures (Algorithms 1.3) Problem 1. Consider the following method: public static int mystery ( Node < Integer > first ) { int x = 0; for ( Node y = first, int i = 0; y!= null ; y = y. next, i ++) { x += ( i % 2 == 0)? y. item : 0; return x; a. What does mystery() compute and return in general? b. What will mystery() return if the argument (a Node object) represents a linked list containing integers 1, 2, 3,..., 10? Problem 2. Consider the following method: public static int mystery ( Bag < Integer > bag ) { int x = 0; Itereator < Integer > iter = bag. iterator (); while ( iter. hasnext ()) { x += iter. next (); return x; a. What does mystery() compute and return in general? 9 of 29

10 b. What will mystery() return if the argument (a Bag object) contains the integers 1, 2, 3,..., 10? Problem 3. Suppose that a minus sign in the input indicates pop the stack and write the return value to standard output, and any other string indicates push the string onto the stack. Further suppose that following input is processed: a. What is written to standard output? it was - the best - of times it was - the - - worst - of times - b. What are the contents (top to bottom) left on the stack? Problem 4. Suppose that an intermixed sequence of (stack) push and pop operations are performed. The pushes push the integers 0 through 9 in order; the pops print out the return value. Which of the following sequence(s) could not occur? A B C D E F G H Problem 5. Consider the following code fragment: Stack < Integer > s = new Stack < Integer >(); while (n > 0) { s. push (n % 2); n = n / 2; while (!s. isempty ()) { StdOut. print (s. pop ()); StdOut. println (); a. What does the following code fragment print when n is 50? b. Give a high-level description of what it does when presented with a positive integer n. Problem 6. Suppose that a minus sign in the input indicates dequeue the queue and write the return value to standard output, and any other string indicates enqueue the string onto the queue. Further suppose that following input is processed: a. What is written to standard output? it was - the best - of times it was - the - - worst - of times - b. What are the contents (head to tail) left on the queue? Problem 7. Suppose that a client performs an intermixed sequence of (queue) enqueue and dequeue operations. The enqueue operations put the integers 0 through 9 in order onto the queue; the dequeue operations print out the return value. Which of the following sequence(s) could not occur? A B C D of 29

11 Problem 8. What does the following code fragment do to the queue q? Stack < String > s = new Stack < String >(); while (!q. isempty ()) { s. push (q. dequeue ()); while (!s. isempty ()) { q. enqueue (s. pop ()); a. Computes and returns the sum of every other integer in node, starting at the first. b. 25 Solution 2. a. Computes and returns the sum of the integers in bag. b. 55 Solution 3. a. was best times of the was the it worst times b. of it Solution 4. B, F, and G Solution 5. a b. Prints the binary representation of n. Solution 6. a. it was the best of times it was the worst b. of times Solution 7. B, C, and D Solution 8. Reverses the items on the queue. 5 Union-find (Algorithms 1.5) Problem 1. Let s say we are using the union-find (UF) data structure to solve the dynamic connectivity problem with 10 sites and input pairs (1, 2), (7, 8), (1, 6), (0, 5), (3, 8), (2, 3), (6, 7), (2, 7), and (4, 9), arriving in that order. a. How many components does UF identify? b. What are those components? c. Will the number of components or their membership change if the input pairs arrive in a different order than above? d. Suppose we process the pairs using QuickFindUF. What are the values in the id array after all the pairs are processed? e. Suppose we process the pairs using QuickUnionUF. What are the values in the parent array after all the pairs are processed? 11 of 29

12 f. Suppose we process the pairs using WeightedQuickUnionUF. What are the values in the parent and size arrays after all the pairs are processed? {0, 5, {4, 9, and {1, 2, 3, 6, 7, 8 3. No 4. id = {5, 8, 8, 8, 9, 5, 8, 8, 8, 9 5. parent = {5, 2, 6, 8, 9, 5, 8, 8, 8, 9 6. parent = {0, 1, 1, 7, 4, 0, 1, 1, 7, 4, size = {2, 6, 1, 1, 2, 1, 1, 3, 1, 1 6 Elementary Sorts (Algorithms 2.1) Problem 1. Consider sorting an array a[] containing the following strings: E A S Y Q U T I O N a. (Selection sort.) What is a[] when i = 3 and after the exchange on line 10? 1 public static void sort ( Comparable [] a) { 2 int N = a. length ; 3 for ( int i = 0; i < N; i ++) { 4 int min = i; 5 for ( int j = i + 1; j < N; j ++) { 6 if ( less (a[j], a[ min ])) { 7 min = j; exch (a, i, min ); b. (Insertion sort.) What is a[] when i = 4 and the inner loop (lines 4-7) is complete? 1 public static void sort ( Comparable [] a) { 2 int N = a. length ; 3 for ( int i = 0; i < N; i ++) { 4 for ( int j = i; j > 0 && less (a[j], a[j - 1]); j - -) { 5 exch (a, j, j - 1); c. (Shell sort.) What is a[] after a 4-sort, ie, after the first iteration of the second while loop (lines 5-14)? 1 public static void sort ( Comparable [] a) { 2 int N = a. length ; 3 int h = 1; 4 while ( h < N / 3) { h = 3 * h + 1; 5 while (h >= 1) { 6 for ( int i = h; i < N; i ++) { 7 for ( int j = i; j >= h && less (a[j], a[j - h ]); j -= h) { 8 exch (a, j, j - h); h /= 3; of 29

13 a. A E I N Q U T S O Y b. A E Q S Y U T I O N c. E A S I O N T Y Q U 7 Merge Sort (Algorithms 2.2) Problem 1. Consider sorting an array a[] containing the following strings: E A S Y Q U T I O N What is a[] when the function call merge(a, aux, 0, 2, 4) returns? 1 public static void sort ( Comparable [] a) { 2 Comparable [] aux = new Comparable [ a. length ]; 3 sort (a, aux, 0, a. length - 1); private static void sort ( Comparable [] a, Comparable [] aux, int lo, int hi) { 7 if (hi <= lo) { return ; 8 int mid = lo + ( hi - lo) / 2; 9 sort (a, aux, lo, mid ); 10 sort (a, aux, mid + 1, hi ); 11 merge (a, aux, lo, mid, hi ); private static void merge ( Comparable [] a, Comparable [] aux, 15 int lo, int mid, int hi) { 16 int i = lo, j = mid + 1; 17 for ( int k = lo; k <= hi; k ++) { 18 aux [k] = a[k]; for ( int k = lo; k <= hi; k ++) { 21 if (i > mid ) { a[k] = aux [j ++]; 22 else if (j > hi) { a[k] = aux [i ++]; 23 else if ( less ( aux [j], aux [i ])) { a[k] = aux [j ++]; 24 else { a[ k] = aux [ i ++]; A E Q S Y U T I O N 8 Quick Sort (Algorithms 2.3) Problem 1. Consider partitioning an array a[] containing the following keys, by calling the partition() method (shown below) from quick sort, as partition(a, 0, a.length - 1): P A R T I O N E X M L 13 of 29

14 private static int partition ( Comparable [] a, int lo, int hi) { int i = lo; int j = hi + 1; Comparable v = a[ lo ]; while ( true ) { while ( less (a [++ i], v)) { if (i == hi) { break ; while ( less (v, a[--j ])) { if (j == lo) { break ; if (i >= j) { break ; exch (a, i, j); exch (a, lo, j); return j; a. What is the value of the pivot element v? b. What is the value returned by the function call, ie, what is the destination index of the pivot? c. What is the state of the array after the call? a. P b. 7 c. E A L M I O N P X T R 9 Priority Queues (Algorithms 2.4) Problem 1. Insert the following keys in that order into a maximum-oriented heap-ordered binary tree: E A S Y Q U T I O N a. What is the state of the array pq representing the resulting tree? b. What is the height of the tree (the root is at height zero)? Problem 2. Suppose that a letter in the input means insert the letter into an initially empty priority queue and an asterisk (*) means remove the minimum from the priority queue. What is left in the priority queue after the following input is processed? a. - Y S U O Q E T A I N b. 3 Solution 2. U P R I O * R * * I * T * Y * * * Q U E * * * U E * 14 of 29

15 10 Sorting Applications (Algorithms 2.5) Problem 1. (Sorting and Shuffling Algorithms) The column on the left is the original input of strings to be sorted or shuffled; the column on the right are the string in sorted order; the other columns are the contents at some intermediate step during one of the 7 algorithms listed below. lynx bass lion bass bass bass gnat wren bass bass bear frog bear bear bear bass worm bear bear crab mole clam clam clam bear oryx clam crab lion hawk crab crab crab crab swan crab lion goat wren frog frog crow lion wolf crow goat duck lynx gnat goat deer goat mule deer mole frog crab goat hawk dove duck mole dove frog dove swan hawk lion duck frog puma duck swan clam bear lion lynx frog dove seal frog clam hawk clam lynx mole gnat clam deer gnat hawk deer bass lynx swan goat hawk lion goat wren crow goat mole wren hawk deer goat hawk mule gnat mule mule gnat mule crow bear lion oryx lynx oryx oryx lynx oryx lynx lynx lynx gnat lynx gnat swan mule lynx lynx gnat lynx lynx puma lynx wren oryx lynx oryx lynx mole puma worm puma puma puma puma puma frog mule worm seal worm worm worm worm worm crab oryx seal oryx seal seal crow seal seal bass puma crow mule crow crow deer lion mule crow seal deer wolf deer deer dove wren wren clam swan wolf wren wolf wolf duck wolf wolf hawk wolf dove swan dove dove seal mole swan dove worm duck mole duck duck wolf swan mole duck wren Original input 2. Selection sort 3. Insertion sort 4. Merge sort (top down) 5. Quick sort (standard, no shuffle) 6. Quick sort (3-way, no shuffle) 7. Heap sort 8. Shuffle 9. Sorted What is the sequence of numbers you get after you match up each algorithm s number with the corresponding column? Use each number exactly once. Problem 2. Give an N log N algorithm for computing the mode (value that occurs most frequently) of a sequence of N integers Solution 2. Sort the sequence using quick sort. Iterate through the sorted sequence to find the length of the longest stretch of numbers. The first step takes linearithmic (N log N) time and the second step can be performed in linear (N) time. The overall running time is N log N + N N log N. 15 of 29

16 11 Symbol Tables (Algorithms 3.1) Problem 1. Consider inserting the following key-value pairs into a sequential search symbol table st, an object of type SequentialSearchST. key: S Y M B O L T A B L E E X A M P L E value: a. What is the state of the linked list first? b. What is the value returned by st.size()? c. What is the value returned by st.get("b")? d. What is the state of the linked list first after the call st.put("e", null)? Problem 2. Consider inserting the following key-value pairs into a binary search (ordered) symbol table st, an object of type BinarySearchST. key: S Y M B O L T A B L E E X A M P L E value: a. What is the state of the keys and values arrays? b. What is the value returned by st.floor("g")? c. What is the value returned by st.ceiling("g")? d. What is the value returned by st.rank("g")? e. What is the value returned by st.select(5)? f. What is the state of the keys and values arrays after the call st.put("e", null)? a. (P, 16) -> (X, 13) -> (E, 18) -> (A, 14) -> (T, 7) -> (L, 17) -> (O, 5) -> (B, 9) -> (M, 15) -> (Y, 2) -> (S, 1) -> null b. 11 c. 9 d. (P, 16) -> (X, 13) -> (A, 14) -> (T, 7) -> (L, 17) -> (O, 5) -> (B, 9) -> (M, 15) -> (Y, 2) -> (S, 1) -> null Solution 2. a keys : A B E L M O P S T X Y values : b. E c. L d. 3 e. O f keys : A B L M O P S T X Y values : of 29

17 12 Binary Search Trees (Algorithms 3.2) Problem 1. Consider inserting the following keys (assume values to be non null and arbitrary) into a binary search tree (ordered) symbol table st, an object of type BST. S Y M B O L T A E X P a. What is the binary search tree (BST) that results? List the keys along with their indices (starting at 1) in level order. b. What is the height of the BST (assume root to be at height 0)? c. What is the order in which the keys are visited if we traverse the BST in pre-order? d. What is the order in which the keys are visited if we traverse the BST in in-order? e. What is the order in which the keys are visited if we traverse the BST in post-order? f. What is the order in which the keys are visited if we traverse the BST in level-order? g. What is the BST that results if we delete the smallest key from the initial tree? h. What is the BST that results if we delete the largest key from the initial tree? i. What is the BST that results if we delete the key B from the initial tree? a. 1: S, 2: M, 3: Y, 4: B, 5: O, 6: T, 8: A, 9: L, 11: P, 13: X, 18: E b. 4 c. S M B A L E O P Y T X d. A B E L M O P S T X Y e. A E L B P O M X T Y S f. S M Y B O T A L P X E g. 1: S, 2: M, 3: Y, 4: B, 5: O, 6: T, 9: L, 11: P, 13: X, 18: E h. 1: S, 2: M, 3: T, 4: B, 5: O, 7: X, 8: A, 9: L, 11: P, 18: E i. 1: S, 2: M, 3: Y, 4: E, 5: O, 6: T, 8: A, 9: L, 11: P, 13: X 13 Balanced Search Trees (Algorithms 3.3) Problem 1. Consider inserting the following keys into an initially empty 2-3 search tree. E A S Y Q U T I O N a. What is the height of the tree that results (assume root to be at height zero)? What is the minimum and maximum number of keys that a 2-3 search tree of this height can hold? b. What are the 2-nodes in the tree? c. What are the 3-nodes in the tree? 17 of 29

18 Problem 2. Suppose you insert the key 23 into the following left-leaning red-black BST: a. Which of the following color flips result? Select all that apply. A. Color flip 18 B. Color flip 22 C. Color flip 23 D. Color flip 24 E. Color flip 26 F. Color flip 28 b. Which of the following rotations result? Select all that apply. A. Rotate 18 left B. Rotate 18 right C. Rotate 22 left D. Rotate 22 right E. Rotate 23 left F. Rotate 23 right G. Rotate 24 left H. Rotate 24 right I. Rotate 26 left J. Rotate 26 right K. Rotate 28 left L. Rotate 28 right a. 2; 7 and 14 b. (S), (U), (A), (Q), (T), (Y) 18 of 29

19 c. (E, O), (I, N) Solution 2. a. E (Color flip 24) b. A (Rotate 18 left), C (Rotate 22 left), J (Rotate 26 right), L (Rotate 28 right) 14 Hash Tables (Algorithms 3.4) Problem 1. Consider inserting the following keys into an initially empty hash table of M = 5 lists, using separate chaining. Use the hash function h(k) = k mod M to transform the kth letter of the alphabet into a table index, where 1 k 26. a. What is the value of h(18)? b. What is the state of the array st? a. 3 b. 0: O -> T -> Y -> E -> null 1: U -> A -> null 2: Q -> null 3: null 4: N -> I -> S -> null E A S Y Q U T I O N 15 Searching Applications (Algorithms 3.5) Problem 1. How is the following 10-dimensional sparse vector represented economically as a symbol table? Problem 2. How is the following 5-by-10 sparse matrix represented economically as an array of sparse vectors (symbol tables)? {2: , 4: Solution 2. 0: { 1: {2: 6, 8: 9 2: {0: 7, 5: 2, 8: 2 3: {0: 9, 3: 1 4: {9: of 29

20 16 Undirected Graphs (Algorithms 4.1) Problem 1. Consider the following undirected graph: a. What is the adjacency matrix representation of the graph? b. What is the adjacency list representation of the graph? List the adjacent vertices in decreasing order of their IDs. c. What is the state of the edgeto array if you run depth-first search (DFS) on the graph, starting at vertex 0? Is there a path from 0 to 3? If so, what is it? d. What is the state of the distto and edgeto arrays if you run breadth-first search (BFS) on the graph, starting at vertex 0? Is there a path from 0 to 3? If so, what is it? e. How many connected components does the graph have? f. What is the component identified by a DFS on the graph, starting at vertex 3? Problem 2. Consider building a SymbolGraph object sg from the following representation of a symbol graph as a file: JFK MCO ORD DEN ORD HOU DFW PHX JFK ATL ORD DFW ORD PHX ATL HOU DEN PHX PHX LAX JFK ORD DEN LAS DFW HOU ORD ATL LAS LAX ATL MCO HOU MCO LAS PHX a. What is the state of the sg.st symbol table and sg.keys array? b. Who are the neighbors of HOU? 20 of 29

21 a b. 0: : 0 2: 0 3: 5 4 4: : : 4 0 7: 8 8: 7 9: : 9 11: : 11 9 c. v edgeto [ v] Yes, 0 -> 6 -> 4 -> 5 -> 3 d. v distto [ v] edgeto [ v] e. 3 Yes, 0 -> 5 -> 3 21 of 29

22 f. {0, 1, 2, 3, 4, 5, 6 Solution 2. a. sg. st: ATL -> 7 DEN -> 3 DFW -> 5 HOU -> 4 JFK -> 0 LAS -> 9 LAX -> 8 MCO -> 1 ORD -> 2 PHX -> 6 sg. keys : 0: JFK 1: MCO 2: ORD 3: DEN 4: HOU 5: DFW 6: PHX 7: ATL 8: LAX 9: LAS b. MCO, DFW, ATL, and ORD 17 Directed Graphs (Algorithms 4.2) Problem 1. Consider a directed graph with the following adjacency list: 0: 5 1 1: 2: 0 3 3: 5 2 4: 3 2 5: 4 6: : 6 8 8: 7 9 9: : 12 11: : 9 a. Is the graph a DAG (ie, a directed acyclic graph)? b. What are the pre-, post-, reverse-post depth first orders for the graph if the source vertex is 0? c. What is the adjacency list of the reverse graph? Problem 2. Consider the following acyclic digraph. Assume the adjacency lists are in sorted order: for example, when iterating through the edges pointing from 0, consider the edge 0 1 before 0 6 or of 29

23 a. Run DFS on the digraph, starting from vertex 2. List the vertices in preorder. b. Run DFS on the digraph, starting from vertex 2. List the vertices in postorder. c. Run DFS on the digraph, starting from vertex 2. List the vertices in topological order. d. Run BFS on the digraph, starting from vertex 2. List the vertices in the order in which they are dequeued from the FIFO queue. a. No b. Preorder: ; Postorder: ; Reverse postorder: c. 0: 6 2 1: 0 2: 4 3 3: 4 2 4: : 3 0 6: 7 7: 8 8: 7 9: : 9 11: 9 12: Solution 2. a b c d of 29

24 18 Minimum Spanning Trees (Algorithms 4.3) Problem 1. Consider the following edge-weighted graph with 9 vertices and 19 edges. distinct integers between 1 and 19. Note that the edge weights are a. Complete the sequence of edges in the MST in the order that Kruskal s algorithm includes them (by specifying their edge weights). b. What is the total weight of the edges on the MST? a b Shortest Paths (Algorithms 4.4) Problem 1. Consider the following edge-weighted digraph: Now suppose we fix the source vertex to be vertex 0 and run Dijkstra s algorithm on the above graph. 24 of 29

25 a. What are the states of the distto and edgeto arrays? b. Is there a path from the source (vertex 0) to vertex 6? If so, what is it and what is its length? a. v distto [ v] edgeto [ v] null > > > > > > > b. Yes, the path is 0 -> > > > , and its length is String Sorts (Algorithms 5.1) Problem 1. Consider sorting the following input array a by section using the key-indexed counting method: name section Becquerel 4 Bethe 2 Bloch 3 Bohr 4 Chadwick 2 Curie 2 Dirac 1 Einstein 3 Faraday 1 Fermi 3 Feynman 3 Galilei 1 Heisenberg 1 Maxwell 2 Newton 1 Planck 1 Rutherford 4 Schrodinger 4 Thomson 3 Walton 1 a. What is the state of the count array after the first step (compute frequency counts) of key-indexed counting? b. What is the state of the count array after the second step (transform counts to indices) of key-indexed counting? c. What is the state of the auxiliary array aux after the third step (distribute the data) of key-indexed counting? d. What is the state of the input array a after the fourth step (copy back) of key-indexed counting? Problem 2. Consider sorting the following array a of fixed-width strings using least-significant-digit (LSD) first string sort. 25 of 29

26 3 LLT919 7 VTF645 5 HPH324 6 LYJ620 7 BVZ383 3 TYQ515 1 JNS516 3 RRI185 1 QEV852 8 FJC018 6 KOX096 7 YLW378 6 ZIG805 What is the state of the input array a at the end of the following iterations of the outer for loop in the sort() method? a. d = 6 b. d = 5 c. d = 0 Problem 3. Consider sorting the following array a of fixed-width strings using most-significant-digit (MSD) first string sort. Bohr Einsten Chadwick Curie Schrodinger Galilei Dirac Walton Rutherford Fermi Heisenberg Maxwell Planck Feynman Thomson Faraday Newton Becquerel Bethe Bloch What is the state of the input array a after the copy back step in the following calls? a. sort(a, 0, N - 1, 0, aux)? b. sort(a, 0, 3, 1, aux)? What is the state of the input array a when the call sort(a, 0, N - 1, 0, aux) returns? a. i: count [i]: b. i: count [ i]: of 29

27 c. i aux [i] 0 Dirac 1 1 Faraday 1 2 Galilei 1 3 Heisenberg 1 4 Newton 1 5 Planck 1 6 Walton 1 7 Bethe 2 8 Chadwick 2 9 Curie 2 10 Maxwell 2 11 Bloch 3 12 Einstein 3 13 Fermi 3 14 Feynman 3 15 Thomson 3 16 Becquerel 4 17 Bohr 4 18 Rutherford 4 19 Schrodinger 4 d. i a[ i] 0 Dirac 1 1 Faraday 1 2 Galilei 1 3 Heisenberg 1 4 Newton 1 5 Planck 1 6 Walton 1 7 Bethe 2 8 Chadwick 2 9 Curie 2 10 Maxwell 2 11 Bloch 3 12 Einstein 3 13 Fermi 3 14 Feynman 3 15 Thomson 3 16 Becquerel 4 17 Bohr 4 18 Rutherford 4 19 Schrodinger 4 Solution 2. a. 6 LYJ620 1 QEV852 7 BVZ383 5 HPH324 7 VTF645 3 TYQ515 3 RRI185 6 ZIG805 1 JNS516 6 KOX096 8 FJC018 7 YLW378 3 LLT919 b. 6 ZIG805 3 TYQ515 1 JNS516 8 FJC of 29

28 3 LLT919 6 LYJ620 5 HPH324 7 VTF645 1 QEV852 7 YLW378 7 BVZ383 3 RRI185 6 KOX096 c. 1 JNS516 1 QEV852 3 LLT919 3 RRI185 3 TYQ515 5 HPH324 6 KOX096 6 LYJ620 6 ZIG805 7 BVZ383 7 VTF645 7 YLW378 8 FJC018 Solution 3. a. i a[ i] 0 Bohr 1 Becquerel 2 Bethe 3 Bloch 4 Chadwick 5 Curie 6 Dirac 7 Einsten 8 Fermi 9 Feynman 10 Faraday 11 Galilei 12 Heisenberg 13 Maxwell 14 Newton 15 Planck 16 Rutherford 17 Schrodinger 18 Thomson 19 Walton b. i a[ i] 0 Becquerel 1 Bethe 2 Bloch 3 Bohr 4 Chadwick 5 Curie 6 Dirac 7 Einsten 8 Fermi 9 Feynman 10 Faraday 11 Galilei 12 Heisenberg 13 Maxwell 14 Newton 28 of 29

29 15 Planck 16 Rutherford 17 Schrodinger 18 Thomson 19 Walton i a[i] 0 Becquerel 1 Bethe 2 Bloch 3 Bohr 4 Chadwick 5 Curie 6 Dirac 7 Einsten 8 Faraday 9 Fermi 10 Feynman 11 Galilei 12 Heisenberg 13 Maxwell 14 Newton 15 Planck 16 Rutherford 17 Schrodinger 18 Thomson 19 Walton 21 Tries (Algorithms 5.2) 22 Substring Search (Algorithms 5.3) 23 Regular Expressions (Algorithms 5.4) 24 Data Compression (Algorithms 5.5) 29 of 29

COS 226 Algorithms and Data Structures Spring Midterm

COS 226 Algorithms and Data Structures Spring Midterm COS 226 Algorithms and Data Structures Spring 2012 Midterm This test has 9 questions worth a total of 60 points. You have 80 minutes. The exam is closed book, except that you are allowed to use a one page

More information

COS 226 Algorithms and Data Structures Spring Midterm

COS 226 Algorithms and Data Structures Spring Midterm COS 226 Algorithms and Data Structures Spring 2014 Midterm This test has 9 questions worth a total of 55 points. You have 80 minutes. The exam is closed book, except that you are allowed to use a one page

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

More information

Analysis of Algorithms 1 / 18

Analysis of Algorithms 1 / 18 Analysis of Algorithms 1 / 18 Outline 1 Complexity of Algorithms 2 Time Complexity 3 Space Complexity 2 / 18 Complexity of Algorithms Questions that arise when we write programs that process large amounts

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Final Review 1. Consider a binary tree of height k. (a) What is the maximum number of nodes? (b) What is the maximum number of leaves? (c) What is the minimum number of

More information

Basic Data Structures

Basic Data Structures Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1

More information

Priority Queues 1 / 15

Priority Queues 1 / 15 Priority Queues 1 / 15 Outline 1 API 2 Elementary Implementations 3 Heap Definitions 4 Algorithms on Heaps 5 Heap Sort 6 Heap Sort and Other Sorts 2 / 15 API Many applications require that we process items

More information

Final Exam. COS 226 Algorithms and Data Structures Fall 2015

Final Exam. COS 226 Algorithms and Data Structures Fall 2015 COS 226 Algorithms and Data Structures Fall 2015 Final Exam You have 180 minutes for this exam. The exam is closed book, except that you are allowed to use one page of notes (8.5-by-11, one side, in your

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40%

CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40% CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40% Name ID Directions: There are 9 questions in this exam. To earn a possible full score, you must solve all questions. Time allowed: 180 minutes Closed

More information

Course Review for Finals. Cpt S 223 Fall 2008

Course Review for Finals. Cpt S 223 Fall 2008 Course Review for Finals Cpt S 223 Fall 2008 1 Course Overview Introduction to advanced data structures Algorithmic asymptotic analysis Programming data structures Program design based on performance i.e.,

More information

COS 226 Algorithms and Data Structures Fall Midterm

COS 226 Algorithms and Data Structures Fall Midterm COS 226 Algorithms and Data Structures Fall 2017 Midterm This exam has 10 questions (including question 0) worth a total of 55 points. You have 0 minutes. This exam is preprocessed by a computer, so please

More information

( ) n 3. n 2 ( ) D. Ο

( ) n 3. n 2 ( ) D. Ο CSE 0 Name Test Summer 0 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to multiply two n n matrices is: A. Θ( n) B. Θ( max( m,n, p) ) C.

More information

Symbol Tables 1 / 15

Symbol Tables 1 / 15 Symbol Tables 1 / 15 Outline 1 What is a Symbol Table? 2 API 3 Sample Clients 4 Implementations 5 Performance Characteristics 2 / 15 What is a Symbol Table? A symbol table is a data structure for key-value

More information

( ) ( ) C. " 1 n. ( ) $ f n. ( ) B. " log( n! ) ( ) and that you already know ( ) ( ) " % g( n) ( ) " #&

( ) ( ) C.  1 n. ( ) $ f n. ( ) B.  log( n! ) ( ) and that you already know ( ) ( )  % g( n) ( )  #& CSE 0 Name Test Summer 008 Last 4 Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time for the following code is in which set? for (i=0; i

More information

( ) D. Θ ( ) ( ) Ο f ( n) ( ) Ω. C. T n C. Θ. B. n logn Ο

( ) D. Θ ( ) ( ) Ο f ( n) ( ) Ω. C. T n C. Θ. B. n logn Ο CSE 0 Name Test Fall 0 Multiple Choice. Write your answer to the LEFT of each problem. points each. The expected time for insertion sort for n keys is in which set? (All n! input permutations are equally

More information

logn D. Θ C. Θ n 2 ( ) ( ) f n B. nlogn Ο n2 n 2 D. Ο & % ( C. Θ # ( D. Θ n ( ) Ω f ( n)

logn D. Θ C. Θ n 2 ( ) ( ) f n B. nlogn Ο n2 n 2 D. Ο & % ( C. Θ # ( D. Θ n ( ) Ω f ( n) CSE 0 Test Your name as it appears on your UTA ID Card Fall 0 Multiple Choice:. Write the letter of your answer on the line ) to the LEFT of each problem.. CIRCLED ANSWERS DO NOT COUNT.. points each. The

More information

& ( D. " mnp ' ( ) n 3. n 2. ( ) C. " n

& ( D.  mnp ' ( ) n 3. n 2. ( ) C.  n CSE Name Test Summer Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to multiply two n " n matrices is: A. " n C. "% n B. " max( m,n, p). The

More information

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D.

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D. CSE 0 Name Test Fall 00 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to convert an array, with priorities stored at subscripts through n,

More information

Your data structure should implement all operations in logarithmic time (or better) as a function of the size of the queue.

Your data structure should implement all operations in logarithmic time (or better) as a function of the size of the queue. 1. Write a method isbst(node t) that checks that the binary subtree at t is a binary search tree. The method should return true if t is the root of a binary search tree and false otherwise. Assume Node

More information

n 2 ( ) ( ) Ο f ( n) ( ) Ω B. n logn Ο

n 2 ( ) ( ) Ο f ( n) ( ) Ω B. n logn Ο CSE 220 Name Test Fall 20 Last 4 Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. 4 points each. The time to compute the sum of the n elements of an integer array is in:

More information

End-Term Examination Second Semester [MCA] MAY-JUNE 2006

End-Term Examination Second Semester [MCA] MAY-JUNE 2006 (Please write your Roll No. immediately) Roll No. Paper Code: MCA-102 End-Term Examination Second Semester [MCA] MAY-JUNE 2006 Subject: Data Structure Time: 3 Hours Maximum Marks: 60 Note: Question 1.

More information

) $ f ( n) " %( g( n)

) $ f ( n)  %( g( n) CSE 0 Name Test Spring 008 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to compute the sum of the n elements of an integer array is: # A.

More information

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

Test 1 Last 4 Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. 2 points each t 1

Test 1 Last 4 Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. 2 points each t 1 CSE 0 Name Test Fall 00 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each t. What is the value of k? k=0 A. k B. t C. t+ D. t+ +. Suppose that you have

More information

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018 CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018 Instructions Form a small group. Start on the first problem. Check off with a helper or discuss your solution process with another group once

More information

n 2 ( ) ( ) + n is in Θ n logn

n 2 ( ) ( ) + n is in Θ n logn CSE Test Spring Name Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to multiply an m n matrix and a n p matrix is in: A. Θ( n) B. Θ( max(

More information

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 Asymptotics, Recurrence and Basic Algorithms 1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 1. O(logn) 2. O(n) 3. O(nlogn) 4. O(n 2 ) 5. O(2 n ) 2. [1 pt] What is the solution

More information

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers? Review for Final (Chapter 6 13, 15) 6. Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B. To

More information

Multiple Choice. Write your answer to the LEFT of each problem. 3 points each

Multiple Choice. Write your answer to the LEFT of each problem. 3 points each CSE 0-00 Test Spring 0 Name Last 4 Digits of Student ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. Suppose f ( x) is a monotonically increasing function. Which of the

More information

CSci 231 Final Review

CSci 231 Final Review CSci 231 Final Review Here is a list of topics for the final. Generally you are responsible for anything discussed in class (except topics that appear italicized), and anything appearing on the homeworks.

More information

n 2 C. Θ n ( ) Ο f ( n) B. n 2 Ω( n logn)

n 2 C. Θ n ( ) Ο f ( n) B. n 2 Ω( n logn) CSE 0 Name Test Fall 0 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to find the maximum of the n elements of an integer array is in: A.

More information

( ). Which of ( ) ( ) " #& ( ) " # g( n) ( ) " # f ( n) Test 1

( ). Which of ( ) ( )  #& ( )  # g( n) ( )  # f ( n) Test 1 CSE 0 Name Test Summer 006 Last Digits of Student ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to multiply two n x n matrices is: A. "( n) B. "( nlogn) # C.

More information

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May www.jwjobs.net R10 SET - 1 II B. Tech I Semester, Supplementary Examinations, May - 2012 (Com. to CSE, IT, ECC ) Time: 3 hours Max Marks: 75 *******-****** 1. a) Which of the given options provides the

More information

COS 226 Midterm Exam, Spring 2011

COS 226 Midterm Exam, Spring 2011 NAME: login ID: Precept (circle one): P01 P01A P01B P02 P02A P03 COS 226 Midterm Exam, Spring 2011 This test is 9 questions, weighted as indicated. The exam is closed book, except that you are allowed

More information

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu.

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu. 17CA 104DATA STRUCTURES Academic Year : 018-019 Programme : MCA Year / Semester : I / I Question Bank Course Coordinator: Mrs. C.Mallika Course Objectives The student should be able to 1. To understand

More information

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF

More information

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination University of Illinois at Urbana-Champaign Department of Computer Science Final Examination CS 225 Data Structures and Software Principles Spring 2010 7-10p, Wednesday, May 12 Name: NetID: Lab Section

More information

( ) 1 B. 1. Suppose f x

( ) 1 B. 1. Suppose f x CSE Name Test Spring Last Digits of Student ID Multiple Choice. Write your answer to the LEFT of each problem. points each is a monotonically increasing function. Which of the following approximates the

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

COS 226 Midterm Exam, Spring 2009

COS 226 Midterm Exam, Spring 2009 NAME: login ID: precept: COS 226 Midterm Exam, Spring 2009 This test is 10 questions, weighted as indicated. The exam is closed book, except that you are allowed to use a one page cheatsheet. No calculators

More information

CIS 121 Data Structures and Algorithms Midterm 3 Review Solution Sketches Fall 2018

CIS 121 Data Structures and Algorithms Midterm 3 Review Solution Sketches Fall 2018 CIS 121 Data Structures and Algorithms Midterm 3 Review Solution Sketches Fall 2018 Q1: Prove or disprove: You are given a connected undirected graph G = (V, E) with a weight function w defined over its

More information

Course Review. Cpt S 223 Fall 2009

Course Review. Cpt S 223 Fall 2009 Course Review Cpt S 223 Fall 2009 1 Final Exam When: Tuesday (12/15) 8-10am Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & class notes Homeworks & program

More information

Course goals. exposure to another language. knowledge of specific data structures. impact of DS design & implementation on program performance

Course goals. exposure to another language. knowledge of specific data structures. impact of DS design & implementation on program performance Course goals exposure to another language C++ Object-oriented principles knowledge of specific data structures lists, stacks & queues, priority queues, dynamic dictionaries, graphs impact of DS design

More information

( D. Θ n. ( ) f n ( ) D. Ο%

( D. Θ n. ( ) f n ( ) D. Ο% CSE 0 Name Test Spring 0 Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to run the code below is in: for i=n; i>=; i--) for j=; j

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

Recitation 9. Prelim Review

Recitation 9. Prelim Review Recitation 9 Prelim Review 1 Heaps 2 Review: Binary heap min heap 1 2 99 4 3 PriorityQueue Maintains max or min of collection (no duplicates) Follows heap order invariant at every level Always balanced!

More information

CS61BL. Lecture 5: Graphs Sorting

CS61BL. Lecture 5: Graphs Sorting CS61BL Lecture 5: Graphs Sorting Graphs Graphs Edge Vertex Graphs (Undirected) Graphs (Directed) Graphs (Multigraph) Graphs (Acyclic) Graphs (Cyclic) Graphs (Connected) Graphs (Disconnected) Graphs (Unweighted)

More information

( ) + n. ( ) = n "1) + n. ( ) = T n 2. ( ) = 2T n 2. ( ) = T( n 2 ) +1

( ) + n. ( ) = n 1) + n. ( ) = T n 2. ( ) = 2T n 2. ( ) = T( n 2 ) +1 CSE 0 Name Test Summer 00 Last Digits of Student ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. Suppose you are sorting millions of keys that consist of three decimal

More information

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# #

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# # 1. Prove that n log n n is Ω(n). York University EECS 11Z Winter 1 Problem Set 3 Instructor: James Elder Solutions log n n. Thus n log n n n n n log n n Ω(n).. Show that n is Ω (n log n). We seek a c >,

More information

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC)

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC) SET - 1 II B. Tech I Semester Supplementary Examinations, May/June - 2016 PART A 1. a) Write a procedure for the Tower of Hanoi problem? b) What you mean by enqueue and dequeue operations in a queue? c)

More information

COMP 251 Winter 2017 Online quizzes with answers

COMP 251 Winter 2017 Online quizzes with answers COMP 251 Winter 2017 Online quizzes with answers Open Addressing (2) Which of the following assertions are true about open address tables? A. You cannot store more records than the total number of slots

More information

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, 2015 Problem Topic Points Possible Points Earned Grader 1 The Basics 40 2 Application and Comparison 20 3 Run Time Analysis 20 4 C++ and Programming

More information

Algorithm Design (8) Graph Algorithms 1/2

Algorithm Design (8) Graph Algorithms 1/2 Graph Algorithm Design (8) Graph Algorithms / Graph:, : A finite set of vertices (or nodes) : A finite set of edges (or arcs or branches) each of which connect two vertices Takashi Chikayama School of

More information

Total Score /1 /20 /41 /15 /23 Grader

Total Score /1 /20 /41 /15 /23 Grader NAME: NETID: CS2110 Spring 2015 Prelim 2 April 21, 2013 at 5:30 0 1 2 3 4 Total Score /1 /20 /41 /15 /23 Grader There are 5 questions numbered 0..4 on 8 pages. Check now that you have all the pages. Write

More information

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate

More information

Second Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

Second Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms... Second Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms.... Q1) Let the keys are 28, 47, 20, 36, 43, 23, 25, 54 and table size is 11 then H(28)=28%11=6; H(47)=47%11=3;

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Final Examination CSE 100 UCSD (Practice)

Final Examination CSE 100 UCSD (Practice) Final Examination UCSD (Practice) RULES: 1. Don t start the exam until the instructor says to. 2. This is a closed-book, closed-notes, no-calculator exam. Don t refer to any materials other than the exam

More information

COS 226 Algorithms and Data Structures Fall Midterm Solutions

COS 226 Algorithms and Data Structures Fall Midterm Solutions 1 COS 226 Algorithms and Data Structures Fall 2010 Midterm Solutions 1. Analysis of algorithms. (a) For each expression in the left column, give the best matching description from the right column. B.

More information

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 MID YEAR COMP103 Introduction to Data

More information

Info 2950, Lecture 16

Info 2950, Lecture 16 Info 2950, Lecture 16 28 Mar 2017 Prob Set 5: due Fri night 31 Mar Breadth first search (BFS) and Depth First Search (DFS) Must have an ordering on the vertices of the graph. In most examples here, the

More information

Table of Contents. Chapter 1: Introduction to Data Structures... 1

Table of Contents. Chapter 1: Introduction to Data Structures... 1 Table of Contents Chapter 1: Introduction to Data Structures... 1 1.1 Data Types in C++... 2 Integer Types... 2 Character Types... 3 Floating-point Types... 3 Variables Names... 4 1.2 Arrays... 4 Extraction

More information

Solutions to Exam Data structures (X and NV)

Solutions to Exam Data structures (X and NV) Solutions to Exam Data structures X and NV 2005102. 1. a Insert the keys 9, 6, 2,, 97, 1 into a binary search tree BST. Draw the final tree. See Figure 1. b Add NIL nodes to the tree of 1a and color it

More information

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 Asymptotics, Recurrence and Basic Algorithms 1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 2. O(n) 2. [1 pt] What is the solution to the recurrence T(n) = T(n/2) + n, T(1)

More information

CS521 \ Notes for the Final Exam

CS521 \ Notes for the Final Exam CS521 \ Notes for final exam 1 Ariel Stolerman Asymptotic Notations: CS521 \ Notes for the Final Exam Notation Definition Limit Big-O ( ) Small-o ( ) Big- ( ) Small- ( ) Big- ( ) Notes: ( ) ( ) ( ) ( )

More information

Sorting Applications 1 / 9

Sorting Applications 1 / 9 Sorting Applications 1 / 9 Outline 1 Sorting Various Types of Data 2 Which Sorting Algorithm Should I Use? 3 Reductions 4 A Brief Survey of Sorting Applications 2 / 9 Sorting Various Types of Data Our

More information

COS 226 Algorithms and Data Structures Fall Midterm

COS 226 Algorithms and Data Structures Fall Midterm COS 226 Algorithms and Data Structures Fall 2014 Midterm This test has 9 questions worth a total of 55 points. You have 80 minutes. The exam is closed book, except that you are allowed to use a one page

More information

Analysis of Algorithms

Analysis of Algorithms Algorithm An algorithm is a procedure or formula for solving a problem, based on conducting a sequence of specified actions. A computer program can be viewed as an elaborate algorithm. In mathematics and

More information

DESIGN AND ANALYSIS OF ALGORITHMS

DESIGN AND ANALYSIS OF ALGORITHMS DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK Module 1 OBJECTIVE: Algorithms play the central role in both the science and the practice of computing. There are compelling reasons to study algorithms.

More information

2. True or false: even though BFS and DFS have the same space complexity, they do not always have the same worst case asymptotic time complexity.

2. True or false: even though BFS and DFS have the same space complexity, they do not always have the same worst case asymptotic time complexity. 1. T F: Consider a directed graph G = (V, E) and a vertex s V. Suppose that for all v V, there exists a directed path in G from s to v. Suppose that a DFS is run on G, starting from s. Then, true or false:

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 18 EXAMINATION Subject Name: Data Structure Model wer Subject Code: 17330 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in

More information

UNIT 5 GRAPH. Application of Graph Structure in real world:- Graph Terminologies:

UNIT 5 GRAPH. Application of Graph Structure in real world:- Graph Terminologies: UNIT 5 CSE 103 - Unit V- Graph GRAPH Graph is another important non-linear data structure. In tree Structure, there is a hierarchical relationship between, parent and children that is one-to-many relationship.

More information

Graph. Vertex. edge. Directed Graph. Undirected Graph

Graph. Vertex. edge. Directed Graph. Undirected Graph Module : Graphs Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS E-mail: natarajan.meghanathan@jsums.edu Graph Graph is a data structure that is a collection

More information

9. The expected time for insertion sort for n keys is in which set? (All n! input permutations are equally likely.)

9. The expected time for insertion sort for n keys is in which set? (All n! input permutations are equally likely.) CSE 0 Name Test Spring 006 Last 4 Digits of Student ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. Suppose f ( x) is a monotonically increasing function. Which of the

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination T09:00

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination T09:00 University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms Instructor: Douglas Wilhelm Harder Time: 2.5 hours Aides: none 18 pages Final Examination

More information

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I MCA 312: Design and Analysis of Algorithms [Part I : Medium Answer Type Questions] UNIT I 1) What is an Algorithm? What is the need to study Algorithms? 2) Define: a) Time Efficiency b) Space Efficiency

More information

COS 226 Algorithms and Data Structures Fall Final Solutions. 10. Remark: this is essentially the same question from the midterm.

COS 226 Algorithms and Data Structures Fall Final Solutions. 10. Remark: this is essentially the same question from the midterm. COS 226 Algorithms and Data Structures Fall 2011 Final Solutions 1 Analysis of algorithms (a) T (N) = 1 10 N 5/3 When N increases by a factor of 8, the memory usage increases by a factor of 32 Thus, T

More information

CSE373: Data Structures & Algorithms Lecture 28: Final review and class wrap-up. Nicki Dell Spring 2014

CSE373: Data Structures & Algorithms Lecture 28: Final review and class wrap-up. Nicki Dell Spring 2014 CSE373: Data Structures & Algorithms Lecture 28: Final review and class wrap-up Nicki Dell Spring 2014 Final Exam As also indicated on the web page: Next Tuesday, 2:30-4:20 in this room Cumulative but

More information

CS171 Final Practice Exam

CS171 Final Practice Exam CS171 Final Practice Exam Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 150 minutes to complete this exam. Read each problem carefully, and review your

More information

Course Name: B.Tech. 3 th Sem. No of hours allotted to complete the syllabi: 44 Hours No of hours allotted per week: 3 Hours. Planned.

Course Name: B.Tech. 3 th Sem. No of hours allotted to complete the syllabi: 44 Hours No of hours allotted per week: 3 Hours. Planned. Course Name: B.Tech. 3 th Sem. Subject: Data Structures No of hours allotted to complete the syllabi: 44 Hours No of hours allotted per week: 3 Hours Paper Code: ETCS-209 Topic Details No of Hours Planned

More information

cs2010: algorithms and data structures

cs2010: algorithms and data structures cs2010: algorithms and data structures Lecture 9: Priority Queues Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin Algorithms ROBERT SEDGEWICK KEVIN WAYNE 2.4 PRIORITY

More information

Graph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1

Graph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1 Graph Algorithms Chapter 22 CPTR 430 Algorithms Graph Algorithms Why Study Graph Algorithms? Mathematical graphs seem to be relatively specialized and abstract Why spend so much time and effort on algorithms

More information

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list

UNIT Name the different ways of representing a graph? a.adjacencymatrix b. Adjacency list UNIT-4 Graph: Terminology, Representation, Traversals Applications - spanning trees, shortest path and Transitive closure, Topological sort. Sets: Representation - Operations on sets Applications. 1. Name

More information

Thomas H. Cormen Charles E. Leiserson Ronald L. Rivest. Introduction to Algorithms

Thomas H. Cormen Charles E. Leiserson Ronald L. Rivest. Introduction to Algorithms Thomas H. Cormen Charles E. Leiserson Ronald L. Rivest Introduction to Algorithms Preface xiii 1 Introduction 1 1.1 Algorithms 1 1.2 Analyzing algorithms 6 1.3 Designing algorithms 1 1 1.4 Summary 1 6

More information

Direct Addressing Hash table: Collision resolution how handle collisions Hash Functions:

Direct Addressing Hash table: Collision resolution how handle collisions Hash Functions: Direct Addressing - key is index into array => O(1) lookup Hash table: -hash function maps key to index in table -if universe of keys > # table entries then hash functions collision are guaranteed => need

More information

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value 1 Possible implementations Sorted linear implementations o Appropriate if

More information

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \ BSc IT C Programming (2013-2017) Unit I Q1. What do you understand by type conversion? (2013) Q2. Why we need different data types? (2013) Q3 What is the output of the following (2013) main() Printf( %d,

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Prelim 2 Solution. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

Prelim 2 Solution. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader Prelim 2 CS 2110, November 19, 2015, 7:30 PM 1 2 3 4 5 6 Total Question True Short Complexity Searching Trees Graphs False Answer Sorting Invariants Max 20 15 13 14 17 21 100 Score Grader The exam is closed

More information

CSE 373 Final Exam 3/14/06 Sample Solution

CSE 373 Final Exam 3/14/06 Sample Solution Question 1. (6 points) A priority queue is a data structure that supports storing a set of values, each of which has an associated key. Each key-value pair is an entry in the priority queue. The basic

More information

Data Structure. A way to store and organize data in order to support efficient insertions, queries, searches, updates, and deletions.

Data Structure. A way to store and organize data in order to support efficient insertions, queries, searches, updates, and deletions. DATA STRUCTURES COMP 321 McGill University These slides are mainly compiled from the following resources. - Professor Jaehyun Park slides CS 97SI - Top-coder tutorials. - Programming Challenges book. Data

More information

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted, [1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n

More information

CSE 431/531: Algorithm Analysis and Design (Spring 2018) Greedy Algorithms. Lecturer: Shi Li

CSE 431/531: Algorithm Analysis and Design (Spring 2018) Greedy Algorithms. Lecturer: Shi Li CSE 431/531: Algorithm Analysis and Design (Spring 2018) Greedy Algorithms Lecturer: Shi Li Department of Computer Science and Engineering University at Buffalo Main Goal of Algorithm Design Design fast

More information

COS 226 Algorithms and Data Structures Fall Final Exam

COS 226 Algorithms and Data Structures Fall Final Exam COS 226 lgorithms and Data Structures Fall 2012 Final Exam This test has 16 questions worth a total of 100 points. You have 180 minutes. The exam is closed book, except that you are allowed to use a one

More information

Graph Algorithms Using Depth First Search

Graph Algorithms Using Depth First Search Graph Algorithms Using Depth First Search Analysis of Algorithms Week 8, Lecture 1 Prepared by John Reif, Ph.D. Distinguished Professor of Computer Science Duke University Graph Algorithms Using Depth

More information

Reference Sheet for CO142.2 Discrete Mathematics II

Reference Sheet for CO142.2 Discrete Mathematics II Reference Sheet for CO14. Discrete Mathematics II Spring 017 1 Graphs Defintions 1. Graph: set of N nodes and A arcs such that each a A is associated with an unordered pair of nodes.. Simple graph: no

More information

COS 226 Algorithms and Data Structures Fall Final

COS 226 Algorithms and Data Structures Fall Final COS 226 Algorithms and Data Structures Fall 2009 Final This test has 12 questions worth a total of 100 points. You have 180 minutes. The exam is closed book, except that you are allowed to use a one page

More information

UCS-406 (Data Structure) Lab Assignment-1 (2 weeks)

UCS-406 (Data Structure) Lab Assignment-1 (2 weeks) UCS-40 (Data Structure) Lab Assignment- (2 weeks) Implement the following programs in C/C++/Python/Java using functions a) Insertion Sort b) Bubble Sort c) Selection Sort d) Linear Search e) Binary Search

More information