In the first question, you will write determine the worst-case running time (“big-O time complexity”) of common Java API method calls and/or of a short method we provide. For example, a question might ask for the running time of:
ArrayList.get()
: constant timeHashSet.contains()
: constant timeLinkedList.indexOf()
: linear in the length of the list
or code such as
int sum(int[] a) {
int s = 0;
for (int i : a) {
s += i;
}
return s;
}
(linear in a.length
)
In the second and third questions, you will write a short method that manipulates maps, sets, or lists. For example, a question might state:
Write a method static void removeFromMultiMap(Map<Integer, List<String>> map, Integer key, String value)
. removeFromMultiMap
must remove the value
, if present, from the list, if present, associated with the given key
. If either is not present it should return without raising an exception. You may assume all keys in the map are associated with non-null values.
For full credit, your method must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume Map
, List
, HashMap
, and ArrayList
are correctly imported from java.util
. You may not import other classes.
static void removeFromMultiMap(Map<Integer, List<String>> map, Integer key, String value) {
if (map.containsKey(key)) {
map.get(key).remove(value);
}
}
Another question might state:
Write a method static List<Integer> expand(List<Integer> list)
. For a given list of integers, expand
should return a list of those integers, such that each integer i appears i consecutive times in the list. You may assume all integers in the list are non-negative.
For example, if list = [1, 4, 2]
, then expand
should return the list [1, 4, 4, 4, 4, 2, 2]
.
expand
must not modify the list. For full credit, your method must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may use List
, and ArrayList
, but no
other classes from the java.util
namespace.
public static List<Integer> expand(List<Integer> list) {
List<Integer> l = new ArrayList<>();
for (int i: list) {
for (int j = 0; j < i; j++) {
l.add(i);
}
}
return l;
}
In the last question, you will demonstrate your understanding of the behavior of the breadth-first search algorithm, similar to that in Problem Set 09 (reproduced here):
Suppose you have the following directed graph.
If you were to perform a breadth-first search to completely explore this graph, starting from S, in what order would the vertices be added to the frontier? Use the same BFS algorithm we covered in lecture and in programming assignment 10. Assume that the neighbors of each vertex are returned in alphabetical order. Do not stop the search if it finds a G node; completely explore the graph.
S, A, B, C, D, E, G2, G1