Quiz 05 sample questions and answers


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 time
  • HashSet.contains(): constant time
  • LinkedList.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 the length of the array)

where answers are either of the form “constant time” or of the form “X in Y” where X is the degree of the polynomial (for example, “linear”) and Y is the variable in question (for exampl,e “the length of the list”).


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;
    }