45
1. What is data structure? A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data. 2. List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation 3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model. RDBMS – Array (i.e. Array of structures) Network data model – Graph Hierarchical data model – Trees 4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type. 5. Minimum number of queues needed to implement a priority queue? 1 Data Structures and

ds_algo

Embed Size (px)

Citation preview

Page 1: ds_algo

1. What is data structure?

A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.

2. List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation

3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.

RDBMS – Array (i.e. Array of structures) Network data model – Graph Hierarchical data model – Trees

4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.

5. Minimum number of queues needed to implement a priority queue?

Two. One queue is used for actual storing of data and another for storing priorities.

6. What is the data structure used to perform recursion?Stack. Because of its LIFO (Last In First Out) property it remembers its ‘caller’;

so the function knows where to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.

Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.

1

Data Structures and Algorithms

Page 2: ds_algo

7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms?

Polish and Reverse Polish notations.

8. Convert the expression ((A + B) * C – (D – E) ^ (F + G)) to equivalent Prefix and Postfix notations.

Prefix Notation:^ - * +ABC - DE + FGPostfix Notation:AB + C * DE - - FG + ^

9. Sorting is not possible by using which of the following methods?(a) Insertion (b) Selection (c) Exchange (d) Deletion

Answer:(d)deletion

Explanation:Using insertion we can perform insertion sort, using selection we can perform

selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion.

10. A binary tree with 20 nodes has null branches.Answer:

21Explanation:

Let us take a tree with 5 nodes (n=5)

It will have only 6 (ie,5+1) null branches. In general, a binary tree with n nodes has exactly n+1 null nodes.

11. What are the methods available in storing sequential files ? Straight merging, Natural merging, Polyphase sort, Distribution of Initial runs.

12. How many different trees are possible with 10 nodes ?

2

Null Branches

Page 3: ds_algo

Answer:1014

Explanation:For example, consider a tree with 3 nodes(n=3), it will have the maximum

combination of 5 different (ie, 23 - 3 = 5) trees.

i ii iii iv v

In general:If there are n nodes, there exist 2n-n different trees.

13. List out a few of the applications of tree data-structure in compilers/compiler design. The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis.

14. List out a few of the applications that make use of Multilinked Structures. Sparse matrix, Index generation.

15. In tree construction which is the suitable efficient data structure?(a ) Array (b) Linked list (c) Stack (d) Queue (e) none

Answer:(b) Linked list

16. What type of the algorithm is used in solving the 8 Queens problem?Backtracking

17. In an AVL tree, what is the condition for balancing to be done? The ‘pivotal value’(or the ‘Height factor’) is greater than 1 or less than–1.

18. What is the bucket size, when overlapping and collision occur at the same time?One. If there is only one entry possible in the bucket, when the collision occurs,

there is no way to accommodate the colliding value. This results in the overlapping of values.

3

Page 4: ds_algo

19. Traverse the given tree using Inorder, Preorder and Postorder traversals.

Inorder : D H B E A F C I G J Preorder: A B D H E C F G I J Postorder: H D E B F I J G C A

20. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have formed a full binary tree?

15. In general:

There are 2n-1 nodes in a full binary tree.By the method of elimination:

Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correct answer is 15.Note:

Full and Complete binary trees are different. All full binary trees are complete binary trees but not vice versa.

21. In the given binary tree, using array, at which location can you store the node 4?

4

A

B C

D E F G

H I J

Given tree:

1

2 3

4

5

Page 5: ds_algo

Answer:At location 6

Explanation:1 2 3 - - 4 - - 5

Root LC1 RC1 LC2 RC2 LC3 RC3 LC4 RC4where LCn means Left Child of node n and RCn means Right Child of node n

22. Sort the given values using Quick Sort?

65 70 75 80 85 60 55 50 45Sorting takes place from the pivot value, which is the first value of the given

elements, this is marked bold. The values at the left pointer and right pointer are indicated using L and R respectively.

65 70L 75 80 85 60 55 50 45R

Since pivot is not yet changed the same process is continued after interchanging the values at L and R positions

65 45 75 L 80 85 60 55 50 R 7065 45 50 80 L 85 60 55 R 75 7065 45 50 55 85 L 60 R 80 75 7065 45 50 55 60 R 85 L 80 75 70

When the L and R pointers cross each other the pivot value is interchanged with the value at right pointer. If the pivot is changed it means that the pivot has occupied its original position in the sorted order (shown in bold italics) and hence two different arrays are formed, one from start of the original array to the pivot position-1 and the other from pivot position+1 to end.

60 L 45 50 55 R 65 85 L 80 75 70 R

55 L 45 50 R 60 65 70 R 80 L 75 8550 L 45 R 55 60 65 70 80 L 75 R 85

In the next pass we get the sorted form of the array.

45 50 55 60 65 70 75 80 85

23. For the given graph, draw the DFS and BFS?

5

A

HX

G PE

Y

M J

The given graph:

Page 6: ds_algo

BFS: A X G H P E M Y J DFS: A X H P E Y M J G

24. Classify the Hashing Functions based on the various methods by which the key value is found.

Direct method, Subtraction method, Modulo-Division method, Digit-Extraction method, Mid-Square method, Folding method, Pseudo-random method.

25. What are the types of Collision Resolution Techniques and the methods used in each of the type?

Open addressing (closed hashing).The methods used include:

Overflow block. Closed addressing (open hashing)The methods used include:

Linked list, Binary tree…

26. In RDBMS, what is the efficient data structure used in the internal storage representation?

B+ tree. Because in B+ tree, all the data are stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.

27. Draw the B-tree of order 3 created by inserting the following data arriving in sequence – 92 24 6 7 11 8 22 4 5 16 19 20 78

28. Of the following tree structure, which is efficient considering space and time complexities?

(a) Incomplete Binary Tree(b) Complete Binary Tree

6

11 -

5 7 19 24

4 - 6 - 8 - 16 - 20 22 78 92

Page 7: ds_algo

(c) Full Binary TreeAnswer:

(b) Complete Binary Tree. Explanation:

By the method of elimination:Full binary tree loses its nature when operations of insertions and deletions are

done. For incomplete binary trees, extra storage is required and overhead of NULL node checking takes place. So complete binary tree is the better one since the property of complete binary tree is maintained even after operations like additions and deletions are done on it.

29. What is a spanning Tree?A spanning tree is a tree associated with a network. All the nodes of the graph

appear on the tree once. A minimal spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized.

30. Does the minimal spanning tree of a graph give the shortest distance between any 2 specified nodes?Answer:

No.Explanation:

Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn’t mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.

31. Convert the given graph with weighted edges to minimal spanning tree.

the equivalent minimal spanning tree is:

7

1 3

2 4

5410

600

200

400

310

1421

2985

612

1

2

3

4 5

410 612200

310

Page 8: ds_algo

32. Which is the simplest file structure?(a) Sequential (b) Indexed (c) Random

Answer:(a) Sequential

33. Is linked-list a linear or non-linear data structure?According to Access strategies Linked list is a linear one.According to Storage, Linked List is a Non-linear one.

34. Draw a binary Tree for the expression :A * B - (C + D) * (P / Q)

35. For the following COBOL code, draw the Binary tree?01 STUDENT_REC.02 NAME.03 FIRST_NAME PIC X(10).03 LAST_NAME PIC X(10).02 YEAR_OF_STUDY.03 FIRST_SEM PIC XX.03 SECOND_SEM PIC XX.

8

-

* *

A B + /

C PD Q

Page 9: ds_algo

Section II – Algorithms1. What is an ‘algorithm’?

An algorithm consists of a finite set of steps that may require one or more operations. These operations should be definite and effective. An algorithm should produce one or more output’s and may have zero or more inputs.This consists of five distinct areas: 1. to device algorithms

2. to validate the algorithms 3. to express the algorithms 4. to analyse the algorithms 5. to test the programs for the algorithms

2. What is a ‘computational procedure’?An algorithm that does not terminate is called ‘computational procedure’.

Example for such ‘computational procedure’ is an ‘operating system’.

3. Define - ‘recursive algorithm’.An algorithm is said to be recursive if the same algorithm is invoked in the body

of the algorithm. Recursive algorithms can be divided into direct recursive and indirect recursive algorithms.Direct recursive:

An algorithm that calls itself. Indirect Recursive:

An algorithm ‘A’ is said to be indirect recursive if it calls another algorithm which in-turn calls algorithm ‘A’.

9

STUDENT_REC

NAME YEAR_OF_STUDY

FIRST_NAME LAST_NAME FIRST_SEM SECOND_SEM

01

02 02

03 03 03 03

Page 10: ds_algo

4. How can you classify performance analysis?‘Performance analysis’ can be classified as:

i. priori analysisii. posteriori analysis

Priori Analysis:The bounds of algorithms’ computing time are obtained by formulating a

function.Posteriori Analysis:

Testing the actual computation of space and time are recorded while the algorithm is executing.

5. Define - ‘Big- O’. For the function f(n)

f(n)=O(g(n)) iff there exist positive constants c and d such that:

f(n) <=c*g(n) for all n,n>=d.

This is defined to be the worst-time complexity of the function f(n).For example:

O(n)=3n+2 because, 3n+2 <=4n for all n>=2.

6. Give various computing times and their meaning.Few of the important computing times are:

Computing Time Meaning

O(1) : constant computing timeO(n) : linear computing timeO(n*n) : quadratic computing timeO(n*n*n) : cubic computing timeO(2*2*2*2*..............*n) : exponential computing time

7. Give the most important ‘basic designs‘ of algorithms.

There are five important basic designs for algorithms. They are:i. Divide and conquer,ii. The greedy method,iii. Dynamic programming,iv. Back-tracking,v. Branch and bound.

8. How does ‘divide and conquer’ algorithms work?

For a function to compute on n inputs the divide and conquer strategy suggests the inputs into a k distinct subsets, 1<k<=n, yielding k sub-problems. These sub-problems must be solved and then a method must be found to combine the sub-solutions into a solution of the whole.

10

Page 11: ds_algo

An example for this approach is ‘binary search’ algorithm. The time complexity of binary search algorithm is O(log n).

9. What is Greedy Method?The greedy method suggests that one can devise an algorithm that works in

stages, considering one input at a time. At each stage, a decision is made regarding whether a particular input is an optimal solution. An example for solution using greedy method is ‘knapsack problem’.

10. What is Dynamic Programming?Dynamic Programming is an algorithm design method that can be used when the

solution to a problem can be viewed as the result of a sequence of decisions. An example for algorithm using dynamic programming is ‘multistage graphs’.

11. What are the time complexities for the following algorithms?Binary search : O(logn)Finding maximum and minimum for a given set of numbers

: O(3n/2-2)Merge Sort : O(nlogn)Insertion Sort : O(n*n);Quick Sort : O(nlogn)Selection Sort : O(n)

12. What is the difference between Merge Sort and Quick sort?Both Merge-sort and Quick-sort have same time complexity i.e. O(nlogn). In

merge sort the file a[1:n] was divided at its midpoint into sub-arrays which are independently sorted and later merged. Whereas, in quick sort the division into two sub-arrays is made so that the sorted sub-arrays do not need to be merged latter.

13. Is there any optimum solution for Matrix multiplication?Yes. Divide and conquer method suggests Strassen’s matrix multiplication

method to be used. If we follow this method, the time complexity is O(n*n*n……..*2.81) times rather O(n*n*n*………*3) times.

14. Define ‘minimum cost spanning method’.Let G=(V,E) be an undirected connected graph. A sub-graph t =(V, E’) of G is a

spanning tree of G if and only if t is a tree.To find out minimum cost spanning method we have following method’s;

Prim’s Algorithm : O(n*n)Kruskal’s Algorithm : O(e loge)

15. Define ’articulation points’.A Vertex V in a connected graph G is an articulation point if and only if the

deletion of vertex V together will all edges incident for disconnects the graph into two or more non-empty Components.

11

Page 12: ds_algo

16. Define ‘biconnected graph’.A graph G is biconnected if and only if it contains no articulation points.

17. What are ‘explicit’ and ‘implicit’ constraints? ‘Explicit constraints’ are rules that restrict each xi to take on values only from a

given set. ‘Implicit constraints’ are rules that determine which of the tuples in the solution space of i satisfy the criterion function.

18. Give ‘Cookies – theorem’.Satisfiability is in P iff P=NPwhere P is the set of all decision problems solvable by deterministic algorithms in

polynomial time and NP is the set of all decision problems solvable by non-deterministic algorithms in a polynomial-time.

Data Structures & Algorithms

Exam 1

Sample 1, 75 Minutes

1. In the class ArrayLinearList a linear list is represented in a one-dimensional array element. The data member size is such that the list elements are in positions 0 through size-1 of the array. The member method rightShift shifts the elements of the linear list right by k positions and fills the empty positions at the left end with null. For example, if the list element[0:5] = [1, 2, 3, 4, 5, 6], whose size is 6, is shifted right by 3, the result is [0, 0, 0, 1, 2, 3, 4, 5, 6], whose size is 9.

(a) [8] Write Java code for the rightShift member method. (b) [2] What is the time complexity of your code as a function of the list size?

2. Consider the class Chain which has the data members firstNode and size. The data type of firstNode is ChainNode. Objects of type ChainNode have the data members element and next. Nodes on a chain are linked together using the field next.

The method isSorted, which is a member of Chain determines whether the chain elements are in ascending (more accurately nondecreasing) order of their element values. The method returns true if the chain is sorted and false if it is not.

(a)

12

Page 13: ds_algo

[8] Write Java code for the isSorted member method. To compare two objects a and b you may do something like

if (((Comparable) a).compareTo(b) > 0){// come here only if a greater than b}

(b) [2] What is the time complexity of your code as a function of the list length?

3. In an n x n N-matrix, all terms other than those in column 1, column n, and the main diagonal are zero. An N-matrix has at most 3n-2 nonzero terms. An N-matrix can be compactly stored in a one-dimensional array by first storing column 1, then column n, and then the remaining elements of the main diagonal.

4. x x 5. x x x6. x x zero x7. x x x8. x x x9. x zero x x10. x x x11. x x12.

13. x denotes a possible nonzero14. all other terms are zero

(a) [2] Give a sample 4 x 4 N-matrix and its compact representation. (b) [8] Suppose that we are defining a class NMatrix that represents an n x n N-matrix in a one-dimensional array element as above. Besides element, the class has the data members n and zero (the zero element for the matrix). Write Java code for the member method set(i, j, newValue) which stores newValue as the (i,j) element of the N-matrix, 1 <= i <= n and 1 <= j <= n. The element is to be stored in the proper position of the one-dimensional array element.

Data Structures & Algorithms

Exam 1

Sample 3, 75 Minutes

Notes:

13

Page 14: ds_algo

1. Write your name, social security number, and section in which you want your exam returned on each sheet.

2. Begin the answer to each question on a new sheet.

1. The class MyList represents a linear list. This class has a member class that implements the Java interface Iterator (recall that Iterator has the public methods hasNext, next, and remove, the remove method is not required for this problem). The class MyList has the public methods clear() that makes the list this empty, append(Object x) that appends x to the right end of the linear list this and iterator() that returns an iterator for the list.

The public static method split(MyList a, MyList b, MyList c) is to be written. Following an invocation of split, b has elements 0, 2, 4, ... of a (in this order) and c has the remaining elements (in order). List a is unchanged. For example, if a is [a, b, c, d, e], then following a split, a, b and c are, respectively, [a, b, c, d, e], [a, c, e] and [b, d]. Notice that the split lists b and c may not be empty initially.

(a) [8] Write code for the public static method split. Do not assume the existence of any methods other than those stated above.

(b) [2] What is the time complexity of your code as a function of the size of list a? Explain how you arrived at this complexity. Assume that each of the methods given above takes O(1) time.

2. In the class MyArrayList a linear list is represented using a one-dimensional array element. The data member size is such that the list elements are in positions 0 through size-1 of the array. The method removeNull (which is a method of MyArrayList) removes every null element of the list. For example, suppose that the list x is [1, null, 3, null, null, 6] (list size is 6). Then following the invocation x.removeNull(), the list is [1, 3, 6] (the size is now 3).

(a) [8] Write code for the member method removeNull. Do not assume the existence of any methods for MyArrayList.

(b) [2] What is the time complexity of your code as a function of the initial list size?

14

Page 15: ds_algo

3. Consider the class MyCHList, which is a singly-linked circular list with header node. The data members of this class are headerNode and size. The data type of headerNode is MyChainNode. Objects of type MyChainNode have the data members element (which is an int) and next (whose data type is MyChainNode.

Nodes on the circular list are linked together using the field next. size is an integer whose value equals the number of elements in the chain (this count excludes the header node/element).

The value in the element field of a header node is INFINITY, where INFINITY is a constant that is larger than the value in any non-header node. Excluding the header, the elements are in ascending (or more accurately nondecreasing) order left to right. The method merge(MyCHList a, MyCHList b) merges the elements in a and b to yield a sorted circular list with header, which is pointed at by this.headerNode. Following the merge, the lists a and b are empty (i.e., they have only a header node and their size is 0).

If a and b are initially [INFINITY, 1, 4, 9] and [INFINITY, 2, 3], then following the merge, a and b are [INFINITY] and this is [INFINITY, 1, 2, 3, 4, 9] (note that INFINITY is the element in the header). The size of this is 5 and that of a and b is 0.

(a) [12] Write code for the member method merge. You must not create new nodes. Reuse the nodes of a and b. Do not assume the existence of any methods for MyCHList. (Possible Hint: To keep the code short, use a single loop.)

(b) [2] What is the time complexity of your code as a function of the length of the resulting chain? Explain how you arrived at this complexity.

Data Structures & Algorithms

Exam 1

Sample 3, 75 Minutes

Solutions

1. (a) The code is given below.

public static void split(MyList a, MyList b, MyList c)

15

Page 16: ds_algo

{ // initialize iterator for a Iterator ia = a.iterator(); // iterator for a

// make b and c empty b.clear(); c.clear();

// append elements from a alternately to b and c while (ia.hasNext()) { b.append(ia.next()); if (ia.hasNext()) c.append(ia.next()); }}

(b) Let n be the size of list a. The while loop is iterated O(n) times, and each iteration takes O(1) time. So the while loop takes O(n) time. The remainder of the code takes takes O(1) time. Therefore, the total time taken by the method is O(n).

2. (a) The code is given below.

public void removeNull(){ int newSize = 0; // number of non-null elements so far // do the removing for (int i = 0; i < size; i++) if (element[i] != null) // save this element element[newSize++] = element[i];

// clean up for garbage collection // this work may be combined into the preceding for loop by // adding the statement element[i] = null; into the if statement for (int i = newSize; i < size; i++) element[i] = null;

size = newSize; // update size}

16

Page 17: ds_algo

(b) Each for loop iterates O(n) times, where n is the initial size of the list. Each iteration of each loop takes O(1) time. Therefore, the complexity of the loops is O(n). The remainder of the code takes O(1) time. Therefore, the overall complexity is O(n).

3. (a) The code is given below.

public void merge(MyCHList a, MyCHList b){ // do the merging MyChainNode currentA = a.headerNode.next, currentB = b.headerNode.next, lastThis = headerNode;

while (currentA != a.headerNode || currentB != b.headerNode) // elements remain if (currentA.element <= currentB.element) {// merge from a lastThis = lastThis.next = currentA; currentA = currentA.next; } else {// merge from b lastThis = lastThis.next = currentB; currentB = currentB.next; }

// merged all elements // close circular list this and update size lastThis.next = headerNode; size = a.size + b.size;

// make a and b empty a.header.next = a.header; b.header.next = b.header; a.size = b.size = 0;}

(b) In each iteration of the while loop one node/element is added to the result list. Therefore, this loop is iterated n times, where n is the size of the result list. Each iteration of the loop takes O(1) time. Therefore, the complexity of the loop is O(n). The remainder of the code takes O(1) time. Therefore, the overall complexity is O(n).

17

Page 18: ds_algo

Data Structures & Algorithms

Exam 1

Sample 2, 75 Minutes

1. In the class ArrayLinearList a linear list is represented as a one-dimensional array element. The data member size is such that the list elements are in positions 0 through size-1 of the array. The member method compress removes every other element of the list. For example, if the list element[0:5] = [1, 2, 3, 4, 5, 6], whose size is 6, is compressed, the result is [1, 3, 5], whose size is 3.

(a) [8] Write code for the member method compress. Do not assume the existence of any methods for ArrayLinearList.

(b) [2] What is the time complexity of your code as a function of the list size?

2. Consider the class Chain. The public methods of this class are: makeEmpty() ... make the chain empty. The time taken by this method is O(1). append(x) ... append x to the end of the chain. The time taken by this method is O(1). iterator() ... returns an object of type Iterator that can be used to move through the chain from left to right. The time taken by this method is O(1).

The public methods associated with the chain iterator are: hasNext() ... returns true iff the chain has more elements. The time taken by this method is O(1). next() ... returns the next element in the chain; returns null if there is no next element. The time taken by this method is O(1).

The nonmember method threeWaySplit(a,b,c,d) splits the chain a into three chains b, c, and d. The first, fourth, seventh, ... elements of a, in that order, define the chain b; the second, fifth, eighth, ... elements of a, in that order, define the chain c; and the third, sixth, ninth, ... elements of a, in that order, define the chain d. The chain a is not modified by the split.

18

Page 19: ds_algo

(a) [8] Write code for the nonmember method threeWaySplit(a,b,c,d). Do not assume the existence of any methods other than those stated above.

(b) [2] What is the time complexity of your code as a function of the length of the initial chain a?

3. In an n x n S-matrix, n is odd and all terms other than those in rows 1, n and n/2 + 1, the top half of column 1, and the bottom half of column n are zero. An S-matrix can be compactly stored in a one-dimensional array by first storing the rows of the S in the order 1, n/2 + 1, and n. Next, the remaining elements of column 1 of the S are stored. Finally, the remaining elements of column n of the S are stored.

4. x x x x x x x x x 5. x 6. x zero 7. x 8. x x x x x x x x x 9. x10. zero x11. x12. x x x x x x x x x 13.

14. x denotes a possible nonzero15.

16. all other terms are zero

(a) [2] Give a sample 5 x 5 S-matrix and its compact representation.

(b) [8] Suppose that we are defining a class SMatrix that represents an n x n S-matrix in a one-dimensional array element as above. Besides element, the class has the data members n and zero (the zero element for the matrix). Write code for the member method get(i, j) which returns the value of S(i,j) for 1 <= i <= n and 1 <= j <= n. You must verify that i and j are in this range.

19

Page 20: ds_algo

Data Structures & Algorithms

Exam 1

Sample 2, 75 Minutes

Solutions

1. (a) The code is given below.

public void compress(){// Eliminate element[i], i = 1, 3, 5, ... and pack.

// eliminate and pack left to right for (int i = 2; i < size; i += 2) element[i / 2] = element[i];

// should set element[newSize : size-1] to null to // enable garbage collection, not required for test

size = (size + 1) / 2; // new size}

(b) The for loop iterates O(size) times, and each iteration takes O(1) time. The remainder of the code takes O(1) time. Therefore, the overall complexity is O(size).

2. (a) The code is given below.

public static void threeWaySplit(Chain a, Chain b, Chain c, Chain d){// Split a into three chains b, c, and d. // When done, a is unchanged. // empty out b, c, and d b.makeEmpty(); c.makeEmpty(); d.makeEmpty();

// assign elements to b, c, and d Iterator ia = a.iterator(); // iterator for a while (ia.hasNext()) { // first give b an element b.append(ia.next()); if (!ia.hasNext())

20

Page 21: ds_algo

break; // now give c an element c.append(ia.next()); if (!ia.hasNext()) break; // now give d an element d.append(ia.next()); }}

(b) The time needed to make the chains b, c, and d empty is O(1). The while loop iterates O(size of a) times. So, the complexity is O(size of a).

3. (a) A sample 5 x 5 S-matrix is given below. 4. 1 0 3 2 15. 3 0 0 0 06. 6 1 7 0 37. 0 0 0 0 18. 9 6 5 4 1

The compact representation is [1,0,3,2,1,6,1,7,0,3,9,6,5,4,1,3,1].

(b) The code is given below.

public Object get(int i, int j){// return S(i,j) if ( i < 1 || j < 1 || i > n || j > n) throw new IllegalArgumentException("index out of range");

if (i == 1) // first row return element[j - 1];

if (i == n / 2 + 1) // middle row return element[n + j - 1];

if (i == n ) // bottom row return element[2 * n + j - 1];

if (i <= n / 2 && j == 1) // first column of S

21

Page 22: ds_algo

return element[3 * n + i - 2];

if (i > n / 2 + 1 && j == n) // last column of S return element[3 * n + i - 3]; else // not in S return zero;}

Data Structures & Algorithms

Exam 1

Sample 1, 75 Minutes

Solutions

1. (a) The code is given below.

public void rightShift(int k){// Shift elements right by k. // make sure k is nonnegative if (k < 0) throw new IllegalArgumentException("Shift amount must be >= 0");

// make sure we have enough space if (size + k > element.length) {// get larger array Object [] newArray = new Object [size + k]; for (int i = 0; i < size; i++) newArray[i] = element[i]; element = newArray; }

// shift elements from right to left for (int i = size - 1; i >= 0; i--) element[i+k] = element[i];

// zero fill at left end for (int i = 0; i < k; i++) element[i] = null;

size += k; // new size}

(b)

22

Page 23: ds_algo

When an exception is thrown the complexity is Theta(1). Otherwise, it takes O(size + k) time to increase the array size (if necessary). The second for loop takes O(size)), and the third loop takes O(k) time. Therefore, the complexity is O(size+k).

2. (a) The code is given below.

public boolean isSorted(){// Return true if the elements are in // nondecreasing order; return false otherwise. if (firstNode == null) return true; // empty

// check nonempty chain ChainNode currentNode = firstNode, nextNode = firstNode.next; while (nextNode != null) { if (((Comparable) currentNode.element).compareTo(nextNode.element) > 0) return false; currentNode = nextNode; nextNode = currentNode.next; } return true;}

(b) The while iterates at most size-1 times and each iteration takes Theta(1) time. The remaining lines take Theta(1) time. Therefore, the overall complexity is O(size).

3. (a) A sample 4 x 4 N-matrix is given below. 4. 1 0 0 25. 3 4 0 56. 6 0 7 87. 9 0 0 1

The compact representation is [1,3,6,9,2,5,8,1,4,7]. (b) The code is given below.

public void set(int i, int j, Object newValue){// Store newValue as N(i,j).

23

Page 24: ds_algo

if ( i < 1 || j < 1 || i > n || j > n) throw new IllegalArgumentException("index out of range");

if (j == 1) element[i-1] = newValue; // first column else if (j == n) element[n+i-1] = newValue; // last column else if (i == j) element[2*n+i-2] = newValue; // rest of diagonal else if (!newValue.equals(zero)) throw new IllegalArgumentException("value must be zero");}

Data Structures & Algorithms

Exam 2, Sample 2

75 Minutes

Points allocated to each part are shown in square brackets. Answers will be graded on correctness as well as efficiency, elegance, and other measures of quality.

1. An abbreviated version of the classes BinaryTreeNode and LinkedBinaryTree of the text is given below.

public class BinaryTreeNode{ // package visible data members Object element; BinaryTreeNode leftChild; // left subtree BinaryTreeNode rightChild; // right subtree }

public class LinkedBinaryTree implements BinaryTree{ // instance data member BinaryTreeNode root; // root node}

24

Page 25: ds_algo

You are to write a public method elementAtLevel(int theLevel) which returns null if the binary tree has no element at level theLevel; otherwise, it returns an element at this level.

(a) [16] Write Java code for the public method elementAtLevel. You may define and implement additional methods as needed. You may not create or delete any nodes or invoke any methods for which you have not provided code. (Hint: use recursion.) (b) [2] What is the time complexity of your code as a function of the number of nodes in the binary tree?

2. There are eight players named a through h in a tournament. Their values are [4, 7, 3, 6, 5, 1, 8, 2]. When two players play a match, the one with smaller value wins.

(a) [4] Draw the winner tree for the tournament. Label internal nodes with player names and external nodes with player values and names. (b) [4] Draw the loser tree for the tournament. Label internal nodes with player names and external nodes with player values and names.

3. (a) [4] Draw a tree that represents a set of elements. The depth of your tree should be at least 7. The tree need not be one that results from the use of either the weight or the height rule. Show the tree that results following the operation Find(e), where e is an element at level 7 and we are using path halving. (b) [8] Suppose you have a binary tree whose data fields are single characters. When the data fields of the nodes are output in inorder, the output is ABCDEFGHIJ, and when they are output in preorder, the output is BAHCEDGFJI. Draw the binary tree showing the data in each node and the pointers between nodes. Show the steps used to arrive at the result. (c) [8] Draw the height biased max leftist tree that results when the height biased max leftist trees below are melded by following their rightmost paths (use the strategy used in the meld algorithm of the text). Show the steps used to arrive at the result.

60 70 / \ / \ / \ / \ 55 48 61 54 / \ / \ / \ / \ 50 52 20 30 58 59 53 45 / /

25

Page 26: ds_algo

40 56

Data Structures & Algorithms

Exam 2, Sample 2

75 Minutes

Solutions

1. (a) To implement a recursive strategy, we need to define a public and a private elementAtLevel method. The public method can be defined as below:/** @return an element at level theLevel */public Object elementAtLevel(int theLevel) {return elementAtLevel(root, theLevel);}

The private method that does the actual search for an element at the desired level.

/** @return an element at level theLevel of subtree rooted at t */private static Object elementAtLevel(BinaryTreeNode t, int theLevel){ if (t == null) // empty tree, no element at level theLevel return null;

if (theLevel == 1) // t is at level 1 return t.element;

// search for desired element in left subtree Object x = elementAtLevel(t.leftChild, theLevel - 1); if (x != null) // found an element at level theLevel return x;

// return desired element from right subtree return elementAtLevel(t.rightChild, theLevel - 1);}

(b) Each node of the binary tree is reached at most once and a constant amount of work is done during each visit. Therefore, the complexity is O(n), where n is the number of nodes in the binary tree.

26

Page 27: ds_algo

2. (a) 3. f4. / \5. / \6. c f7. / \ / \8. a c f h9. / \ / \ / \ / \10. 4 7 3 6 5 1 8 211. a b c d e f g h12.

(b) f | c / \ / \ a h / \ / \ b d e g / \ / \ / \ / \ 4 7 3 6 5 1 8 2 a b c d e f g h

13. (a) Following path halving, every other node on the original path from the find element e to the root points to its original grandparent.

(b) Examine the preorder output from left to right. In this order, the first element B is the root of the binary tree. Also B comes between the left and right subtree in inorder. So A is the inorder output of the left subtree and CDEFGHIJ is the inorder output of the right subtree. The next element in preorder A is the root of the left subtree unless the left subtree is empty (in which case it is the root of the right subtree). Using this information and what we have already learnt from the inorder sequence, we see that A is the root of the left subtree and the subtrees of A are empty. Proceeding in this way we can construct the entire binary tree. The unique binary tree from which the given inorder and preorder outputs came is:

B / \ / \ A H / \ C J \ / E I / \ D G

27

Page 28: ds_algo

/ F

(c) 70 / \ / \ / \ 60 61 / \ / \ / \ / \ 55 54 58 59 / \ / \ / 50 52 48 53 56 / / \ 40 20 45 / 30

Data Structures & Algorithms

Exam 2

Sample 3, 75 Minutes

Notes: 1. Write your name, social security number, and section in which you want your exam

returned on each sheet. 2. Begin the answer to each question on a new sheet.

1. [18] The classes MyBinaryTreeNode and MyBinaryTree are given below. Objects of type MyBinaryTree are linked binary trees.

public class MyBinaryTreeNode{ Object element; BinaryTreeNode leftChild; // left subtree BinaryTreeNode rightChild; // right subtree }

public class MyBinaryTree{ BinaryTreeNode root; // root node

28

Page 29: ds_algo

// code you write will come here}

You are to write a public method maxHeightDifference(). The invocation x.maxHeightDifference() returns 0 if the binary tree x is empty; otherwise, it returns the maximum difference in the heights of the left and right subtrees of any node in the tree.

x.maxHeightDifference() = maxy is a node of x {|height(left subtree of y)                                             - height(right subtree of y)|}

(a) [16] Write Java code for the public method maxHeightDifference. You may define, implement and create additional methods and variables as needed. You may use Java's methods Math.max and Math.abs. Math.max(a,b) returns the larger of a and b, and Math.abs(a) returns the absolute value of a. You may not create any new nodes, new instances of MyBinaryTree, or invoke any methods (other than Math.max and Math.abs) for which you have not provided code. (Hint: use recursion.)

(b) [2] What is the time complexity of your code as a function of the number of nodes in the binary tree?

2. (a) [4] A 10 element complete binary tree is represented by the array [20, 15, 12, 8, 10, 6, 2, 4, 7, 1]. Draw the complete binary tree. Is this complete binary tree a max heap? Why?

(b) [4] There are eight players named a through h in a tournament. Their values are [1, 7, 4, 3, 5, 8, 9, 2]. When two players play a match, the one with larger value wins. Draw the winner tree for the tournament. Label internal nodes with player names and external nodes with player values and names.

(c) [4] Draw the loser tree (including overall winner) for the tournament described in (b). Label internal nodes with player names and external nodes with player values and names.

29

Page 30: ds_algo

3. (a) [8] Suppose you have a binary tree whose data fields are single characters. When the data fields of the nodes are output in inorder, the output is ABCDEFGHIJ, and when they are output in level order, the output is BAIDJCFEHG. Draw the binary tree showing the data in each node and the pointers between nodes. Show the steps used to arrive at the result.

(b) [8] Draw the height biased max leftist tree that results when the max element is removed from the following height biased max leftist tree (use the strategy used in the text). Show the steps used to arrive at the result.

60 / \ / \ 55 48 / \ / \ 50 52 20 30 / 40

(c) [4] Consider the following binary search tree. Label each node with its balance factor. Is this tree an AVL search tree? Why?

30 / \ / \ 20 50 / \ / \ 10 25 40 60 / \ / / 5 15 35 55 / 54

Data Structures & Algorithms

Exam 2

Sample 3, 75 Minutes

Solutions

1. (a) We will use a static variable maxDifferenceSoFar to represent the maximum height difference detected so far. private static int maxDifferenceSoFar;

30

Page 31: ds_algo

Whenever we determine the height difference between the left and right subtrees of a new node, the absolute value of this difference is compared to maxDifferenceSoFar, and maxDifferenceSoFar updated if necessary. To implement a recursive strategy, we need to define a public and a private maxHeightDifference method. The public method is given below:public int maxHeightDifference(){ maxDifferenceSoFar = 0; // initialize static variable maxHeightDifference(root); // compute max height difference return maxDifferenceSoFar;}

The private method that does the actual computation of the maximum height difference is given below. This method also returns the height of the tree whose root is t.

private static int maxHeightDifference(MyBinaryTreeNode t){// return height of t and update maxDifferenceSoFar if (t == null) return 0; // height of empty tree

// compute heights of left and right subtrees int heightLeft = maxHeightDifference(t.leftChild); int heightRight = maxHeightDifference(t.rightChild);

// determine height difference and update masDifferenceSoFar int heightDifference = heightLeft - heightRight; maxDifferenceSoFar = Math.max(maxDifferenceSoFar, Math.abs(heightDifference)); // return height of subtree rooted at t return Math.max(heightLeft, heightRight) + 1;}

(b) Each node of the binary tree is reached once and a constant amount of work is done at each node. Therefore, the complexity is O(n), where n is the number of nodes in the binary tree.

2. (a) The complete binary tree is given below: 20 / \ / \ 15 12

31

Page 32: ds_algo

/ \ / \ 8 10 6 2 / \ / 4 7 1

This is a max heap because it is both a complete binary tree and a max tree. (b) The winner tree is: g / \ / \ b g / \ / \ b c f g / \ / \ / \ / \ 1 7 4 3 5 8 9 2 a b c d e f g h

(c) The loser tree is: g <--- overall winner | b / \ / \ c f / \ / \ a d e h / \ / \ / \ / \ 1 7 4 3 5 8 9 2 a b c d e f g h

3. (a) Examine the level order output from left to right. In this order, subtree roots are seen before subtree descendants. So, the first element in level order, B, is the root of the binary tree. Also B comes between the left and right subtrees in inorder. So the inorder output of the left subtree is A and CDEFGHIJ is the inorder output of the right subtree. The next element in level order A is the root of whichever subtree it is in. Using this information and what we have already learnt from the inorder sequence, we see that A is the root of the left subtree. Proceeding in this way we can construct the entire binary tree. The unique binary tree from which the given inorder and level order outputs came is: B / \ / \ A I / \ D J / \ C F / \ E H

32

Page 33: ds_algo

/ G

(b) When the max element is removed, we get the following 2 max leftist trees:

55 48 / \ / \ 50 52 20 30 / 40

These trees are melded by following rightmost paths. First, the right subtree of 55 is melded with the tree whose root is 48. The result is: 52 / 48 / \ 20 32

This new tree becomes the right subtree of 55. The subtrees of 55 are not swapped, as the tree already satisfies the leftist tree properties. 55 / \ 50 52 / / 40 48 / \ 20 32

(c) Balance factors are shown in place of key values. -1 / \ / \ 1 -1 / \ / \ 0 0 1 2 / \ / / 0 0 0 1 / 0

The given binary search tree is not an AVL search tree because it has a node whose balance factor is 2.

33