Operations on Data Structures - Computer Science

Card 0 of 15

Question

Which of the following defines a method that successfully deletes an item from an array of integers?

Answer

Of course, this is an inefficient way to do such a delete, but arrays are rather "locked" data structures in that their size cannot change without a reassignment. (You could, of course keep track of the last "used" index. However, that is a different implementation, not reflected here.) The correct answer is the one that carefully goes through the original array, copying those contents into the new array skipping the one value that is not wanted.

Compare your answer with the correct one above

Question

public static boolean remove(int\[\] arr, int val) {

boolean found = false;

int i;

for(i = 0; i < arr.length && !found; i++) {

if(arr\[i\] == val) {

found = true;

}

}

if(found) {

for(int j = i; j < arr.length;j++) {

arr\[j - 1\] = arr\[j\];

}

arr\[arr.length - 1\] = 0;

}

return found;

}

For the code above, what will be the content of the variable arr at the end of execution, if the method is called with the following values for its parameters:

arr = {3,4,4,5,17,4,3,1}

val = 4

Answer

This code simulates the removal of a value from an array by shifting all of the elements after that one so that the array no longer contains the first instance of that value. So, for instance, this code takes the original array {3,4,4,5,17,4,3,1} and notices the first instance of 4: {3,**4**,4,5,17,4,3,1}. Next, it starts shifting things to the left. Thus, some of the steps will look like this:

{3,4,4,5,17,4,3,1}

{3,4,5,5,17,4,3,1}

{3,4,5,17,17,4,3,1}

...

{3,4,5,5,17,4,1,1}

Then, at the very end, it sets the last element to 0:

{3,4,5,17,4,3,1,0}

Compare your answer with the correct one above

Question

int\[\] arr = new int\[20\];

int x = 6,i=2;

for(int j = 0; j < x; j++) {

arr\[j\] = j * 40 + 20;

}

for(int j = x; j > i; j--) {

arr\[j\] = arr\[j - 1\];

}

arr\[i\] = 20;

for(int j = 0; j < x; j++) {

System.out.print(arr\[j\] + " ");

}

What is the output for the code above?

Answer

It is easiest to understand this by a bit of code parsing:

First, there is the loop: for(int j = 0; j < x; j++) { // ...

This will fill the array with 20 + 0, 20 + 40, 20 + 80, ... Thus, it will be:

20, 60, 100, 140, 180, 220

Next, there is the array: for(int j = x; j > i; j--) { // ...

This basically shifts everything after index i backward by 1. Thus you have:

20, 60, 100,100, 140, 180, 220

Next, you set arr\[2\] equal to 20:

20, 60, 20,100, 140, 180, 220

Finally you output each of the first 6 elements. Be careful here. Notice that it is from j = 0 to x - 1!

Thus, the answer is:

20 60 20 100 140 180

This algorithm basically implements a simple kind of array deletion.

Compare your answer with the correct one above

Question

public static int[] doWork(int[] arr, int val,int index) {

int[] ret = new int[arr.length + 1];

for(int i = 0; i < index; i++) {

ret[i] = arr[i];

}

ret[index] = val;

for(int i = index + 1; i < ret.length; i++) {

ret[i] = arr[i - 1];

}

return ret;

}

What does the code above perform?

Answer

A quesiton like this is most easily understood by doing a careful reading of the code in question. Let's consider each major section of code:

int[] ret = new int[arr.length + 1];

This line of code creates a new array, one that is 1 longer than the array arr.

for(int i = 0; i < index; i++) . . .

This loop copies into ret the values of arr up to index - 1.

(This is because of the i < index condition)

Then, the code stores the value val in ret[index]

_for(int i = index + 1; i < ret.length; i++) . . ._

It then finishes copying the values into ret.

Thus, what this does is insert a value into the original array arr, returning the new array that is one size larger. (This is necessary because of the static sizing of arrays in Java.)

Compare your answer with the correct one above

Question

public static int[] doWork(int[] arr, int val,int index) {

int[] ret = new int[arr.length + 1];

for(int i = 0; i < index; i++) {

ret[i] = arr[i];

}

ret[index] = val;

for(int i = index + 1; i < ret.length; i++) {

ret[i] = arr[i - 1];

}

return ret;

}

Which of the following is a possible error in the first loop in code above?

I. The array arr might be indexed out of bounds.

II. The array ret might be indexed out of bounds.

III. A null pointer exception might occur.

Answer

The most obvious possible error is that the array arr might be a null value. You need to check for these kinds of values before using the variables. (If you do arr[0] on a null value, an exception will be thrown.) In addition, it is possible that a value for index might be given that is too large. Consider if index = 100 but arr is only 4 elements long. Then, you will have ret be a 5 value array. When the first loop starts to run, you will go all the way to 99 (or at least attempt to do so) for the index value i_; h_owever, once you get to ret[4] = arr[4], there will be an out of bounds error on arr, which only has indices 0, 1, 2, and 3. Of course, there could be other problems later on with ret, but the question only asks about this first loop.

Compare your answer with the correct one above

Question

int\[\] arr = {0,0,0,0,0,0,0,0,0,0};

int arrFill = 0;

int val;

// In here, n items are added. ArrFill is n. Presume that n <= 9

// The variable val now contains a new value to be added

Which of the following blocks of code push a new value into arr as though it were a stack?

Answer

Let us presume that the array arr looks like the following list of integers:

{4,51,41,0,0,0,0,0,0,0}

Presume that our new value is 77.

A stack could either push on to the beginning and move everything back one, giving you something like:

{77,4,51,41,0,0,0,0,0,0}

However, none of the options do this. (No, not even the one that uses the index 0. This one does not add on to the array so much as replace the first element of it.)

So, the other option is to put it on the "end" of the list. The variable arrFill is being used for this purpose. If it is 3, this means that it is the value of the fourth element. Thus, you can set arr\[4\] = 77 (where 4 really is arrFill).

This will give you:

{4,51,41,77,0,0,0,0,0,0}

You also need to add one to the value of arrFill.

The other options do not correctly address the array. They either are too large or too small by one.

Compare your answer with the correct one above

Question

True or False.

The worst case for insertion into an ArrayList is O(N).

Answer

Insertion into an ArrayList is typically O(1). However, since an ArrayList uses an array as its underlying data structure, there can be a need to resize the underlying array. Resizing an array requires creating a new array and copying all the data from the old array to the new array which takes O(N) time.

Compare your answer with the correct one above

Question

Consider the code below:

public static class BTNode {

public static final int PARSE_IN = 1;

public static final int PARSE_PRE = 2;

public static final int PARSE_POST = 3;

String name;

BTNode lPointer,rPointer;

public BTNode(String s) {

name = s;

lPointer = rPointer = null;

}

public void insert(String s) {

insert(this,s);

}

private static void insert(BTNode node,String s) {

int comparison = s.compareTo(node.name);

if(comparison < 0) {

if(node.lPointer != null) {

insert(node.lPointer,s);

} else {

node.lPointer = new BTNode(s);

}

} else if(comparison > 0) {

if(node.rPointer != null) {

insert(node.rPointer,s);

} else {

node.rPointer = new BTNode(s);

}

}

}

public ArrayList parse(final int parseOrder) {

return parse(this,parseOrder);

}

private static ArrayList parse(BTNode node, final int parseOrder) {

ArrayList retVal = new ArrayList();

if(node == null) {

return(retVal);

}

ArrayList leftList = parse(node.lPointer,parseOrder);

ArrayList rightList = parse(node.rPointer,parseOrder);

if(parseOrder == PARSE_PRE) {

retVal.add(node.name);

retVal.addAll(leftList);

retVal.addAll(rightList);

} else if (parseOrder == PARSE_POST) {

retVal.addAll(leftList);

retVal.addAll(rightList);

retVal.add(node.name);

} else {

retVal.addAll(leftList);

retVal.add(node.name);

retVal.addAll(rightList);

}

return retVal;

}

}

public static void main(String\[\] args) {

String\[\] names = {"Hervaeus","Peter Auriol","Guiral","Felix","Lila","Lola","Yippy","Yiiiipppy","Acton","Pierce","Betty"};

BTNode node = new BTNode(names\[0\]);

for(int i = 1; i < names.length; i++) {

node.insert(names\[i\]);

}

ArrayList traversedNames = node.parse(BTNode.PARSE_IN);

for(String s : traversedNames) {

System.out.println(s);

}

}

What is the output for this method?

Answer

The code given is a standard implementation of a binary tree containing an insert and a parse method. For now, you can merely pay attention to your parse logic, particularly just the logic that will be invoked for the indicator value PARSE_IN. (Notice that this is merely in the else of the parse method. This is a "catch all" / default in case a bad value is given for the parse order.)

retVal.addAll(leftList);

retVal.add(node.name);

retVal.addAll(rightList);

This is just the standard binary tree style of parsing based on our insert. The smaller items are on the left of the current node, and the larger ones are on the right of it. Thus, you have:

List of all smaller values + This current value + List of all larger values

Recursively, this will end with an ordered list, which is just what you need.

Compare your answer with the correct one above

Question

Consider the following code:

import java.util.ArrayList;

public class MethodClass5 {

public static class BTNode {

public static final int PARSE_IN = 1;

public static final int PARSE_PRE = 2;

public static final int PARSE_POST = 3;

String name;

BTNode lPointer,rPointer;

public BTNode(String s) {

name = s;

lPointer = rPointer = null;

}

public void insert(String s) {

insert(this,s);

}

private static void insert(BTNode node,String s) {

int comparison = s.compareTo(node.name);

if(comparison < 0) {

if(node.lPointer != null) {

insert(node.lPointer,s);

} else {

node.lPointer = new BTNode(s);

}

} else if(comparison > 0) {

if(node.rPointer != null) {

insert(node.rPointer,s);

} else {

node.rPointer = new BTNode(s);

}

}

}

public ArrayList parse(final int parseOrder) {

return parse(this,parseOrder);

}

private static ArrayList parse(BTNode node, final int parseOrder) {

ArrayList retVal = new ArrayList();

if(node == null) {

return(retVal);

}

ArrayList leftList = parse(node.lPointer,parseOrder);

ArrayList rightList = parse(node.rPointer,parseOrder);

if(parseOrder == PARSE_PRE) {

retVal.add(node.name);

retVal.addAll(leftList);

retVal.addAll(rightList);

} else if (parseOrder == PARSE_POST) {

retVal.addAll(leftList);

retVal.addAll(rightList);

retVal.add(node.name);

} else {

retVal.addAll(leftList);

retVal.add(node.name);

retVal.addAll(rightList);

}

return retVal;

}

}

public static void main(String\[\] args) {

String\[\] names = {"Thomas Aquinas","Thomas Cajetan","Thomas Prufer","Thomas the Tank Engine","Thomas the Bread-Eater"};

BTNode node = new BTNode(names\[0\]);

for(int i = 1; i < names.length; i++) {

node.insert(names\[i\]);

}

ArrayList traversedNames = node.parse(BTNode.PARSE_POST);

for(String s : traversedNames) {

System.out.println(s);

}

}

}

What is the output for the_main_ method above?

Answer

This code is a standard implementation of a Binary Tree class. The call that we are making in main is meant to parse the tree (traverse it) in post-fix order. This means that we will always look to the left of each node first, then to the right, then finally to the value we are at. However, the tree is unbalanced, so the parsing will do much more right traveral than anything else. See the following sequence of inserts:

Step 1:

Tree11

Step 2:

Tree12

Step 3:

Tree13

Step 4:

Tree14

Step 5:

Tree15

Now, your traversal path will look like this:

Tree16

Interestingly, this means that you will end up with a list that is in reverse order. This is only the case for the given data as it happened to have been inserted.

Compare your answer with the correct one above

Question

The function recur is defined as follows:

public int recur(int x)

{

if (x <= 1)

{

return 1;

}

else

{

return x + recur(x/2);

}

}

How many times is recur called in the following declaration?

int num = recur(6);

Answer

The first call is in the declaration. Because 6 > 1, it calls recur, which makes the total 2.

Next, it calls recur(6/2). Because 3 > 1, it calls recur again, which makes the total 3.

Next, it calls recur(3/2). Because it's dividing integers, this evaluates to recur(1).

Because 1 <= 1, it doesn't call recur anymore, so that total number of calls is 3.

Compare your answer with the correct one above

Question

TREE TRAVERSALS

Given the following tree structure:

Blank flowchart   new page

What is the pre-order traversal of the tree?

Answer

When a preorder traversal is done, you go through the following:

1. ROOT

2. LEFT CHILD

3. RIGHT CHILD

Therefore, starting at the root (1), we go to the LEFT node (2). That node however, is the root/parent of other nodes, so we go left again (4). That node is a parent/root, so we go left (5). Now it's time to go to the right; however, only node 1 has a right child, so going to the right of one we land at (3). That node is the parent/root of more children so we go left (6). Node 6 doesn't have any left children, but it does have a right so we go right (8). Node 8 has a left child to traverse (9) and then a right (5). And we finish the traversal by going to the right of three (7). This is a rather complicated example; however, make sure you can traverse the tree properly.

Blank flowchart   new page  1

In the above image, you can see the approach of the pre-order traversal. First you go through the roots, then the left trees, then the right trees. Make sure that if you're guiding yourself by the image above, that you don't repeat the nodes that you already traversed. Understanding the algorithm is key.

Compare your answer with the correct one above

Question

Which of the following code performs a multiplication by 5 of the elements of the array defined as:

int\[\]\[\] vals = new int\[50\]\[100\];

Presume that the array has been properly initialized and filled with values.

Answer

What we are looking for in this problem is a standard traversal of a 2D array. When you do this, you need to make sure that you iterate through both the rows and the columns. In order to do this, you first must set up a loop like:

for(int i = 0; i < vals.length;i++) {...

The value of vals.length indicates the number of rows in the 2D array.

Now, for each row, you have a certain number of columns. (A 2D array is like an "array of arrays".) Thus, for each row, you need to run through the entire set of columns for that row:

for(int j = 0; j < vals\[i\].length; j++) { ...

Notice that none of the incorrect questions use vals\[i\].length in this way. Thus, none of them iterate through the two dimensions of the array correctly.

Compare your answer with the correct one above

Question

Traverse and print out this list

List integers = new ArrayList();

integers.add(1);

integers.add(2);

integers.add(3);

Answer

Use a for loop to traverse the list. The .size() method is used for Lists as opposed to the .length method for arrays. The .get() method is used for Lists as opposed to accessing the index for arrays.

Compare your answer with the correct one above

Question

What's the best way to traverse this list in Swift (iOS)?

var list: \[Int\] = \[0, 1, 2, 3, 4, 5\]

Answer

The correct answer is the best way because it uses Swift's built in "in" operator. In this case, "in" will convert the thing that comes after "in" (so in this case, list) into a range operator. Essentially it will say "i in range(list.count)." This is why the other answer choice that uses "in" is incorrect in terms of the "best" way to traverse a list of integers in Swift.

Compare your answer with the correct one above

Question

Suppose you are given an array of integers:

int array\[\] = {1,2,3,4,5};

and the following method:

public static void printArray(int\[\] arr)

{

for (int a = 0; r < arr.length-1; a++)

{

if (a%2==0)

{

System.out.println(arr\[a\]);

}

}

}

After the method cacll printArray(array) is called, the output would be:

Answer

The correct answer is:

1

3

The important line here is the if statement, which only executes if (a%2==0) is true, or if the loop counter divided by 2 is 0. A possible error is to divide each element of the array by 2 instead of the loop counter. So the println statement will only execute if the loop counter is even, which happens on the 1st itteration (a=0) and the 3rd itteration (a=2). The for loop ends at arr.length-1, which means that a takes on a maximum value of 3, and not 4 (choosing the option 1 3 5 would mean you did not notice the bounds on the for loop). Finally, println prints a new line every time, so, it is not possible for all the integers to be on one line, as println is executed twice.

Compare your answer with the correct one above

Tap the card to reveal the answer