{"exams":[{"id":"61b-fa20-final","t":"Fall 2020 Final","src":{"exam":"https://drive.google.com/file/d/1A1YPTJAsiVOQtIUiQgPFL6rM2T9oXntW/view","sol":"https://drive.google.com/file/d/1nRrI0buwfZ-c9eAzVzKP3_MSfM0Nh5Fw/view","topics":"fa20-final"},"p":[{"id":"61b-fa20-final/2","n":"2","t":"2. Basic Sorts (180 pts)","b":[{"s":[{"p":"Initial array is [4, 5, 1, 2, 3, 7]. Identify the first swap made by each algorithm, or select no swaps."}]},{"id":1,"l":[{"p":"Selection sort"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":2,"l":[{"p":"Insertion sort"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":5,"topics":["SORTING"],"topicsBy":"site"},{"id":3,"l":[{"p":"Quicksort-LTH with Hoare partition, no shuffle"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":7,"topics":["SORTING"],"topicsBy":"site"},{"id":4,"l":[{"p":"Merge sort"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":15,"topics":["SORTING"],"topicsBy":"site"},{"id":5,"l":[{"p":"In-place heapsort"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":11,"topics":["SORTING"],"topicsBy":"site"},{"id":6,"l":[{"p":"Counting sort"}],"k":"mc","o":["4-5","4-1","4-2","4-3","4-7","5-1","5-2","5-3","5-7","1-2","1-3","1-7","2-3","2-7","3-7","No swaps"],"a":15,"topics":["SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/3","n":"3","t":"3. New Traversals (220 pts)","b":[{"s":[{"p":"Undirected graph edges: 1–2, 2–5, 2–4, 4–3. DFS visits smaller neighbors first."}]},{"id":10,"l":[{"p":"DFS preorder from node 4"}],"k":"blank","a":["4, 2, 1, 5, 3"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":11,"l":[{"p":"DFS postorder from node 2"}],"k":"blank","a":["1, 3, 4, 5, 2"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"s":[{"p":"For a binary tree, pre/in traversal is: print node; recurse left; print node again; recurse right. Use this tree: root 1, left child 2; node 2 has left child 5 and right child 4; node 4 has left child 3."}]},{"id":12,"l":[{"p":"Pre/in traversal from root 1"}],"k":"blank","a":["1, 2, 5, 5, 2, 4, 3, 3, 4, 1"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"s":[{"p":"Given pre/in traversal 9,3,3,6,5,1,1,5,6,9, answer:"}]},{"id":13,"l":[{"p":"Number of nodes"}],"k":"blank","a":["5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":14,"l":[{"p":"Height"}],"k":"blank","a":["4"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":15,"l":[{"p":"Left child of 6"}],"k":"blank","a":["5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":16,"l":[{"p":"Parent of 1"}],"k":"blank","a":["5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":17,"l":[{"p":"Level order traversal"}],"k":"blank","a":["9, 3, 6, 5, 1"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":18,"l":[{"p":"Number of distinct binary trees with pre/in traversal 2,2,2,2,2,2,3,3"}],"k":"blank","a":["5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/4","n":"4","t":"4. Java Syntax and Data Structure Usage (220 pts)","b":[{"s":[{"p":"PrimeFactorIterator returns the prime factors of positive integer x in increasing order, with repeated factors included."},{"c":"class PrimeFactorIterator implements ⟪a⟫, ⟪b⟫ {\n  private int x;\n  PrimeFactorIterator(int givenX) { ⟪c⟫ }\n  public boolean hasNext() { return ⟪d⟫; }\n  public int next() {\n    int i=2;\n    while (⟪e⟫) { ⟪f⟫ }\n    x = ⟪g⟫;\n    return i;\n  }\n  public Iterator<Integer> iterator() { return ⟪h⟫; }\n}","lang":"java"}]},{"id":20,"l":[{"p":"Iterator interface"}],"k":"blank","a":["Iterator<Integer>"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":21,"l":[{"p":"Iterable interface"}],"k":"blank","a":["Iterable<Integer>"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":22,"l":[{"p":"Store input"}],"k":"blank","a":["this.x = givenX"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":23,"l":[{"p":"Has next factor"}],"k":"blank","a":["x >= 2"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":24,"l":[{"p":"Find smallest divisor"}],"k":"blank","a":["x % i != 0"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":25,"l":[{"p":"Try next divisor"}],"k":"blank","a":["i = i + 1"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":26,"l":[{"p":"Remove factor from x"}],"k":"blank","a":["x / i"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":27,"l":[{"p":"Iterable returns itself"}],"k":"blank","a":["this"],"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"s":[{"c":"private int uniquePrimeFactorCount(int x) {\n  HashSet<Integer> set = ⟪i⟫;\n  for (int factor : new PrimeFactorIterator(x)) { ⟪j⟫ }\n  return ⟪k⟫;\n}","lang":"java"}]},{"id":28,"l":[{"p":"Create set"}],"k":"blank","a":["new HashSet<Integer>()"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":29,"l":[{"p":"Remember factor"}],"k":"blank","a":["set.add(factor);"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":30,"l":[{"p":"Return unique count"}],"k":"blank","a":["set.size()"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"s":[{"p":"Keep the k values in [1,n] with the largest uniquePrimeFactorCount. Use O(k) memory and O(n log k) time. MinPQ uses the supplied comparator and removeSmallest()."},{"c":"Comparator<Integer> c = ⟪m⟫;\nMinPQ<Integer> pq = new MinPQ<>(⟪n⟫);\nfor (int i=1; i<=n; i++) {\n  ⟪o⟫\n  ⟪p⟫\n}\nfor (int i : pq) ⟪q⟫;","lang":"java"}]},{"id":31,"l":[{"p":"Comparator construction"}],"k":"blank","a":["new UniqueFactorCountComparator()"],"topics":["COMPARATORS","HEAPS"],"topicsBy":"site"},{"id":32,"l":[{"p":"Priority queue comparator argument"}],"k":"blank","a":["c"],"topics":["COMPARATORS","HEAPS"],"topicsBy":"site"},{"id":33,"l":[{"p":"Add candidate"}],"k":"blank","a":["pq.add(i);"],"topics":["COMPARATORS","HEAPS"],"topicsBy":"site"},{"id":34,"l":[{"p":"Trim to k values"}],"k":"blank","a":["if (pq.size() > k) pq.removeSmallest();"],"topics":["COMPARATORS","HEAPS"],"topicsBy":"site"},{"id":35,"l":[{"p":"Print retained values"}],"k":"blank","a":["System.out.println(i)"],"topics":["COMPARATORS","HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/5","n":"5","t":"5. Sorting Variations (150 pts)","b":[{"s":[{"p":"All strings are unique and constant length. P1sort: partition around leftmost pivot; selection-sort the left partition; quicksort the right partition (P1sort itself is not recursive)."}]},{"id":40,"l":[{"p":"P1sort best-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":3,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":41,"l":[{"p":"P1sort worst-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":4,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"P2sort splits in half, heapsorts the left half, randomly chooses Selection/Merge/Quick/LSD/P2sort for the right half, then merges."}]},{"id":42,"l":[{"p":"P2sort best-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":3,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":43,"l":[{"p":"P2sort worst-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":4,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"P3sort splits in half, independently chooses Selection/Merge/Quick/LSD/P3sort for each half, then merges."}]},{"id":44,"l":[{"p":"P3sort best-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":2,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":45,"l":[{"p":"P3sort worst-case runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":4,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":46,"l":[{"p":"P3sort runtime when it chooses itself at every recursive choice"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)","Worse than Θ(N⁴)","Never terminates"],"a":3,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/6","n":"6","t":"6. Minimum Spanning Trees (150 pts)","b":[{"s":[{"p":"Undirected weighted graph: DP=8, DA=4, DN=3, NA=5, AV=6, JV=7, AP=9, AI=1, IR=2. Run Prim from P; break ties alphabetically."}]},{"id":50,"l":[{"p":"Prim node visitation order"}],"k":"blank","a":["P, D, N, A, I, R, V, J"],"topics":["MSTS"],"topicsBy":"site"},{"id":51,"l":[{"p":"Which edges are in the MST?"}],"k":"sata","o":["AV","IR","AI","AN","JV","DN","DP","AD","AP"],"a":[0,1,2,4,5,6],"topics":["MSTS"],"topicsBy":"site"},{"s":[{"p":"For each edge independently, replace only its weight with a value that creates multiple MSTs. Give None if impossible."}]},{"id":52,"l":[{"p":"Replacement weight for AD"}],"k":"blank","a":["5"],"topics":["MSTS"],"topicsBy":"site"},{"id":53,"l":[{"p":"Replacement weight for AP"}],"k":"blank","a":["8"],"topics":["MSTS"],"topicsBy":"site"},{"id":54,"l":[{"p":"Replacement weight for DN"}],"k":"blank","a":["5"],"topics":["MSTS"],"topicsBy":"site"},{"id":55,"l":[{"p":"Replacement weight for AI"}],"k":"blank","a":["None"],"topics":["MSTS"],"topicsBy":"site"},{"id":56,"l":[{"p":"Replacement weight for AV"}],"k":"blank","a":["None"],"topics":["MSTS"],"topicsBy":"site"},{"id":57,"l":[{"p":"Replacement weight for IR"}],"k":"blank","a":["None"],"topics":["MSTS"],"topicsBy":"site"},{"id":58,"l":[{"p":"Replacement weight for AN"}],"k":"blank","a":["4"],"topics":["MSTS"],"topicsBy":"site"},{"id":59,"l":[{"p":"Replacement weight for DP"}],"k":"blank","a":["9"],"topics":["MSTS"],"topicsBy":"site"},{"id":60,"l":[{"p":"Replacement weight for JV"}],"k":"blank","a":["None"],"topics":["MSTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/7","n":"7","t":"7. Hashing Bears (80 pts)","b":[{"s":[{"p":"HashMap bucket array has length 4 and never resizes. Bear.equals compares names; hashCode is name.length(). Start with a=\"sohum\", b=\"arjun\". Operations: put(a,1); put(b,2); double a.name; put(a,3); put(b,4); double b.name; put(b,5). Buckets are indexed by hashCode mod 4."}]},{"id":70,"l":[{"p":"map.size()"}],"k":"blank","a":["4"],"topics":["HASHING"],"topicsBy":"site"},{"id":71,"l":[{"p":"get(new Bear(\"sohum\"))"}],"k":"blank","a":["null"],"topics":["HASHING"],"topicsBy":"site"},{"id":72,"l":[{"p":"get(new Bear(\"sohumsohum\"))"}],"k":"blank","a":["3"],"topics":["HASHING"],"topicsBy":"site"},{"id":73,"l":[{"p":"Bucket 1 list length"}],"k":"blank","a":["2"],"topics":["HASHING"],"topicsBy":"site"},{"id":74,"l":[{"p":"Bucket 1 values in order"}],"k":"blank","a":["1, 4"],"topics":["HASHING"],"topicsBy":"site"},{"id":75,"l":[{"p":"Bucket 2 list length"}],"k":"blank","a":["2"],"topics":["HASHING"],"topicsBy":"site"},{"id":76,"l":[{"p":"Bucket 2 values in order"}],"k":"blank","a":["3, 5"],"topics":["HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/8","n":"8","t":"8. BST Rotations (160 pts)","b":[{"s":[{"p":"BST structure: root 5; 5.left=3, 5.right=11; 3.left=2, 3.right=4; 2.left=1; 11.left=9, 11.right=12; 9.left=7, 9.right=10; 7.left=6, 7.right=8. A left rotation at node p5 promotes its right child."}]},{"id":80,"l":[{"p":"Root after rotateLeft(5)"}],"k":"blank","a":["11"],"topics":["BSTS"],"topicsBy":"site"},{"id":81,"l":[{"p":"3 parent"}],"k":"blank","a":["5"],"topics":["BSTS"],"topicsBy":"site"},{"id":82,"l":[{"p":"5 parent"}],"k":"blank","a":["11"],"topics":["BSTS"],"topicsBy":"site"},{"id":83,"l":[{"p":"9 parent"}],"k":"blank","a":["5"],"topics":["BSTS"],"topicsBy":"site"},{"id":84,"l":[{"p":"11 parent"}],"k":"blank","a":["-1"],"topics":["BSTS"],"topicsBy":"site"},{"id":85,"l":[{"p":"12 parent"}],"k":"blank","a":["11"],"topics":["BSTS"],"topicsBy":"site"},{"s":[{"p":"Rotate the same tree so that node 10 becomes the root, using three rotations."}]},{"id":86,"l":[{"p":"First rotation type"}],"k":"blank","a":["rotateLeft"],"topics":["BSTS"],"topicsBy":"site"},{"id":87,"l":[{"p":"First rotated node"}],"k":"blank","a":["9"],"topics":["BSTS"],"topicsBy":"site"},{"id":88,"l":[{"p":"Second rotation type"}],"k":"blank","a":["rotateRight"],"topics":["BSTS"],"topicsBy":"site"},{"id":89,"l":[{"p":"Second rotated node"}],"k":"blank","a":["11"],"topics":["BSTS"],"topicsBy":"site"},{"id":90,"l":[{"p":"Third rotation type"}],"k":"blank","a":["rotateLeft"],"topics":["BSTS"],"topicsBy":"site"},{"id":91,"l":[{"p":"Third rotated node"}],"k":"blank","a":["5"],"topics":["BSTS"],"topicsBy":"site"},{"s":[{"c":"public void rotateUp(int value) { ⟪a⟫ }\npublic void rotateUpHelper(int value, BSTNode curr) {\n  if (⟪b⟫) { ⟪c⟫ }\n  if (⟪d⟫) {\n    ⟪e⟫\n    ⟪f⟫\n  } else {\n    ⟪g⟫\n    ⟪h⟫\n  }\n}","lang":"java"}]},{"id":92,"l":[{"p":"Start helper at root"}],"k":"blank","a":["rotateUpHelper(value, root);"],"topics":["BSTS"],"topicsBy":"site"},{"id":93,"l":[{"p":"Target found"}],"k":"blank","a":["curr.value == value"],"topics":["BSTS"],"topicsBy":"site"},{"id":94,"l":[{"p":"Stop recursion"}],"k":"blank","a":["return;"],"topics":["BSTS"],"topicsBy":"site"},{"id":95,"l":[{"p":"Target in left subtree"}],"k":"blank","a":["value < curr.value"],"topics":["BSTS"],"topicsBy":"site"},{"id":96,"l":[{"p":"Recurse left"}],"k":"blank","a":["rotateUpHelper(value, curr.left);"],"topics":["BSTS"],"topicsBy":"site"},{"id":97,"l":[{"p":"Rotate right"}],"k":"blank","a":["rotateRight(curr);"],"topics":["BSTS"],"topicsBy":"site"},{"id":98,"l":[{"p":"Recurse right"}],"k":"blank","a":["rotateUpHelper(value, curr.right);"],"topics":["BSTS"],"topicsBy":"site"},{"id":99,"l":[{"p":"Rotate left"}],"k":"blank","a":["rotateLeft(curr);"],"topics":["BSTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/9","n":"9","t":"9. Shortest Paths (220 pts)","b":[{"s":[{"p":"Undirected weighted graph edges: AB=5, AC=3, BC=4, BD=2, BE=4, BF=10, CD=1, DG=4, EF=1, FG=1. Break ties alphabetically."}]},{"id":110,"l":[{"p":"BFS first four visits from G"}],"k":"blank","a":["G, D, F, B"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":111,"l":[{"p":"distTo(B)"}],"k":"blank","a":["5"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":112,"l":[{"p":"distTo(C)"}],"k":"blank","a":["3"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":113,"l":[{"p":"distTo(D)"}],"k":"blank","a":["4"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":114,"l":[{"p":"distTo(E)"}],"k":"blank","a":["9"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":115,"l":[{"p":"distTo(F)"}],"k":"blank","a":["9"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":116,"l":[{"p":"distTo(G)"}],"k":"blank","a":["8"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":117,"l":[{"p":"Dijkstra visitation order from A"}],"k":"blank","a":["A, C, D, B, G, E, F"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":118,"l":[{"p":"Edges in Dijkstra shortest-path tree from A"}],"k":"sata","o":["AC","AB","BC","BD","BE","BF","CD","DG","EF","FG"],"a":[0,1,4,6,7,9],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":119,"l":[{"p":"Minimum integer k to subtract from one edge so Dijkstra returns an incorrect A-to-G shortest path"}],"k":"mc","o":["2","3","4","5"],"a":2,"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":120,"l":[{"p":"Which edge changed by that minimum k makes Dijkstra fail?"}],"k":"mc","o":["AC","AB","BC","BD","BF","CD","DG","EF","FG"],"a":3,"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"s":[{"p":"Run A* from A to G with h(v) equal to shortest-path distance from v to E (h(E)=0, h(F)=1, h(G)=2, h(B)=4)."}]},{"id":121,"l":[{"p":"Priority assigned to C when added to fringe"}],"k":"blank","a":["10"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":122,"l":[{"p":"A* visit order"}],"k":"blank","a":["A, B, E, C, D, G"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":123,"l":[{"p":"Does A* compute the correct shortest A-to-G distance for this graph and heuristic?"}],"k":"mc","o":["Yes","Depends on priority queue tie-breaking","No"],"a":0,"topics":["SHORTEST_PATHS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa20-final/10","n":"10","t":"10. Optimal Peak (210 pts)","b":[{"s":[{"p":"Undirected positive-weight trail graph: AD=7, AB=2, AS=6, SB=5, SG=1, GB=2, BD=8, BC=7, GE=4, GF=7, EF=3, EC=5. A valid goal has two equally short paths from start to goal that enter and leave the goal on different edges; maximize total round-trip distance."},{"p":"For each start, give the optimal goal and the set of trails used in the round trip (list each trail once)."}]},{"id":130,"l":[{"p":"Trails traversed for start C"}],"k":"sata","o":["AB","AD","AS","BC","BD","BG","BS","CE","EF","EG","FG","GS","None"],"a":[3,5,7,9],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":131,"l":[{"p":"Optimal peak for start C"}],"k":"mc","o":["A","B","C","D","E","F","G","S","None"],"a":6,"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":132,"l":[{"p":"Trails traversed for start A"}],"k":"sata","o":["AB","AD","AS","BC","BD","BG","BS","CE","EF","EG","FG","GS","None"],"a":[0,5,8,9,10],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":133,"l":[{"p":"Optimal peak for start A"}],"k":"mc","o":["A","B","C","D","E","F","G","S","None"],"a":5,"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"s":[{"p":"Describe the steps of an O(E log V) algorithm for finding the optimalPeak. The trip must be equal-length in both directions, each direction must be shortest, and the first and last trails at the goal must differ."}]},{"id":134,"l":[{"p":"Run shortest paths from start"}],"k":"blank","a":["Dijkstra"],"topics":["SHORTEST_PATHS","MSTS"],"topicsBy":"site"},{"id":135,"l":[{"p":"For candidate v, inspect neighbors other than its chosen predecessor"}],"k":"blank","a":["all adjacent vertices w except edgeTo(v)"],"topics":["SHORTEST_PATHS","MSTS"],"topicsBy":"site"},{"id":136,"l":[{"p":"Check alternate route equality"}],"k":"blank","a":["distTo(w) + weight(w,v) == distTo(v)"],"topics":["SHORTEST_PATHS","MSTS"],"topicsBy":"site"},{"id":137,"l":[{"p":"Keep candidate with greatest distance"}],"k":"blank","a":["maximum distTo(v) among those with another shortest predecessor"],"topics":["SHORTEST_PATHS","MSTS"],"topicsBy":"site"},{"id":138,"l":[{"p":"Return"}],"k":"blank","a":["the farthest qualifying vertex, or null if none"],"topics":["SHORTEST_PATHS","MSTS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa20-mt1","t":"Fall 2020 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1uZBrjtJMZd1M5dFbyztC1KsACZSrAGBg/view","sol":"https://drive.google.com/file/d/1sQFkLAorx7RRLnrVL9lYOcPSXh45QOyQ/view","topics":"fa20-mt1"},"p":[{"id":"61b-fa20-mt1/2","n":"2","t":"2. Character counting and comparators (92 pts)","b":[{"s":[{"p":"Implement countChar, which counts occurrences of c in a non-null string."},{"c":"public static int countChar(String a, char c) {\n    int count = 0;\n    for (⟪a⟫) {\n        if (⟪b⟫) {\n            ⟪c⟫;\n        }\n    }\n    return ⟪d⟫;\n}","lang":"java","f":{"a":"int i = 0; i < a.length(); i += 1","b":"a.charAt(i) == c","c":"count += 1","d":"count"}}]},{"id":1,"l":[{"p":"(a) Loop header"}],"k":"blank","a":["int i = 0; i < a.length(); i += 1","int i = 0; i < a.length(); i++"],"topics":["JAVA"],"part":"a"},{"id":2,"l":[{"p":"(a) Condition"}],"k":"blank","a":["a.charAt(i) == c","c == a.charAt(i)"],"topics":["JAVA"],"part":"a"},{"id":3,"l":[{"p":"(a) On a match"}],"k":"blank","a":["count += 1","count++"],"topics":["JAVA"],"part":"a"},{"id":4,"l":[{"p":"(a) Return value"}],"k":"blank","a":["count"],"topics":["JAVA"],"part":"a"},{"s":[{"p":"XComparator compares strings by the count of lowercase x. countChar is available."},{"c":"public int compare(String a, String b) {\n    return ⟪e⟫;\n}","lang":"java","f":{"e":"countChar(a, 'x') - countChar(b, 'x')"}}]},{"id":5,"l":[{"p":"(b) Return expression"}],"k":"blank","a":["countChar(a, 'x') - countChar(b, 'x')","Integer.compare(countChar(a, 'x'), countChar(b, 'x'))"],"topics":["JAVA","COMPARATORS"],"part":"b"},{"s":[{"p":"CharCountComparator instead uses a character supplied to its constructor."},{"c":"private char c;\npublic CharCountComparator(char givenC) {\n    ⟪f⟫;\n}\npublic int compare(String a, String b) {\n    return ⟪g⟫;\n}","lang":"java","f":{"f":"c = givenC","g":"countChar(a, c) - countChar(b, c)"}}]},{"id":6,"l":[{"p":"(c) Constructor body"}],"k":"blank","a":["c = givenC","this.c = givenC"],"topics":["JAVA","COMPARATORS"],"part":"c"},{"id":7,"l":[{"p":"(c) compare return expression"}],"k":"blank","a":["countChar(a, c) - countChar(b, c)","Integer.compare(countChar(a, c), countChar(b, c))"],"topics":["JAVA","COMPARATORS"],"part":"c"},{"s":[{"p":"findMax returns a maximum string according to any Comparator<String> c. The array is nonempty."},{"c":"private static String findMax(String[] strings, Comparator<String> c) {\n    String best = ⟪h⟫;\n    for (int i = 0; i < strings.length; i += 1) {\n        if (⟪i⟫) {\n            ⟪j⟫;\n        }\n    }\n    return ⟪k⟫;\n}","lang":"java","f":{"h":"strings[0]","i":"c.compare(strings[i], best) > 0","j":"best = strings[i]","k":"best"}}]},{"id":8,"l":[{"p":"(d) Initial best"}],"k":"blank","a":["strings[0]"],"topics":["COMPARATORS"],"part":"d"},{"id":9,"l":[{"p":"(d) Update condition"}],"k":"blank","a":["c.compare(strings[i], best) > 0","c.compare(best, strings[i]) < 0"],"topics":["COMPARATORS"],"part":"d"},{"id":10,"l":[{"p":"(d) Update"}],"k":"blank","a":["best = strings[i]"],"topics":["COMPARATORS"],"part":"d"},{"id":11,"l":[{"p":"(d) Return"}],"k":"blank","a":["best"],"topics":["COMPARATORS"],"part":"d"}],"topics":null},{"id":"61b-fa20-mt1/3","n":"3","t":"3. Student equals (66 pts)","b":[{"s":[{"c":"class Student {\n    String name; int SID;\n    public boolean equals(Student other) {\n        return name.equals(other.name) && SID == other.SID;\n    }\n}\nStudent sB = new Student(\"Borf\", 123);\nStudent sG = new Student(\"Gorf\", 123);\nStudent sB2 = new Student(\"Borf\", 123);\nObject oG = sG;\nObject oB2 = sB2;","lang":"java"},{"p":"The method equals(Student) overloads, rather than overrides, Object.equals(Object). Choose the result of each expression."}]},{"id":12,"l":[{"p":"(a) sB.equals(sG)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":1,"topics":["DMS"],"part":"a"},{"id":13,"l":[{"p":"(a) sB.equals(sB2)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":14,"l":[{"p":"(a) sB == sB2"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":1,"topics":["DMS"],"part":"a"},{"id":15,"l":[{"p":"(a) sG.equals(oG)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":16,"l":[{"p":"(a) sG == oG"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":17,"l":[{"p":"(a) sG.equals((Student) oG)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":18,"l":[{"p":"(a) sB.equals(oB2)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":1,"topics":["DMS"],"part":"a"},{"id":19,"l":[{"p":"(a) sB == oB2"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":1,"topics":["DMS"],"part":"a"},{"id":20,"l":[{"p":"(a) sB.equals((Student) oB2)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":21,"l":[{"p":"(a) ((Object) sB2).equals((Student) oB2)"}],"k":"mc","o":["true","false","compile error","runtime error"],"a":0,"topics":["DMS"],"part":"a"},{"id":22,"l":[{"p":"(b) After changing the parameter to Object and casting it to Student, which previously false expression becomes true?"}],"k":"mc","o":["sB.equals(sG)","sB == sB2","sB.equals(oB2)","sB == oB2"],"a":2,"topics":["DMS"],"part":"b"},{"id":23,"l":[{"p":"(c) Which check is needed before casting the Object argument to Student?"}],"k":"mc","o":["Only an SID comparison","That it is non-null and a Student","That both names are interned","That the argument is a String"],"a":1,"topics":["DMS"],"part":"c"}],"topics":null},{"id":"61b-fa20-mt1/4","n":"4","t":"4. Dynamic method selection with dogs (28 pts)","b":[{"s":[{"c":"class Dog { void bark() { System.out.println(\"bark\"); } }\nclass Puppy extends Dog { void bark() { System.out.println(\"lil bark\"); } }\nclass DogLover {\n    void pet(Dog d) { System.out.print(\"pet dog\"); d.bark(); }\n    void pet(Puppy p) { System.out.print(\"pet puppy\"); p.bark(); }\n}\nclass PuppyLover extends DogLover {\n    void pet(Puppy p) { System.out.print(\"pup love\"); p.bark(); }\n}\nPuppyLover pl = new PuppyLover();\nPuppy p = new Puppy();","lang":"java"}]},{"id":24,"l":[{"p":"What does pl.pet(p) print?"}],"k":"mc","o":["pup lovelil bark","pet puppylil bark","pet doglil bark","pet dogbark"],"a":0,"topics":["JAVA","INHERITANCE","DMS"]},{"id":25,"l":[{"p":"What does ((DogLover) pl).pet(p) print?"}],"k":"mc","o":["pup lovelil bark","pet puppylil bark","pet doglil bark","pet dogbark"],"a":0,"topics":["JAVA","INHERITANCE","DMS"]},{"id":26,"l":[{"p":"What does pl.pet((Dog) p) print?"}],"k":"mc","o":["pup lovelil bark","pet puppylil bark","pet doglil bark","pet dogbark"],"a":2,"topics":["JAVA","INHERITANCE","DMS"]},{"id":27,"l":[{"p":"What does ((DogLover) pl).pet((Dog) p) print?"}],"k":"mc","o":["pup lovelil bark","pet puppylil bark","pet doglil bark","pet dogbark"],"a":2,"topics":["JAVA","INHERITANCE","DMS"]}],"topics":null},{"id":"61b-fa20-mt1/5","n":"5","t":"5. AddOnlyList (118 pts)","b":[{"s":[{"p":"An AddOnlyList stores item 0 at array index 0, item 1 at M−1, item 2 at 1, item 3 at M−2, and so on. M is a power of two at least 8."},{"c":"private int indexOfI(int i, int M) {\n    if (i % 2 == 0) return ⟪a⟫;\n    else return ⟪b⟫;\n}\npublic T get(int i) { return ⟪c⟫; }","lang":"java","f":{"a":"i / 2","b":"M - i / 2 - 1","c":"items[indexOfI(i, items.length)]"}}]},{"id":28,"l":[{"p":"(a) Even item index"}],"k":"blank","a":["i / 2"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"a"},{"id":29,"l":[{"p":"(a) Odd item index"}],"k":"blank","a":["M - i / 2 - 1"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"a"},{"id":30,"l":[{"p":"(b) get return value"}],"k":"blank","a":["items[indexOfI(i, items.length)]"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"b"},{"s":[{"c":"public void addLast(T x) {\n    if (size == items.length) resize(size * 2);\n    int index = ⟪d⟫;\n    ⟪e⟫;\n    ⟪f⟫;\n}","lang":"java","f":{"d":"indexOfI(size, items.length)","e":"items[index] = x","f":"size += 1"}}]},{"id":31,"l":[{"p":"(c) New item index"}],"k":"blank","a":["indexOfI(size, items.length)"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"c"},{"id":32,"l":[{"p":"(c) Store item"}],"k":"blank","a":["items[index] = x"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"c"},{"id":33,"l":[{"p":"(c) Update size"}],"k":"blank","a":["size += 1","size++"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"c"},{"s":[{"c":"public void resize(int newlen) {\n    T[] newItems = (T[]) new Object[newlen];\n    for (int i = 0; i < size; i += 1) {\n        int targetIndex = ⟪g⟫;\n        ⟪h⟫;\n    }\n    ⟪i⟫;\n}","lang":"java","f":{"g":"indexOfI(i, newlen)","h":"newItems[targetIndex] = get(i)","i":"items = newItems"}}]},{"id":34,"l":[{"p":"(d) Destination index"}],"k":"blank","a":["indexOfI(i, newlen)"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"d"},{"id":35,"l":[{"p":"(d) Copy item"}],"k":"blank","a":["newItems[targetIndex] = get(i)"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"d"},{"id":36,"l":[{"p":"(d) Replace array"}],"k":"blank","a":["items = newItems"],"topics":["LISTS","ARRAYS","DEQUES"],"part":"d"}],"topics":null},{"id":"61b-fa20-mt1/6","n":"6","t":"6. List testing and implementation (120 pts)","b":[{"s":[{"p":"List61B<T> has get(i), size(), addLast(x), and a default contains method. The list is non-destructive."},{"c":"default boolean contains(T x) {\n    for (int i = 0; i < size(); i += 1) {\n        if (⟪a⟫) return true;\n    }\n    return false;\n}","lang":"java","f":{"a":"get(i).equals(x)"}}]},{"id":37,"l":[{"p":"(b) Match condition"}],"k":"blank","a":["get(i).equals(x)"],"topics":["JAVA","LISTS","ABSTRACTION","INHERITANCE"],"part":"b"},{"s":[{"p":"itemsNotIn(other) returns the items in this list but not in other, in original order."},{"c":"default List61B<T> itemsNotIn(List61B<T> other) {\n    AList<T> meOnly = new AList<>();\n    for (int i = 0; i < size(); i += 1) {\n        T current = get(i);\n        if (⟪b⟫) ⟪c⟫;\n    }\n    return meOnly;\n}","lang":"java","f":{"b":"!other.contains(current)","c":"meOnly.addLast(current)"}}]},{"id":38,"l":[{"p":"(d) Keep condition"}],"k":"blank","a":["!other.contains(current)"],"topics":["JAVA","LISTS","ABSTRACTION","INHERITANCE"],"part":"d"},{"id":39,"l":[{"p":"(d) Append kept item"}],"k":"blank","a":["meOnly.addLast(current)"],"topics":["JAVA","LISTS","ABSTRACTION","INHERITANCE"],"part":"d"},{"id":40,"l":[{"p":"(a) A three-item contains test should assert which results?"}],"k":"mc","o":["Only one present item","All three present items and one absent item","Only an absent item","Only the list size"],"a":1,"topics":["JAVA","LISTS","ABSTRACTION","INHERITANCE"],"part":"a"},{"id":41,"l":[{"p":"(c) For [0,1,2].itemsNotIn([1,4,5]), what is returned?"}],"k":"mc","o":["[0,2]","[1]","[0,1,2]","[4,5]"],"a":0,"topics":["JAVA","LISTS","ABSTRACTION","INHERITANCE"],"part":"c"}],"topics":null},{"id":"61b-fa20-mt1/7","n":"7","t":"7. Removing nodes (155 pts)","b":[{"s":[{"p":"IntLinkedListDeque uses a circular sentinel and doubly linked Node objects."},{"c":"private void removeNode(Node t) {\n    ⟪a⟫;\n    ⟪b⟫;\n}","lang":"java","f":{"a":"t.prev.next = t.next","b":"t.next.prev = t.prev"}}]},{"id":42,"l":[{"p":"(a) Fix previous node"}],"k":"blank","a":["t.prev.next = t.next"],"topics":["DEQUES"],"part":"a"},{"id":43,"l":[{"p":"(a) Fix next node"}],"k":"blank","a":["t.next.prev = t.prev"],"topics":["DEQUES"],"part":"a"},{"s":[{"c":"public boolean removeOneIterative(int x) {\n    Node p = sentinel.next;\n    while (p != sentinel) {\n        if (⟪c⟫) {\n            removeNode(p);\n            return true;\n        }\n        ⟪d⟫;\n    }\n    return false;\n}","lang":"java","f":{"c":"p.value == x","d":"p = p.next"}}]},{"id":44,"l":[{"p":"(b) Match condition"}],"k":"blank","a":["p.value == x"],"topics":["DEQUES","ABSTRACTION"],"part":"b"},{"id":45,"l":[{"p":"(b) Advance"}],"k":"blank","a":["p = p.next"],"topics":["DEQUES","ABSTRACTION"],"part":"b"},{"s":[{"c":"private boolean removeOneRecursive(Node p, int x) {\n    if (p == sentinel) return false;\n    if (p.value == x) { removeNode(p); return true; }\n    return ⟪e⟫;\n}\npublic boolean removeOneRecursive(int x) {\n    return ⟪f⟫;\n}","lang":"java","f":{"e":"removeOneRecursive(p.next, x)","f":"removeOneRecursive(sentinel.next, x)"}}]},{"id":46,"l":[{"p":"(c) Recursive step"}],"k":"blank","a":["removeOneRecursive(p.next, x)"],"topics":["DEQUES","ABSTRACTION"],"part":"c"},{"id":47,"l":[{"p":"(c) Public entry point"}],"k":"blank","a":["removeOneRecursive(sentinel.next, x)"],"topics":["DEQUES","ABSTRACTION"],"part":"c"},{"s":[{"p":"moveToFront(x) moves all occurrences of x to the front, preserving the order of other items."},{"c":"default void moveToFront(int x) {\n    int n = 0;\n    while (⟪g⟫) n += 1;\n    for (int i = 0; i < n; i += 1) ⟪h⟫;\n}","lang":"java","f":{"g":"removeOne(x)","h":"addFirst(x)"}}]},{"id":48,"l":[{"p":"(d) Remove and count each match"}],"k":"blank","a":["removeOne(x)"],"topics":["DEQUES","ABSTRACTION"],"part":"d"},{"id":49,"l":[{"p":"(d) Reinsert at front"}],"k":"blank","a":["addFirst(x)"],"topics":["DEQUES","ABSTRACTION"],"part":"d"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa20-mt2","t":"Fall 2020 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1XiwxEwQs0tYdPOQUYZE8-MEzMH22OHrc/view","sol":"https://drive.google.com/file/d/1HSuZJyBdn7UpKYvvMdbXG1WvZ3fYKvOt/view","topics":"fa20-mt2"},"p":[{"id":"61b-fa20-mt2/1","n":"1","t":"1. Heap Operations (55 pts)","b":[{"s":[{"p":"Consider this min-heap (written as its array, without the unused first spot): [1, 2, 3, 4, 5, 7, 8, 6]."},{"c":"          1\n       /     \\\n      2       3\n     / \\     / \\\n    4   5   7   8\n   /\n  6","lang":"txt"},{"p":"(a) We call insert(0). The resulting min-heap has 9 elements. (a) is the root, (b) the root’s right child, (c) the root’s left child’s left child, and (d) that node’s right child (the new 9th spot)."}]},{"id":1,"l":[{"p":"(a) What number is at (a)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":0,"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a) What number is at (b)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":3,"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":3,"l":[{"p":"(a) What number is at (c)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":2,"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":4,"l":[{"p":"(a) What number is at (d)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":4,"topics":["HEAPS"],"topicsBy":"site","x":"0 goes in under 4 and swims up past 4, 2 and 1: the array becomes [0, 1, 3, 2, 5, 7, 8, 6, 4].","part":"a"},{"s":[{"p":"(b) Starting from the same heap, we call removeMin three times. The result has five elements: (a) the root, (b) its left child, (c) its right child, and (d), (e) the left child’s children."}]},{"id":5,"l":[{"p":"(b) What number is at (a)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":4,"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":6,"l":[{"p":"(b) What number is at (b)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":5,"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":7,"l":[{"p":"(b) What number is at (c)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":7,"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":8,"l":[{"p":"(b) What number is at (d)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":6,"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":9,"l":[{"p":"(b) What number is at (e)?"}],"k":"mc","o":["0","1","2","3","4","5","6","7","8"],"a":8,"topics":["HEAPS"],"topicsBy":"site","x":"The heap ends as [4, 5, 7, 6, 8].","part":"b"}],"topics":null},{"id":"61b-fa20-mt2/2","n":"2","t":"2. Trie Operations (60 pts)","b":[{"s":[{"p":"The trie below stores the keys goal, chin, chair, sun, sunny, sue and sued. Its paths: g–o–a–l; c–h–i–n and c–h–a–i–r; s–u–n–n–y and s–u–e–d. The nodes ending a key (isKey true) are l, the n of chin, r, the first n of sun, y, e and d."}]},{"id":10,"l":[{"p":"(a) If we call keysWithPrefix(\"su\"), what keys are returned?"}],"k":"sata","o":["sun","chin","sued","goal","sue","sunn","chair","sunny","n","y","e","d"],"a":[0,2,4,7],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":11,"l":[{"p":"(b) What key, when added, creates the fewest nodes? If several tie, select all of them."}],"k":"sata","o":["goals","in","goat","soccer","chain","cheese","at","camel"],"a":[0,2,4],"topics":["TRIES"],"topicsBy":"site","x":"goals, goat and chain each need just one new node.","part":"b"},{"s":[{"p":"(c) shortestPrefixOf(String s) returns the shortest key in the trie that is a prefix of s; e.g. shortestPrefixOf(\"goalie\") returns \"goal\", and a string is a prefix of itself. It traverses no more nodes than necessary."}]},{"id":12,"l":[{"p":"(c) Which s maximizes the number of nodes traversed? If several tie, select all of them."}],"k":"sata","o":["sun","sunnyday","sunny","chin","sue","goal","sued","sunn","chair","chairlift"],"a":[8,9],"topics":["TRIES"],"topicsBy":"site","x":"The search stops at the first key it reaches. chair (and chairlift) walk c–h–a–i–r, 5 nodes, before reaching a key; the s words stop at sun or sue after 3.","part":"c"}],"topics":null},{"id":"61b-fa20-mt2/3","n":"3","t":"3. Heap Iterator (50 pts)","b":[{"s":[{"p":"XMinPQ implements the MinPQ interface for Integers, where an Integer’s priority is itself. Don’t assume XMinPQ uses a heap."},{"c":"public class XMinPQ implements MinPQ<Integer>, Iterable<Integer> {\n    public void add(Integer x) {...}\n    public Integer getSmallest() {...}\n    public Integer removeSmallest() {...}\n    public int size() {...}\n    public Iterator<Integer> iterator() {\n        return new XIterator();\n    }\n    private class XIterator implements Iterator<Integer> {\n        public int x;\n        public XIterator() {\n            x = removeSmallest();\n        }\n        public boolean hasNext() {\n            return x > 0;\n        }\n        public Integer next() {\n            x = x - 1;\n            return removeSmallest();\n        }\n    }\n}\n\npublic static void main(String[] args) {\n    XMinPQ mpq = new XMinPQ();\n    mpq.add(4);\n    mpq.add(1);\n    mpq.add(5);\n    mpq.add(2);\n    mpq.add(6);\n    mpq.add(3);\n    mpq.add(8);\n    mpq.add(7);\n    for (int i: mpq) {\n        System.out.print(i + \" \"); // line 1\n    }\n    System.out.println();\n    for (int i: mpq) {\n        System.out.print(i + \" \"); // line 2\n    }\n}","lang":"java"}]},{"id":13,"l":[{"p":"What does line 1 print? (Numbers separated by spaces.)"}],"k":"blank","a":["2"],"topics":["HEAPS","ITERATORS"],"topicsBy":"site"},{"id":14,"l":[{"p":"What does line 2 print?"}],"k":"blank","a":["4 5 6","4, 5, 6"],"topics":["HEAPS","ITERATORS"],"topicsBy":"site","x":"Making an iterator removes the smallest item as the count: the first removes 1, so it returns one item, 2. The second removes 3, so it returns 4, 5, 6."}],"topics":null},{"id":"61b-fa20-mt2/4","n":"4","t":"4. Asymptotics (230 pts)","b":[{"s":[{"p":"For each, give the worst-case runtime in Θ notation as a function of N."},{"c":"public static void loops(int N) {\n    for (int i = 1; i < 2; i += 1) {\n        for (int j = 2; j < 4; j = j * j) {\n            for (int k = 3; k < N; k = k * 2) {\n                for (int m = 4; m < 8; m = m * m * m) {\n                    System.out.println(\"hello\");\n                }\n            }\n        }\n    }\n}","lang":"java"}]},{"id":15,"l":[{"p":"(a) loops"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":3,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Every loop but k’s runs once; k doubles up to N.","part":"a"},{"s":[{"c":"public static void addToSet(int N) {\n    HashSet<RandomThing> m = new HashSet<>();\n    for (int i = 0; i < N; i += 1) {\n        // getNextRandomThing takes constant time\n        RandomThing rt = getNextRandomThing();\n        m.add(rt);\n    }\n}","lang":"java"}]},{"id":16,"l":[{"p":"(b) addToSet"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":6,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","x":"In the worst case every RandomThing hashes to the same bucket.","part":"b"},{"s":[{"c":"public static List<Integer> nestedSum(List<Integer> x) {\n    List<Integer> newInts = new ArrayList<>();\n    for (int i : x) {\n        for (int j : x) {\n            newInts.add(i + j);\n        }\n    }\n    return newInts;\n}\n\nList<Integer> x = getIntegers(); // getIntegers returns a List of Integers\nint N = x.size();\nList<Integer> x2 = nestedSum(nestedSum(x));","lang":"java"}]},{"id":17,"l":[{"p":"(c) nestedSum(nestedSum(x))"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":10,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"The inner call returns N² items, so the outer call does (N²)² work.","part":"c"},{"s":[{"c":"private static void g(int N, int ss) {\n    if (ss > N) {\n        return;\n    }\n    for (int i = 0; i < N; i += ss) {\n        System.out.print(i + \" \");\n    }\n    System.out.println();\n    g(N, ss * 2);\n}\n// Give the runtime for g(N, 1);","lang":"java"}]},{"id":18,"l":[{"p":"(d) g(N, 1)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"N + N/2 + N/4 + … < 2N.","part":"d"},{"s":[{"c":"private static void g2(int N, int ss) {\n    if (ss > N) {\n        return;\n    }\n    for (int i = 0; i < N; i += ss) {\n        System.out.print(i + \" \");\n    }\n    System.out.println();\n    g2(N, ss * 2);\n    g2(N, ss * 2);\n}\n// Give the runtime for g2(N, 1);","lang":"java"}]},{"id":19,"l":[{"p":"(e) g2(N, 1)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":5,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Each level of calls does N work in total (twice as many calls, each half as much), for log N levels.","part":"e"},{"s":[{"c":"public void func(int N) {\n    int Q = 0;\n    for (int i = 1; i < N; i *= 3) {\n        Q += 1;\n    }\n    disco(Q);\n}\npublic void disco(int Q) {\n    if (Q == 0) {\n        return;\n    }\n    for (int i = 0; i < Q; i += 1) {\n        System.out.println(\"hi\");\n    }\n    disco(Q - 1);\n}","lang":"java"}]},{"id":20,"l":[{"p":"(f) func"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Q is about log₃ N, and disco does Q + (Q − 1) + … + 1 = Θ(Q²).","part":"f"}],"topics":null},{"id":"61b-fa20-mt2/5","n":"5","t":"5. Compress (60 pts)","b":[{"s":[{"p":"Consider the UnionFind class from lab (no path compression). We add compress, which compresses the height of each tree to 1 by connecting every vertex to its root. For example, compress turns the parent array {−4, 0, 0, 2, −4, 4, 4, 6} into {−4, 0, 0, 0, −4, 4, 4, 4}: vertices 3 and 7 connect to their roots, and the roots (0, 4) and the vertices already under them (1, 2, 5, 6) don’t change. Use the given skeleton."},{"c":"public class UnionFind {\n    private int[] parent;\n    public int sizeOf(int v1) {\n        int root = find(v1);\n        return -1 * parent[root];\n    }\n    public boolean isConnected(int v1, int v2) {\n        return find(v1) == find(v2);\n    }\n    public void connect(int v1, int v2) { ... }\n    // Path compression is NOT implemented\n    public int find(int v1) { ... }\n\n    public void compress() {\n        for (⟪a⟫) {\n            if (⟪b⟫) {\n                ⟪c⟫;\n            }\n        }\n    }\n}","lang":"java","f":{"a":"int i = 0; i < parent.length; i++","b":"parent[i] >= 0","c":"parent[i] = find(i)"}}]},{"id":21,"l":[{"p":"(a) The loop header"}],"k":"blank","a":["int i = 0; i < parent.length; i++","int i = 0; i < parent.length; i += 1"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":22,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["parent[i] >= 0","i != find(i)","parent[i] > -1"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":23,"l":[{"p":"(c) Inside the if"}],"k":"blank","a":["parent[i] = find(i)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"Point every non-root straight at its root; roots keep their negative sizes.","part":"c"}],"topics":null},{"id":"61b-fa20-mt2/6","n":"6","t":"6. LLRB Insertions (150 pts)","b":[{"s":[{"p":"We use this LLRB (links labeled red are red; the others are black):"},{"c":"                18\n          red /     \\\n            6         24\n          /   \\      /   \\\n         4     8    22    40\n        / \\   / \\   / red\n       3   5 7  17 21","lang":"txt"},{"p":"For each prompt, give a single int which, inserted into the LLRB above, causes exactly the requested balance operation and no other. If several work, give the smallest positive one; if none does, write None. Each part starts from the tree above."}]},{"id":24,"l":[{"p":"(a) A single rotateLeft"}],"k":"blank","a":["41"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"41 becomes a red right child of 40, which has no left child: one rotateLeft. No integer fits as a right child further left.","part":"a"},{"id":25,"l":[{"p":"(b) A single rotateRight"}],"k":"blank","a":["None","none"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"A rotateRight always leaves a node with two red children, so a colorFlip follows.","part":"b"},{"id":26,"l":[{"p":"(c) A single colorFlip"}],"k":"blank","a":["23"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"23 becomes 22’s red right child next to red 21: colorFlip(22), and 22 is a left child, so nothing else.","part":"c"},{"s":[{"p":"Now consider the corresponding 2-3 tree. Values may be any real number (e.g. 3.6)."}]},{"id":27,"l":[{"p":"(d) What is the minimum number of values we must add to increase its height?"}],"k":"blank","a":["3"],"topics":["B_TREES","RED_BLACK_TREES"],"topicsBy":"site","part":"d"},{"id":28,"l":[{"p":"(e) What is the maximum number of values we can add without increasing its height?"}],"k":"blank","a":["14"],"topics":["B_TREES","RED_BLACK_TREES"],"topicsBy":"site","x":"The 2-3 tree is [6 18] with children [4], [8] and [24], and leaves [3], [5], [7], [17], [21 22] and [40]. Filled to height 2 it can hold 26 values (13 nodes × 2); it holds 12 now.","part":"e"}],"topics":null},{"id":"61b-fa20-mt2/7","n":"7","t":"7. By The Numbers (175 pts)","b":[{"s":[{"p":"For each scenario, give the minimum and maximum. If there is no min or max, write None. Height is the number of links from the root to the farthest leaf (a tree with 2 nodes has height 1); a node’s depth is the number of links from the root to it (the root has depth 0). BSTs have no duplicates."}]},{"id":29,"l":[{"p":"(a) The number of nodes in a non-empty tree which is both a BST and a max-heap: minimum"}],"k":"blank","a":["1"],"topics":["BSTS","HEAPS"],"topicsBy":"site","part":"a"},{"id":30,"l":[{"p":"(a) …maximum"}],"k":"blank","a":["2"],"topics":["BSTS","HEAPS"],"topicsBy":"site","x":"A max-heap needs children smaller than the parent, so only a left child, but a heap must be complete: at most one child.","part":"a"},{"id":31,"l":[{"p":"(b) The height of a BST with 7 nodes where the median is the root: minimum"}],"k":"blank","a":["2"],"topics":["BSTS"],"topicsBy":"site","part":"b"},{"id":32,"l":[{"p":"(b) …maximum"}],"k":"blank","a":["3"],"topics":["BSTS"],"topicsBy":"site","x":"Each side has 3 nodes, which can be a chain of height 2 below the root.","part":"b"},{"id":33,"l":[{"p":"(c) The height of a WeightedQuickUnion with 10 items, all connected: minimum"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"c"},{"id":34,"l":[{"p":"(c) …maximum"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"A WQU of height H needs at least 2ᴴ items, and 2⁴ = 16 > 10.","part":"c"},{"id":35,"l":[{"p":"(d) The depth of the median value in a heap of 15 objects, none duplicates: minimum"}],"k":"blank","a":["1"],"topics":["HEAPS"],"topicsBy":"site","part":"d"},{"id":36,"l":[{"p":"(d) …maximum"}],"k":"blank","a":["3"],"topics":["HEAPS"],"topicsBy":"site","part":"d"},{"id":37,"l":[{"p":"(e) The depth of the median value in a BST of 15 objects: minimum"}],"k":"blank","a":["0"],"topics":["BSTS"],"topicsBy":"site","part":"e"},{"id":38,"l":[{"p":"(e) …maximum"}],"k":"blank","a":["14"],"topics":["BSTS"],"topicsBy":"site","part":"e"},{"id":39,"l":[{"p":"(f) The length of the longest list in a hash table with 10 buckets and 20 items, each bucket a list: minimum"}],"k":"blank","a":["2"],"topics":["HASHING"],"topicsBy":"site","part":"f"},{"id":40,"l":[{"p":"(f) …maximum"}],"k":"blank","a":["20"],"topics":["HASHING"],"topicsBy":"site","part":"f"},{"id":41,"l":[{"p":"(g) The height of the tallest tree in a hash table with 10 buckets and 7 items, each bucket an LLRB: minimum"}],"k":"blank","a":["0"],"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","part":"g"},{"id":42,"l":[{"p":"(g) …maximum"}],"k":"blank","a":["3"],"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","x":"All 7 in one LLRB: its height can reach 3 with red links.","part":"g"}],"topics":null},{"id":"61b-fa20-mt2/8","n":"8","t":"8. Window (180 pts)","b":[{"s":[{"p":"(a) Point represents a point in 2D space. Fill in isInside so it returns true if the point is inside the window bounded by the given x and y coordinates (points on the boundary count). Assume x1 ≤ x2 and y1 ≤ y2."},{"c":"public class Point {\n    public double x;\n    public double y;\n    public Point(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n    public boolean isInside(double x1, double x2, double y1, double y2) {\n        return ⟪a⟫;\n    }\n}","lang":"java","f":{"a":"x1 <= x && x <= x2 && y1 <= y && y <= y2"}}]},{"id":43,"l":[{"p":"(a) return ____"}],"k":"blank","a":["x1 <= x && x <= x2 && y1 <= y && y <= y2","x >= x1 && x <= x2 && y >= y1 && y <= y2","y1 <= y && y <= y2 && x1 <= x && x <= x2"],"topics":["K_D_TREES"],"topicsBy":"site","part":"a"},{"s":[{"p":"Now use a k-d tree to find all points inside a window. For example, window(4, 7, 4, 7) on the tree below returns (5, 5) and (5, 6). The method should be efficient and prune branches that definitely contain no points in the window."},{"p":"The tree, with its branch labels: ψ(2, 3) splits on x, with left branch (a) to γ(1, 5) and right branch (b) to κ(5, 2). γ splits on y, with branches (c) down and (d) up (both empty). κ splits on y, with (e) down (empty) and (f) up to δ(5, 6). δ splits on x, with (g) left to λ(3, 3) and (h) right to π(5, 5). λ splits on y, with (i) down and (j) up; π splits on y, with (k) down and (l) up (all empty)."}]},{"id":44,"l":[{"p":"(b) Which branches can be pruned in the call window(4, 7, 4, 7)? If a branch higher up is pruned, branches below it are not counted (they’re never considered). Branches that don’t point to a node, e.g. (d), can still be pruned."}],"k":"sata","o":["(a)","(b)","(c)","(d)","(e)","(f)","(g)","(h)","(i)","(j)","(k)","(l)","No branches can be pruned"],"a":[0,3,4,8],"topics":["K_D_TREES"],"topicsBy":"site","x":"Following the staff key: (a) holds only x < 2, (e) only y < 2 and (i) only y < 3, all outside the window; (d) is marked pruned as well.","part":"b"},{"s":[{"p":"(c) Fill in window (at most 3 lines in its body) and windowHelper."},{"c":"private static final boolean HORIZONTAL = false; // we compare x coordinates\nprivate static final boolean VERTICAL = true; // we compare y coordinates\nprivate Node root;\n\nprivate class Node {\n    private Point p;\n    private boolean orientation; // true == VERTICAL, false == HORIZONTAL\n    private Node leftChild;  // also refers to the \"down\" child\n    private Node rightChild; // also refers to the \"up\" child\n    ...\n}\n\npublic List<Point> window(double x1, double x2, double y1, double y2) {\n    List<Point> points = new LinkedList<>();\n    ⟪b⟫;\n    return points;\n}\n\nprivate void windowHelper(Node n, List<Point> points, double x1, double x2, double y1, double y2) {\n    if (⟪c⟫) {\n        return;\n    }\n    if (n.p.isInside(x1, x2, y1, y2)) {\n        points.add(n.p);\n    }\n    if (n.orientation == HORIZONTAL) {\n        if (⟪d⟫) {\n            windowHelper(n.leftChild, points, x1, x2, y1, y2);\n        }\n        if (⟪e⟫) {\n            windowHelper(n.rightChild, points, x1, x2, y1, y2);\n        }\n    } else {\n        if (⟪f⟫) {\n            windowHelper(n.leftChild, points, x1, x2, y1, y2);\n        }\n        if (⟪g⟫) {\n            windowHelper(n.rightChild, points, x1, x2, y1, y2);\n        }\n    }\n}","lang":"java","f":{"b":"windowHelper(root, points, x1, x2, y1, y2)","c":"n == null","d":"n.p.x > x1","e":"n.p.x <= x2","f":"n.p.y > y1","g":"n.p.y <= y2"}}]},{"id":45,"l":[{"p":"(c) The middle line of window"}],"k":"blank","a":["windowHelper(root, points, x1, x2, y1, y2)"],"topics":["K_D_TREES"],"topicsBy":"site","part":"c"},{"id":46,"l":[{"p":"(c) The base case: if (____) return"}],"k":"blank","a":["n == null"],"topics":["K_D_TREES"],"topicsBy":"site","part":"c"},{"id":47,"l":[{"p":"(c) Horizontal node: when to search the left child"}],"k":"blank","a":["n.p.x > x1","n.p.x >= x1","x1 < n.p.x","x1 <= n.p.x"],"topics":["K_D_TREES"],"topicsBy":"site","part":"c"},{"id":48,"l":[{"p":"(c) Horizontal node: when to search the right child"}],"k":"blank","a":["n.p.x <= x2","x2 >= n.p.x"],"topics":["K_D_TREES"],"topicsBy":"site","part":"c"},{"id":49,"l":[{"p":"(c) Vertical node: when to search the down child"}],"k":"blank","a":["n.p.y > y1","n.p.y >= y1","y1 < n.p.y","y1 <= n.p.y"],"topics":["K_D_TREES"],"topicsBy":"site","part":"c"},{"id":50,"l":[{"p":"(c) Vertical node: when to search the up child"}],"k":"blank","a":["n.p.y <= y2","y2 >= n.p.y"],"topics":["K_D_TREES"],"topicsBy":"site","x":"Only search a side that could hold points in the window. Ties go right, so the staff used > for the left side, but they accepted >= too.","part":"c"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa22-final","t":"Fall 2022 Final","src":{"exam":"https://drive.google.com/file/d/1LQ1Z6cki1dtPg5KGBYaKT53B9ZiPgvXt/view","sol":"https://drive.google.com/file/d/18OqXS1qtv97nV1gUChcdb58HsMWphQYg/view","topics":"fa22-final"},"p":[{"id":"61b-fa22-final/1","n":"1","t":"1. Are You Better Informed than ChatGPT?","b":[{"s":[{"p":"For each response, select every statement that is completely true. Hash-table buckets use linked lists."}]},{"id":1,"l":[{"p":"1.1 Advantages of a balanced BST over a hash table"}],"k":"sata","o":["Faster average search, insert, and delete because keys are ordered","Efficient minimum, maximum, and range queries","A better worst-case bound for these operations than a chained hash table","None of the above"],"a":[1,2],"topics":["BSTS"],"topicsBy":"site","x":"A balanced BST has logarithmic worst-case operations; a chained table may have linear worst-case operations."},{"id":2,"l":[{"p":"1.2 Advantages of insertion sort over randomized quicksort"}],"k":"sata","o":["Insertion sort is faster on small inputs because its time complexity is O(n)","Insertion sort is stable; randomized quicksort with Hoare partitioning is not","Insertion sort is in-place but randomized quicksort always needs an auxiliary array","Insertion sort can exploit an already partially sorted array","None of the above"],"a":[1,3],"topics":["SORTING"],"topicsBy":"site","x":"Insertion sort still has quadratic worst-case time. Hoare partitioning is in-place."},{"id":3,"l":[{"p":"1.3 Advantages of Quick Find over Weighted Quick Union"}],"k":"sata","o":["Quick Find is generally faster on average because all operations are constant time","Quick Find uses less space because WQU cannot use a flat array","Quick Find is better for frequently changing connectivity","None of the above"],"a":[3],"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"Quick Find has fast connectivity queries but slow union operations; both implementations can use arrays."},{"id":4,"l":[{"p":"1.4 Selection sort versus merge sort: statements credited by the official key"}],"k":"sata","o":["Selection sort is O(n²), whereas merge sort is O(n log n)","Choose selection sort for small inputs or whenever a stable sort is needed","None of the above"],"a":[0],"topics":["SORTING"],"topicsBy":"site","x":"The first statement is true and the staff accepted it, though it is not a reason to prefer selection sort. Merge sort is stable."}],"topics":null},{"id":"61b-fa22-final/2","n":"2","t":"2. Sort Mechanisms","b":[{"s":[{"p":"Start with [5, 3, 1, 6, 4, 9, 7]. Give the array after the first swap under each algorithm."}]},{"id":5,"l":[{"p":"2.1 Selection sort"}],"k":"blank","a":["1, 3, 5, 6, 4, 9, 7"],"topics":["SORTING"],"topicsBy":"site","x":"Selection sort first swaps the minimum, 1, with 5."},{"id":6,"l":[{"p":"2.2 Insertion sort"}],"k":"blank","a":["3, 5, 1, 6, 4, 9, 7"],"topics":["SORTING"],"topicsBy":"site","x":"The adjacent 5 and 3 swap first."},{"id":7,"l":[{"p":"2.3 Quicksort, leftmost pivot 5 and Hoare partitioning"}],"k":"blank","a":["5, 3, 1, 4, 6, 9, 7"],"topics":["SORTING"],"topicsBy":"site","x":"The first misplaced pair is 6 and 4."},{"id":8,"l":[{"p":"2.4 Heapsort, including heapification"}],"k":"blank","a":["5, 3, 9, 6, 4, 1, 7"],"topics":["SORTING"],"topicsBy":"site","x":"Bottom-up max-heapification swaps 1 with its larger child, 9."},{"id":9,"l":[{"p":"2.5 Why ask no first-swap question for lecture merge sort?"}],"k":"mc","o":["Merge sort is nondeterministic","The merge strategy changes the first swap","The given input array is not sorted by swaps","Merge sort never swaps values in any array"],"a":2,"topics":["SORTING"],"topicsBy":"site","x":"The lecture algorithm merges into auxiliary space rather than swapping items in the given array."}],"topics":null},{"id":"61b-fa22-final/3","n":"3","t":"3. Asymptotic Runtime Analysis","b":[{"s":[{"c":"void f1(int N) {\n  for (int i = 1; i < N; i += 2)\n    for (int j = 1; j < N; j *= 3) print(\"*\");\n}\nvoid f2(int N) {\n  print(\"x\");\n  if (N > 1) for (int i = 0; i < 4; i++) f2(N / 2);\n}\nvoid f3(int N) {\n  for (int i = 0; i < N; i++) print(\"*\");\n  if (N > 1) for (int i = 0; i < 4; i++) f3(N / 2);\n}","lang":"java"}]},{"id":10,"l":[{"p":"3.1 Tight runtime of f1"}],"k":"blank","a":["Theta(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":11,"l":[{"p":"3.2 Number of prints in f2, as a sum for power-of-two N"}],"k":"blank","a":["1 + 4 + 16 + ... + N^2"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"There are 4^k calls at level k and log₂N levels below the root."},{"id":12,"l":[{"p":"3.3 Tight runtime of f3"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Level costs are N, 2N, 4N, and so on, dominated by the final level."},{"s":[{"p":"f4 fills an array with 0,1,…,N−1, swaps every adjacent pair from left to right once, then insertion-sorts the result."}]},{"id":13,"l":[{"p":"3.4 Tight runtime of f4"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"The array becomes [1,2,…,N−1,0], with only N−1 inversions."},{"s":[{"p":"f5 loops x from 2 to N−1. For each x, it tests divisors f from 2 up to √x and breaks on a divisor."}]},{"id":14,"l":[{"p":"3.5 Valid big-O upper bounds for f5"}],"k":"sata","o":["O(1)","O(√N)","O(N√N)","O(N²)","O(N!)"],"a":[2,3,4],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"The outer loop takes Θ(N) iterations, and each inner loop is at most O(√N)."}],"topics":null},{"id":"61b-fa22-final/4","n":"4","t":"4. BSTs","b":[{"s":[{"p":"The original BST has root 48. Its right branch goes through 95, 57, 75, 66, 59; its in-order predecessor and successor of 48 are 36 and 50."}]},{"id":15,"l":[{"p":"4.1 Where does add(58) place the new node?"}],"k":"blank","a":["left child of 59"],"topics":["BSTS"],"topicsBy":"site","x":"Follow 48→95→57→75→66→59."},{"id":16,"l":[{"p":"4.2 Which listed value can replace root 48 under Hibbard deletion?"}],"k":"blank","a":["36"],"topics":["BSTS"],"topicsBy":"site","x":"The predecessor is 36; the successor is 50, which was not a choice."},{"id":17,"l":[{"p":"4.3 Effect on tree height of rotateLeft(57)"}],"k":"mc","o":["Decreases by 1","Unchanged","Increases by 1"],"a":1,"topics":["BSTS"],"topicsBy":"site","x":"75 moves above 57, and a longest root-to-leaf path remains the same length."},{"id":18,"l":[{"p":"4.4 Possible depths of the median in some 13-node BST"}],"k":"sata","o":["0","1","3","5","12"],"a":[0,1,2,3,4],"topics":["BSTS"],"topicsBy":"site","x":"The median can be the root, an interior node, or even a leaf at depth 12 in a zig-zag tree."}],"topics":null},{"id":"61b-fa22-final/5","n":"5","t":"5. Shortest Paths","b":[{"id":19,"l":[{"p":"5.1 Inputs required to run A*"}],"k":"sata","o":["Graph","Source vertex","Target vertex","Disallowed vertices","Precomputed shortest-path tree","Heuristic"],"a":[0,1,2,5],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"s":[{"p":"5.2 was struck from grading by course staff because the real-world wording was ambiguous."},{"p":"For 5.3–5.5, use this directed graph. Edges and weights: 0→1 (4), 1→2 (2), 2→0 (5), 0→3 (6), 0→4 (3), 2→3 (8), 2→5 (2), 3→4 (9), 5→4 (2)."}]},{"id":20,"l":[{"p":"5.3 Dijkstra removal order starting from 2"}],"k":"blank","a":["2, 5, 4, 0, 3, 1"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","x":"The shortest distances from 2 are 0, 2, 4, 5, 8, and 9 in that vertex order."},{"id":21,"l":[{"p":"5.4 Which vertices can be visited last by BFS from 2 with arbitrary adjacency order?"}],"k":"sata","o":["0","1","2","3","4","5"],"a":[1,4],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","x":"The last BFS layer consists of 1 and 4."},{"id":22,"l":[{"p":"5.5 Which vertices can be visited last if the BFS fringe is a stack?"}],"k":"sata","o":["0","1","2","3","4","5"],"a":[1,3,5],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","x":"The start 2 is first, 0 must precede 1, and 4 is reached before another unfinished neighbor of 2."},{"id":23,"l":[{"p":"5.6 Relax E/2 randomly chosen edges before ordinary Dijkstra. Does this preserve correctness?"}],"k":"mc","o":["Always computes the correct SPT","Only if no relaxed edge is in the SPT","Only if every relaxed edge is in the SPT","Never computes the correct SPT"],"a":0,"topics":["SHORTEST_PATHS"],"topicsBy":"site","x":"Early relaxations only improve tentative distances; Dijkstra still removes vertices by priority."},{"id":24,"l":[{"p":"5.7 Negate every edge weight, then run Dijkstra. What is always true?"}],"k":"mc","o":["It returns longest simple paths","It returns the original shortest-path tree","Neither"],"a":2,"topics":["SHORTEST_PATHS"],"topicsBy":"site","x":"Dijkstra does not generally work on negative edges."},{"id":25,"l":[{"p":"5.8 Double every edge weight. What happens to the shortest-path tree?"}],"k":"mc","o":["The same tree remains a shortest-path tree","It is only sometimes the same","It is never the same"],"a":0,"topics":["SHORTEST_PATHS"],"topicsBy":"site","x":"Multiplying all path weights by the same positive constant preserves their order."},{"id":26,"l":[{"p":"5.9 Every edge weighs 1. Can Dijkstra and BFS produce the same SPT?"}],"k":"mc","o":["Always identical even without matching tie-breaks","Sometimes identical; tie-breaks can differ","Never identical"],"a":1,"topics":["SHORTEST_PATHS"],"topicsBy":"site","x":"With matching source and tie-breaking, they agree; without specified tie-breaking, only “sometimes” is guaranteed."}],"topics":null},{"id":"61b-fa22-final/6","n":"6","t":"6. Tries","b":[{"s":[{"p":"The original diagram shows the keys ma, map, maple, man, mane, plus other branches. Refer to the original PDF for its exact drawn shape."}]},{"id":27,"l":[{"p":"6.1 Which keys does keysWithPrefix(\"ma\") return?"}],"k":"sata","o":["ma","map","mapl","maple","man","mane"],"a":[1,3,4,5],"topics":["TRIES"],"topicsBy":"site","x":"The path “mapl” is a prefix but not a complete key; “ma” is likewise not marked as a key."},{"id":28,"l":[{"p":"6.2 Which additions create the fewest new nodes?"}],"k":"sata","o":["arck","at","of","maples","marg","marge"],"a":[0,1,3],"topics":["TRIES"],"topicsBy":"site","x":"Each adds one node to the shown trie."},{"id":29,"l":[{"p":"6.3 Inputs requiring the most traversal for shortestPrefixOf"}],"k":"sata","o":["arcs","dude","duel","duels","duelsport","mane","mapl","maple","maplesyrup"],"a":[3,4],"topics":["TRIES"],"topicsBy":"site","x":"Both traverse through the five-letter key “duels” before stopping."}],"topics":null},{"id":"61b-fa22-final/7","n":"7","t":"7. Mash Ups","b":[{"id":30,"l":[{"p":"7.1 Worst-case contains in a hash set whose buckets are heaps"}],"k":"blank","a":["O(N)"],"topics":["HASHING"],"topicsBy":"site","x":"Searching an arbitrary value in a heap can require scanning the entire heap."},{"id":31,"l":[{"p":"7.2 Worst-case contains when each bucket is a 2–3 tree"}],"k":"blank","a":["O(log N)"],"topics":["HASHING"],"topicsBy":"site","x":"Even if all N keys collide, the balanced tree has logarithmic height."},{"s":[{"p":"7.3–7.4: An outer table has M buckets; each contains a P-bucket inner table. Both levels use the same hashCode; N items are evenly distributed by hashCode. Assume M=P."}]},{"id":32,"l":[{"p":"7.3 Average list length under the two accepted interpretations"}],"k":"blank","a":["N/M","N/M^2"],"topics":["HASHING"],"topicsBy":"site","x":"Staff accepted N/M among occupied inner lists or N/M² averaged over all allocated inner lists."},{"id":33,"l":[{"p":"7.4 Approximate number of occupied buckets"}],"k":"blank","a":["M"],"topics":["HASHING"],"topicsBy":"site","x":"Each outer bucket uses just one of its inner buckets because the hash is reused."},{"id":34,"l":[{"p":"7.5 After inserting 5 then 3 into a right-leaning red-black BST, what repairs the red-link direction?"}],"k":"blank","a":["rotateRight(5)"],"topics":["RED_BLACK_TREES"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa22-final/8","n":"8","t":"8. Heap Verification","b":[{"s":[{"p":"A max-heap is represented as a 2D array, one row per level: [[15], [11, 8], [4, 10, 5, 6]]. The helper is isValidHeap(heap, r, c), where r is row and c is the index within that row."}]},{"id":35,"l":[{"p":"8.1 Initial helper call arguments"}],"k":"blank","a":["heap, 0, 0"],"topics":["HEAPS"],"topicsBy":"site","x":"Start at the root in row 0, column 0."},{"id":36,"l":[{"p":"8.2 Base case for helper recursion"}],"k":"blank","a":["r >= heap.length - 1"],"topics":["HEAPS"],"topicsBy":"site","x":"The last row consists of leaves."},{"id":37,"l":[{"p":"8.3 Left-child column in the next row"}],"k":"blank","a":["2 * c"],"topics":["HEAPS"],"topicsBy":"site"},{"id":38,"l":[{"p":"8.4 Comparison that detects a max-heap violation at the left child"}],"k":"blank","a":["heap[r][c] < heap[r + 1][left]"],"topics":["HEAPS"],"topicsBy":"site"},{"id":39,"l":[{"p":"8.5 Return expression after checking both children"}],"k":"blank","a":["isValidHeap(heap, r + 1, left) && isValidHeap(heap, r + 1, right)"],"topics":["HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa22-final/9","n":"9","t":"9. IterableComparator","b":[{"s":[{"p":"Implement Comparator<Iterable> by comparing the number of elements available in two iterables a and b."}]},{"id":40,"l":[{"p":"9.1 Return type of compare"}],"k":"blank","a":["int"],"topics":["COMPARATORS"],"topicsBy":"site"},{"id":41,"l":[{"p":"9.2 Method name"}],"k":"blank","a":["compare"],"topics":["COMPARATORS"],"topicsBy":"site"},{"id":42,"l":[{"p":"9.3 Parameter type for both a and b"}],"k":"blank","a":["Iterable"],"topics":["COMPARATORS"],"topicsBy":"site"},{"id":43,"l":[{"p":"9.4 Enhanced-for loop header over a"}],"k":"blank","a":["Object x : a"],"topics":["ITERATION"],"topicsBy":"site","x":"Iterable does not promise int elements or a size() method."},{"id":44,"l":[{"p":"9.5 Loop body to count one element"}],"k":"blank","a":["ac = ac + 1;"],"topics":["ITERATION"],"topicsBy":"site"},{"id":45,"l":[{"p":"9.6 Valid compare return expressions"}],"k":"sata","o":["ac","bc","ac > bc","ac - bc","(ac - bc) * 2","None of the above"],"a":[3,4],"topics":["COMPARATORS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa22-final/10","n":"10","t":"10. MSTs","b":[{"s":[{"p":"For the original weighted graph, Kruskal checks edges in this order: 0–4, 3–4, 2–3, 0–3, 0–2, 0–1, then possibly 1–2. See the PDF for the graph."}]},{"id":46,"l":[{"p":"10.1 Which isConnected checks return true?"}],"k":"sata","o":["0–4","3–4","2–3","0–3","0–2","0–1","1–2"],"a":[3,4],"topics":["MSTS"],"topicsBy":"site","x":"The staff also accepted 1–2 if the algorithm continues to test after reaching V−1 edges; the practice version stops there."},{"id":47,"l":[{"p":"10.2 Prim visit order from vertex 2"}],"k":"blank","a":["2, 3, 4, 0, 1"],"topics":["MSTS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa22-mt1","t":"Fall 2022 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1Y7iOyo4pFS2x-2BLNtLShtZSgrk13aKl/view","sol":"https://drive.google.com/file/d/1nxtpZZLtNfS3kYlUn2e8FukQipq140CU/view","topics":"fa22-mt1"},"p":[{"id":"61b-fa22-mt1/1","n":"1","t":"1. Residents & Friends (359 pts)","b":[{"s":[{"c":"public class Resident {\n    public String name;\n    private Resident[] friends;\n    public static int changes = 0;\n\n    public Resident(String n) {\n        this.name = n;\n        this.friends = null;\n    }\n    public Resident(String n, Resident[] friends) {\n        this.name = n;\n        this.friends = friends;\n    }\n\n    public void takeFriendsAndRenameOne(Resident a, String s) {\n        this.friends = a.friends;\n        this.friends[0].name = s;\n        Resident.changes = Resident.changes + 1;\n    }\n    public static void main(String[] args) {\n        Resident claire;\n        Resident ethan = new Resident(\"Ethan\");\n        Resident vidya = new Resident(\"Vidya\");\n        Resident nandini = new Resident(\"Nandini\");\n        Resident[] friends = {vidya, ethan, nandini};\n        vidya.takeFriendsAndRenameOne(new Resident(\"Jedi\", friends), \"Allen\");\n        Resident.takeFriendsAndRenameOne(nandini, \"Kyle\");\n        vidya.friends[0] = nandini;\n    }\n}","lang":"java"},{"p":"(a) If a line errors, the program continues as if it hadn’t run. (On the exam you drew the final box-and-pointer diagram.)"}]},{"id":1,"l":[{"p":"(a) Which line of main errors?"}],"k":"mc","o":["Resident claire;","Resident[] friends = {vidya, ethan, nandini};","vidya.takeFriendsAndRenameOne(new Resident(\"Jedi\", friends), \"Allen\");","Resident.takeFriendsAndRenameOne(nandini, \"Kyle\");","vidya.friends[0] = nandini;","None"],"a":3,"topics":["JAVA"],"x":"takeFriendsAndRenameOne isn’t static, so it can’t be called on the class.","part":"a"},{"id":2,"l":[{"p":"(a) At the end, what is vidya.name?"}],"k":"mc","o":["Ethan","Vidya","Nandini","Jedi","Allen","Kyle"],"a":4,"topics":["JAVA"],"x":"vidya takes Jedi’s friends array, whose element 0 is vidya herself, and renames it \"Allen\".","part":"a"},{"id":3,"l":[{"p":"(a) At the end, what is Resident.changes?"}],"k":"blank","a":["1"],"topics":["JAVA"],"part":"a"},{"id":4,"l":[{"p":"(a) At the end, vidya.friends is the same array as the local variable friends. What does it hold, in order?"}],"k":"mc","o":["nandini, ethan, nandini","vidya, ethan, nandini","Allen (vidya), ethan, Kyle","nandini, Jedi, nandini"],"a":0,"topics":["JAVA"],"x":"The last line sets element 0 of that shared array to nandini.","part":"a"},{"id":5,"l":[{"p":"(b) Instead of in Resident.java, main is run from a new file CS61B.java. Which line that ran successfully before will now error?"}],"k":"mc","o":["Resident claire;","Resident[] friends = new Resident[]{vidya, ethan, nandini};","vidya.takeFriendsAndRenameOne(new Resident(\"Jedi\", friends), \"Allen\");","vidya.friends[0] = nandini;","None of the above"],"a":3,"topics":["JAVA"],"x":"friends is private, so another class can’t access it.","part":"b"}],"topics":null},{"id":"61b-fa22-mt1/2","n":"2","t":"2. IntList Of (300 pts)","b":[{"s":[{"p":"A vararg (int... items) lets a method take any number of values, or an array. Write IntList.of, which returns an IntList of the given values: IntList.of(1, 2, 3, 4) is 1, then 2, then 3, then 4. IntList has int first, IntList rest and a constructor IntList(int f, IntList r)."},{"c":"public static IntList of(int... x) {\n    IntList L = ⟪a⟫;\n    for (int i = ⟪b⟫; ⟪c⟫; ⟪d⟫) {\n        ⟪e⟫;\n    }\n    return ⟪f⟫;\n}","lang":"java","f":{"a":"null","b":"x.length - 1","c":"i >= 0","d":"i--","e":"L = new IntList(x[i], L)","f":"L"}}]},{"id":6,"l":[{"p":"(a) IntList L = ____"}],"k":"blank","a":["null"],"topics":["JAVA","LINKED_LISTS"],"part":"a"},{"id":7,"l":[{"p":"(a) i starts at"}],"k":"blank","a":["x.length - 1"],"topics":["JAVA","LINKED_LISTS"],"part":"a"},{"id":8,"l":[{"p":"(a) Loop condition"}],"k":"blank","a":["i >= 0","i > -1"],"topics":["JAVA","LINKED_LISTS"],"part":"a"},{"id":9,"l":[{"p":"(a) Loop update"}],"k":"blank","a":["i--","i -= 1","i = i - 1"],"topics":["JAVA","LINKED_LISTS"],"part":"a"},{"id":10,"l":[{"p":"(a) Loop body"}],"k":"blank","a":["L = new IntList(x[i], L)"],"topics":["JAVA","LINKED_LISTS"],"part":"a"},{"id":11,"l":[{"p":"(a) return ____"}],"k":"blank","a":["L"],"topics":["JAVA","LINKED_LISTS"],"x":"Build from the back, putting each value in front of the list so far.","part":"a"}],"topics":null},{"id":"61b-fa22-mt1/3","n":"3","t":"3. IntList replaceValue (300 pts)","b":[{"s":[{"p":"replaceValue returns a copy of L with the value at position pos replaced by x: for 10, 11, 12, 13, 14, replaceValue(L, 100, 2) returns 10, 11, 100, 13, 14. It must not modify L, and the new list may not share any nodes with it. For an invalid pos (e.g. −1 or past the end) it returns an unchanged copy."},{"c":"public static IntList replaceValue(IntList L, int x, int pos) {\n    if (⟪a⟫) {\n        return ⟪b⟫;\n    }\n    if (⟪c⟫) {\n        return ⟪d⟫;\n    }\n    return ⟪e⟫;\n}","lang":"java","f":{"a":"L == null","b":"null","c":"pos == 0","d":"new IntList(x, replaceValue(L.rest, x, pos - 1))","e":"new IntList(L.first, replaceValue(L.rest, x, pos - 1))"}}]},{"id":12,"l":[{"p":"if (____)"}],"k":"blank","a":["L == null"],"topics":["LINKED_LISTS"]},{"id":13,"l":[{"p":"return ____"}],"k":"blank","a":["null"],"topics":["LINKED_LISTS"]},{"id":14,"l":[{"p":"if (____)"}],"k":"blank","a":["pos == 0"],"topics":["LINKED_LISTS"]},{"id":15,"l":[{"p":"return ____ (replace here)"}],"k":"blank","a":["new IntList(x, replaceValue(L.rest, x, pos - 1))"],"topics":["LINKED_LISTS"]},{"id":16,"l":[{"p":"return ____ (copy this node)"}],"k":"blank","a":["new IntList(L.first, replaceValue(L.rest, x, pos - 1))"],"topics":["LINKED_LISTS"],"x":"Keep copying past the replaced position too, so no node is shared. A negative pos simply never hits 0."}],"topics":null},{"id":"61b-fa22-mt1/4","n":"4","t":"4. JUnit (300 pts)","b":[{"s":[{"p":"Write tests showing evidence that replaceValue works: Test One checks the input isn’t modified and only the chosen value changes; Test Two checks the returned list shares no nodes with the original. assertEquals and assertNotEquals compare IntList contents; you may use IntList.of."},{"c":"@Test\npublic void testOne() {\n    IntList L = IntList.of(1, 2);\n    ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n}\n\n@Test\npublic void testTwo() {\n    IntList L = IntList.of(1, 2);\n    ⟪d⟫;\n    ⟪e⟫;\n    ⟪f⟫;\n}","lang":"java","f":{"a":"IntList w = IntList.replaceValue(L, 100, 1)","b":"assertEquals(IntList.of(1, 2), L)","c":"assertEquals(IntList.of(1, 100), w)","d":"IntList W = IntList.replaceValue(L, 100, -1)","e":"assertTrue(L != W)","f":"assertTrue(L.rest != W.rest)"}}]},{"id":17,"l":[{"p":"testOne, line 1"}],"k":"blank","a":["IntList w = IntList.replaceValue(L, 100, 1)"],"topics":["TESTING"]},{"id":18,"l":[{"p":"testOne, line 2"}],"k":"blank","a":["assertEquals(IntList.of(1, 2), L)"],"topics":["TESTING"]},{"id":19,"l":[{"p":"testOne, line 3"}],"k":"blank","a":["assertEquals(IntList.of(1, 100), w)"],"topics":["TESTING"]},{"id":20,"l":[{"p":"testTwo, line 1"}],"k":"blank","a":["IntList W = IntList.replaceValue(L, 100, -1)"],"topics":["TESTING"]},{"id":21,"l":[{"p":"testTwo, line 2"}],"k":"blank","a":["assertTrue(L != W)","assertFalse(L == W)"],"topics":["TESTING"]},{"id":22,"l":[{"p":"testTwo, line 3"}],"k":"blank","a":["assertTrue(L.rest != W.rest)","assertFalse(L.rest == W.rest)"],"topics":["TESTING"],"x":"Both node comparisons were needed for full credit; assertEquals compares contents, so it can’t show the nodes are new."}],"topics":null},{"id":"61b-fa22-mt1/5","n":"5","t":"5. Norinori (720 pts)","b":[{"s":[{"p":"Norinori is played on a grid divided into regions: shade dominoes (two adjacent cells) so that no two dominoes touch except at corners and every region has exactly two shaded cells. int[][] areas gives each cell’s region, and boolean[][] shaded a proposed solution. Both are rectangular with the same dimensions."},{"p":"(a) countAdjacentShaded returns how many cells orthogonally adjacent (up, left, down, right) to cell [i][j] are shaded; i and j are valid."},{"c":"int countAdjacentShaded(boolean[][] shaded, int i, int j) {\n    int result = 0;\n    if (⟪a⟫) {\n        result++;\n    }\n    if (⟪b⟫) {\n        result++;\n    }\n    if (⟪c⟫) {\n        result++;\n    }\n    if (⟪d⟫) {\n        result++;\n    }\n    return result;\n}","lang":"java","f":{"a":"i != 0 && shaded[i - 1][j]","b":"j != 0 && shaded[i][j - 1]","c":"i != shaded.length - 1 && shaded[i + 1][j]","d":"j != shaded[0].length - 1 && shaded[i][j + 1]"}}]},{"id":23,"l":[{"p":"(a) Up"}],"k":"blank","a":["i != 0 && shaded[i - 1][j]","i > 0 && shaded[i - 1][j]"],"topics":["ARRAYS"],"part":"a"},{"id":24,"l":[{"p":"(a) Left"}],"k":"blank","a":["j != 0 && shaded[i][j - 1]","j > 0 && shaded[i][j - 1]"],"topics":["ARRAYS"],"part":"a"},{"id":25,"l":[{"p":"(a) Down"}],"k":"blank","a":["i != shaded.length - 1 && shaded[i + 1][j]","i < shaded.length - 1 && shaded[i + 1][j]","i + 1 < shaded.length && shaded[i + 1][j]"],"topics":["ARRAYS"],"part":"a"},{"id":26,"l":[{"p":"(a) Right"}],"k":"blank","a":["j != shaded[0].length - 1 && shaded[i][j + 1]","j < shaded[0].length - 1 && shaded[i][j + 1]","j + 1 < shaded[i].length && shaded[i][j + 1]"],"topics":["ARRAYS"],"x":"Check bounds first; && stops before an out-of-range index.","part":"a"},{"s":[{"p":"(b) validNorinoriSolution returns whether shaded solves the puzzle with numAreas regions. Hint: shaded cells all form dominoes that touch only at corners exactly when every shaded cell has exactly one shaded orthogonal neighbor."},{"c":"boolean validNorinoriSolution(int[][] areas, boolean[][] shaded, int numAreas) {\n    int[] areaCounts = ⟪e⟫;\n    for (int i = 0; i < areas.length; i++) {\n        for (int j = 0; j < areas[i].length; j++) {\n            if (shaded[i][j]) {\n                if (⟪f⟫) {\n                    return false;\n                }\n                ⟪g⟫;\n            }\n        }\n    }\n    for (int c : areaCounts) {\n        if (⟪h⟫) {\n            return false;\n        }\n    }\n    return true;\n}","lang":"java","f":{"e":"new int[numAreas]","f":"countAdjacentShaded(shaded, i, j) != 1","g":"areaCounts[areas[i][j]] += 1","h":"c != 2"}}]},{"id":27,"l":[{"p":"(b) int[] areaCounts = ____"}],"k":"blank","a":["new int[numAreas]"],"topics":["ARRAYS"],"part":"b"},{"id":28,"l":[{"p":"(b) if (____) return false"}],"k":"blank","a":["countAdjacentShaded(shaded, i, j) != 1"],"topics":["ARRAYS"],"part":"b"},{"id":29,"l":[{"p":"(b) Then count it"}],"k":"blank","a":["areaCounts[areas[i][j]] += 1","areaCounts[areas[i][j]]++"],"topics":["ARRAYS"],"part":"b"},{"id":30,"l":[{"p":"(b) if (____) return false"}],"k":"blank","a":["c != 2"],"topics":["ARRAYS"],"part":"b"}],"topics":null},{"id":"61b-fa22-mt1/6","n":"6","t":"6. Ooh baby a triple!! (420 pts)","b":[{"s":[{"p":"A “triply” linked list (TLList) is a circular doubly linked list (left and right pointers) with one sentinel, where each TripleNode also has a next pointer to some other node. Let “alpha” be the node right of the sentinel. promoteNewAlphaDestroyOldAlpha removes alpha and moves alpha’s next node to the leftmost position (just right of the sentinel). No next pointers change."},{"c":"Before:  sentinel ⇄ 5 ⇄ 8 ⇄ 9 ⇄ 3 ⇄ 4 ⇄ (sentinel)      5.next is 3\nAfter:   sentinel ⇄ 3 ⇄ 8 ⇄ 9 ⇄ 4 ⇄ (sentinel)","lang":"txt"},{"c":"public void promoteNewAlphaDestroyOldAlpha() {\n    TripleNode oldAlpha = sentinel.right;\n    TripleNode newAlpha = oldAlpha.next;\n\n    newAlpha.left.right = ⟪a⟫;\n    newAlpha.⟪b⟫ = ⟪c⟫;\n\n    newAlpha.⟪d⟫ = oldAlpha.right;\n    oldAlpha.⟪e⟫ = ⟪f⟫;\n\n    ⟪g⟫;\n    ⟪h⟫;\n}","lang":"java","f":{"a":"newAlpha.right","b":"right.left","c":"newAlpha.left","d":"right","e":"right.left","f":"newAlpha","g":"newAlpha.left = sentinel","h":"sentinel.right = newAlpha"}}]},{"id":31,"l":[{"p":"(a) newAlpha.left.right = ____"}],"k":"blank","a":["newAlpha.right"],"topics":["LINKED_LISTS"],"part":"a"},{"id":32,"l":[{"p":"(b) newAlpha.____ (left side)"}],"k":"blank","a":["right.left"],"topics":["LINKED_LISTS"],"part":"b"},{"id":33,"l":[{"p":"(c) = ____"}],"k":"blank","a":["newAlpha.left"],"topics":["LINKED_LISTS"],"x":"These two lines unlink newAlpha from where it was.","part":"c"},{"id":34,"l":[{"p":"(d) newAlpha.____ = oldAlpha.right"}],"k":"blank","a":["right"],"topics":["LINKED_LISTS"],"part":"d"},{"id":35,"l":[{"p":"(e) oldAlpha.____ (left side)"}],"k":"blank","a":["right.left"],"topics":["LINKED_LISTS"],"part":"e"},{"id":36,"l":[{"p":"(f) = ____"}],"k":"blank","a":["newAlpha"],"topics":["LINKED_LISTS"],"part":"f"},{"id":37,"l":[{"p":"(g) Next line"}],"k":"blank","a":["newAlpha.left = sentinel"],"topics":["LINKED_LISTS"],"part":"g"},{"id":38,"l":[{"p":"(h) Last line"}],"k":"blank","a":["sentinel.right = newAlpha"],"topics":["LINKED_LISTS"],"x":"Then newAlpha takes oldAlpha’s place between the sentinel and oldAlpha’s right neighbor.","part":"h"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa22-mt2","t":"Fall 2022 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1-pPuHGuw0anqwnLh3nc_8z2Alqqcnpi5/view","sol":"https://drive.google.com/file/d/1EorWXul3vuZLpgpCkWUxFuOqn_Z5RaYP/view","topics":"fa22-mt2"},"p":[{"id":"61b-fa22-mt2/1","n":"1","t":"1. DisjointSets (250 pts)","b":[{"s":[{"p":"A correct implementation of the WeightedQuickUnion idea from lecture uses one array arr: a root’s value is its set’s weight, negated; any other element’s value is its parent."},{"c":"1: public void connect(int v1, int v2) {\n2:     int rootV1 = find(v1);\n3:     int rootV2 = find(v2);\n4:     if (rootV1 != rootV2) {\n5:         if (arr[rootV1] <= arr[rootV2]) {\n6:             arr[rootV1] += arr[rootV2]; // adds rootV2 tree size to rootV1\n7:             arr[rootV2] = rootV1;\n8:         } else {\n9:             arr[rootV2] += arr[rootV1]; // adds rootV1 tree size to rootV2\n10:            arr[rootV1] = rootV2;\n11:        }\n12:    }\n13: }","lang":"java"}]},{"id":1,"l":[{"p":"(a) Suppose we replace line 7 with arr[rootV2] = v1;. What are the potential negative consequences of this change?"}],"k":"sata","o":["If connect is called when v1 is not a root, later isConnected operations may be incorrect","If connect is called when v2 is not a root, later isConnected operations may be incorrect","Runtime for connect operations may be asymptotically worse than with the original line 7","Runtime for isConnected operations may be asymptotically worse than with the original line 7","None of the above"],"a":[2,3],"topics":["DISJOINT_SETS"],"x":"Hanging rootV2’s tree under v1 (possibly deep in rootV1’s tree) keeps the sets right but can make trees taller, so finds get slower.","part":"a"},{"id":2,"l":[{"p":"(b) With the same modified code and 6 items (valid arguments 0 to 5), what is the worst-case height of the WeightedQuickUnion tree (height is zero-indexed)?"}],"k":"mc","o":["0","1","2","3","4","5","10","11"],"a":5,"topics":["DISJOINT_SETS"],"x":"Attaching each new tree under the deepest node of the other can make a chain of all 6 items: height 5.","part":"b"}],"topics":null},{"id":"61b-fa22-mt2/2","n":"2","t":"2. EvenIterable (400 pts)","b":[{"s":[{"p":"We want an EvenIterable class whose constructor takes an Iterable and creates a new Iterable that only iterates over items in even-numbered positions. For example, this prints 0, then 10, then 20:"},{"c":"public static void main(String[] args) {\n    List<Integer> L = List.of(0, 1, 10, 2, 20, 3);\n    EvenIterable<Integer> evenIt = new EvenIterable<>(L);\n    for (int i : evenIt) {\n        System.out.println(i);\n    } // prints 0 then 10 then 20\n}","lang":"java"},{"p":"Fill in EvenIterable. The constructor may use linear space and time, and the code must not throw exceptions for the main method above."},{"c":"public class EvenIterable<T> implements Iterable<T> {\n    private ⟪a⟫;\n\n    public EvenIterable(Iterable<T> iterable) {\n        ⟪b⟫;\n        Iterator<T> it = iterable.⟪c⟫;\n        while (⟪d⟫) {\n            ⟪e⟫\n        }\n    }\n\n    public Iterator<T> iterator() {\n        return ⟪f⟫;\n    }\n}","lang":"java","f":{"a":"List<T> evens","b":"evens = new ArrayList<>()","c":"iterator()","d":"it.hasNext()","e":"evens.add(it.next());\nif (it.hasNext()) {\n    it.next();\n}","f":"evens.iterator()"}}]},{"id":3,"l":[{"p":"(a) private ____"}],"k":"blank","a":["List<T> evens","ArrayList<T> evens","LinkedList<T> evens"],"topics":["ITERATORS"],"part":"a"},{"id":4,"l":[{"p":"(b) First line of the constructor"}],"k":"blank","a":["evens = new ArrayList<>()","evens = new LinkedList<>()","evens = new ArrayList<T>()"],"topics":["ITERATORS"],"part":"b"},{"id":5,"l":[{"p":"(c) Iterator<T> it = iterable.____"}],"k":"blank","a":["iterator()"],"topics":["ITERATORS"],"part":"c"},{"id":6,"l":[{"p":"(d) while (____)"}],"k":"blank","a":["it.hasNext()"],"topics":["ITERATORS"],"part":"d"},{"id":7,"l":[{"p":"(e) The loop body (several lines)"}],"k":"blank","a":["evens.add(it.next());\nif (it.hasNext()) {\n    it.next();\n}","evens.add(it.next());\nif (it.hasNext()) it.next();","evens.add(it.next())\nif (it.hasNext()) {\nit.next()\n}"],"topics":["ITERATORS"],"part":"e"},{"id":8,"l":[{"p":"(f) iterator() returns"}],"k":"blank","a":["evens.iterator()"],"topics":["ITERATORS"],"x":"Copy every other item into a list, checking hasNext before skipping so an odd-length input doesn’t throw. (A boolean flag or counter also works.)","part":"f"}],"topics":null},{"id":"61b-fa22-mt2/3","n":"3","t":"3. HashSets (299 pts)","b":[{"s":[{"p":"HashableArrayList’s hash code is the sum of its items’ hash codes (an Integer’s hash code is itself). For example, [1, 2, 10] hashes to 13. The hash code is reduced to a bucket by modding by the number of buckets (4 here), the table never resizes, collisions are chained in a linked list, and ArrayList.equals compares contents."},{"c":"public class HashableArrayList<T> extends ArrayList<T> {\n    @Override\n    public int hashCode() {\n        int hc = 0;\n        for (int i = 0; i < size(); i += 1) {\n            hc += get(i).hashCode();\n        }\n        return hc;\n    }\n}\n\n1: HashSet<HashableArrayList<Integer>> set = new HashSet<>();\n2: set.add(new HashableArrayList<>(1, 2, 10));\n3: HashableArrayList<Integer> zeroOneTwo = new HashableArrayList<>(0, 1, 2);\n4: set.add(zeroOneTwo);\n5: set.add(new HashableArrayList<>(13));","lang":"java"},{"p":"(a) After lines 1–5, what does each bucket hold? Write the lists in chain order, separated by commas, e.g. [1, 2, 10], [13]; write [] for an empty bucket."}]},{"id":9,"l":[{"p":"(a) Bucket 0"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"part":"a"},{"id":10,"l":[{"p":"(a) Bucket 1"}],"k":"blank","a":["[1, 2, 10], [13]","[[1, 2, 10], [13]]"],"topics":["HASHING"],"part":"a"},{"id":11,"l":[{"p":"(a) Bucket 2"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"part":"a"},{"id":12,"l":[{"p":"(a) Bucket 3"}],"k":"blank","a":["[0, 1, 2]","[[0, 1, 2]]"],"topics":["HASHING"],"x":"[1, 2, 10] and [13] both hash to 13 → bucket 1; [0, 1, 2] hashes to 3 → bucket 3.","part":"a"},{"s":[{"p":"(b) Now we also run:"},{"c":"6: set.add(zeroOneTwo);\n7: zeroOneTwo.add(3);\n8: set.add(zeroOneTwo);","lang":"java"}]},{"id":13,"l":[{"p":"(b) After all 8 lines, which buckets hold a reference to the zeroOneTwo list?"}],"k":"sata","o":["Bucket 0","Bucket 1","Bucket 2","Bucket 3"],"a":[2,3],"topics":["HASHING"],"x":"Line 6 finds it already in bucket 3. Line 7 mutates it to [0, 1, 2, 3], which hashes to 6 → bucket 2, where line 8 finds nothing equal and adds it again. The same list is now in buckets 2 and 3.","part":"b"}],"topics":null},{"id":"61b-fa22-mt2/4","n":"4","t":"4. LLRBs (575 pts)","b":[{"s":[{"p":"Suppose we have the LLRB of integers below (links labeled red are red; the others are black):"},{"c":"            40\n       red /  \\\n         20    60\n        /  \\   / red\n      10   30 50","lang":"txt"}]},{"id":14,"l":[{"p":"(a) In the corresponding 2-3 tree, what keys are in the root? (Separate them with commas.)"}],"k":"blank","a":["20, 40","20 40","[20, 40]"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"a"},{"id":15,"l":[{"p":"(a) And in its rightmost leaf?"}],"k":"blank","a":["50, 60","50 60","[50, 60]"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"The 2-3 tree is [20 40] with children [10], [30] and [50 60].","part":"a"},{"id":16,"l":[{"p":"(b) Give all integers which, when inserted into the LLRB, result in a single rotateLeft and no further operations. Use inclusive brackets, e.g. [62, 64], [66, 68]; or write impossible."}],"k":"blank","a":["[11, 19], [31, 39]","[11,19],[31,39]","[11, 19] and [31, 39]"],"topics":["RED_BLACK_TREES"],"x":"A value that becomes the right child of a lone black node (10 or 30) leans right and needs exactly one rotateLeft: 11–19 or 31–39.","part":"b"},{"id":17,"l":[{"p":"(c) Give all integers which, when inserted, result in a single rotateRight and no further operations (or write impossible)."}],"k":"blank","a":["impossible","Impossible"],"topics":["RED_BLACK_TREES"],"x":"rotateRight is only needed for two left-leaning reds in a row, which always leaves a node with two red children, so a colorFlip follows.","part":"c"},{"id":18,"l":[{"p":"(d) At most, how many additional inserts can be performed without triggering any color flip? Don’t count the insert that causes the first color flip."}],"k":"blank","a":["2"],"topics":["RED_BLACK_TREES"],"x":"Only 10 and 30 can take one more key each without a 3-key 2-3 node forming.","part":"d"},{"id":19,"l":[{"p":"(e) True or false: if we insert enough values into the LLRB above, we will eventually get a colorFlip(40) operation."}],"k":"mc","o":["True","False"],"a":1,"topics":["RED_BLACK_TREES"],"x":"40 is a red child, and a node with a red link to its parent never gets two red children (that would be three keys in one 2-3 node), so 40 is never color-flipped.","part":"e"}],"topics":null},{"id":"61b-fa22-mt2/5","n":"5","t":"5. Tree Life (750 pts)","b":[{"s":[{"p":"Generalize the array representation of a complete binary tree to a complete trinary tree (three children per node). A trinary heap is represented by the array [-, 2, 4, 5, 12, 6, 7, 8, 11, 20], where the first position is unused."}]},{"id":20,"l":[{"p":"(a) What value is 8’s parent?"}],"k":"blank","a":["4"],"topics":["BSTS","HEAPS"],"part":"a"},{"id":21,"l":[{"p":"(b) In a pre-order traversal of this tree, what are the last 3 values traversed, in order?"}],"k":"blank","a":["11, 20, 12","11 20 12","[11, 20, 12]"],"topics":["BSTS","HEAPS","TREE_TRAVERSALS"],"part":"b"},{"id":22,"l":[{"p":"(c) In a post-order traversal, what are the first 3 values traversed, in order?"}],"k":"blank","a":["6, 7, 8","6 7 8","[6, 7, 8]"],"topics":["BSTS","HEAPS","TREE_TRAVERSALS"],"part":"c"},{"id":23,"l":[{"p":"(d) A DFS graph traversal starting from node 12, breaking ties by going to the smallest node first: give the whole DFS pre-order."}],"k":"blank","a":["12, 2, 4, 6, 7, 8, 5, 11, 20","12 2 4 6 7 8 5 11 20","[12, 2, 4, 6, 7, 8, 5, 11, 20]"],"topics":["BSTS","HEAPS","TREE_TRAVERSALS"],"x":"The tree is 2 → (4, 5, 12); 4 → (6, 7, 8); 5 → (11, 20). From 12 the only neighbor is 2; then 4 and its children, then 5 and its children.","part":"d"},{"id":24,"l":[{"p":"(e) Replace 20 with some arbitrary value X so the trinary heap is still valid (heaps may contain duplicates). Using the standard heap deletion algorithm, where can X end up after one deleteMin? Select all that apply."}],"k":"sata","o":["X might not be in the heap at all after deleteMin.","In the root position previously occupied by the 2.","In the position previously occupied by the 4.","In the position previously occupied by the 5.","In the position previously occupied by the 12.","In the position previously occupied by the 6.","In the position previously occupied by the 7.","In the position previously occupied by the 8.","In the position previously occupied by the 11.","In the same position, i.e. X might not move."],"a":[2,5],"topics":["BSTS","HEAPS"],"x":"X (≥ 5) moves to the root and sinks below the smallest child each time: first to 4’s old spot, then possibly to 6’s.","part":"e"}],"topics":null},{"id":"61b-fa22-mt2/6","n":"6","t":"6. Asymptotics and ArrayDeques (400 pts)","b":[{"id":25,"l":[{"p":"(a) Suppose R(N) = 11 + 22 + 33 + 44 + … + N; e.g. if N = 55, then R(N) = 165. Which of the following are true?"}],"k":"sata","o":["R(N) ∈ O(1)","R(N) ∈ O(N)","R(N) ∈ O(N²)","R(N) ∈ O(N³)","R(N) ∈ Θ(1)","R(N) ∈ Θ(N)","R(N) ∈ Θ(N²)","R(N) ∈ Θ(N³)"],"a":[2,3,6],"topics":["ASYMPTOTICS"],"x":"About N/11 terms averaging N/2: Θ(N²).","part":"a"},{"s":[{"p":"(b) An ArrayDeque resizes, when too full, by adding 11 new entries. What is the order of growth of this code’s runtime?"},{"c":"ArrayDeque<Integer> ad = new ArrayDeque<>();\nfor (int i = 0; i < N; i += 1) {\n    ad.add(i);\n}","lang":"java"}]},{"id":26,"l":[{"p":"(b) Runtime"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS"],"x":"A resize every 11 adds copies the whole array: 11 + 22 + … + N = Θ(N²).","part":"b"},{"id":27,"l":[{"p":"(c) Let f(x) = x if x is a power of 2, and 1 otherwise, and Z(N) = f(1) + f(2) + … + f(N). For example, Z(8) = 19. Which are true about Z(N)?"}],"k":"sata","o":["Z(N) ∈ O(1)","Z(N) ∈ O(N)","Z(N) ∈ O(N²)","Z(N) ∈ O(N³)","Z(N) ∈ Θ(1)","Z(N) ∈ Θ(N)","Z(N) ∈ Θ(N²)","Z(N) ∈ Θ(N³)"],"a":[1,2,3,5],"topics":["ASYMPTOTICS"],"x":"The powers of two sum to less than 2N, and the rest add at most N: Θ(N).","part":"c"},{"id":28,"l":[{"p":"(d) The same code, but the ArrayDeque doubles the size of the array when too full. Runtime?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)"],"a":2,"topics":["ASYMPTOTICS"],"x":"Total copying is 1 + 2 + 4 + … + N < 2N.","part":"d"}],"topics":null},{"id":"61b-fa22-mt2/7","n":"7","t":"7. Asymptotics and Dynamic Method Selection (575 pts)","b":[{"s":[{"c":"public class Cheese {\n    public String cheese;\n    public Cheese(String cheese) {\n        this.cheese = cheese;\n    }\n\n    // String's substring runs in Θ(length of the substring)\n    public Cheese slice(int from, int to) {\n        return new Cheese(cheese.substring(from, to));\n    }\n\n    // String's length runs in Θ(1)\n    public int weight() {\n        return cheese.length();\n    }\n}\n\npublic class Parmesan extends Cheese {\n    public Parmesan(String cheese) {\n        super(cheese);\n    }\n    @Override\n    public int weight() {\n        int w = super.weight();\n        if (w <= 1) {\n            return w;\n        }\n        Cheese mine = slice(0, w / 2);\n        Cheese yours = slice(w / 2, w);\n        return mine.weight() + yours.weight();\n    }\n}","lang":"java"},{"p":"The static type of slice(int from, int to) is Cheese, its return type. The dynamic type of the returned object is whatever was actually instantiated."}]},{"id":29,"l":[{"p":"(a) What is the tightest runtime of Parmesan’s weight in terms of N, the length of the underlying String?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)"],"a":2,"topics":["INHERITANCE","DMS","ASYMPTOTICS"],"x":"slice returns plain Cheeses, whose weight is Θ(1); the two substrings cost Θ(N) in total.","part":"a"},{"s":[{"c":"// (b): added to Parmesan\n@Override\npublic Cheese slice(int from, int to) {\n    Cheese b = super.slice(from, to);\n    return b;\n}","lang":"java"}]},{"id":30,"l":[{"p":"(b) With this override, what is the runtime of weight?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)"],"a":2,"topics":["INHERITANCE","DMS","ASYMPTOTICS"],"x":"super.slice still makes a plain Cheese.","part":"b"},{"s":[{"c":"// (c): instead of (b)\n@Override\npublic Cheese slice(int from, int to) {\n    String sayCheese = cheese.substring(from, to);\n    Parmesan c = new Cheese(sayCheese);\n    return c;\n}","lang":"java"}]},{"id":31,"l":[{"p":"(c) This method results in an error. What kind?"}],"k":"mc","o":["Runtime error","Compile-time error","Infinite loop"],"a":1,"topics":["INHERITANCE","DMS"],"x":"A Cheese can’t be assigned to a Parmesan variable without a cast.","part":"c"},{"s":[{"c":"// (d): instead of (b) and (c)\n@Override\npublic Cheese slice(int from, int to) {\n    String sayCheese = cheese.substring(from, to);\n    Parmesan d = (Parmesan) new Cheese(sayCheese);\n    return d;\n}","lang":"java"}]},{"id":32,"l":[{"p":"(d) This method results in an error. What kind?"}],"k":"mc","o":["Runtime error","Compile-time error","Infinite loop"],"a":0,"topics":["INHERITANCE","DMS"],"x":"The cast compiles, but the object is really a Cheese: ClassCastException.","part":"d"},{"s":[{"c":"// (e): instead of (b), (c) and (d)\n@Override\npublic Cheese slice(int from, int to) {\n    String sayCheese = cheese.substring(from, to);\n    Parmesan e = new Parmesan(sayCheese);\n    return e;\n}","lang":"java"}]},{"id":33,"l":[{"p":"(e) This doesn’t error. What is the runtime of weight now?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)"],"a":3,"topics":["INHERITANCE","DMS","ASYMPTOTICS"],"x":"Now the halves are Parmesans, so weight recurses on both: Θ(N) substring work per level, log N levels.","part":"e"}],"topics":null},{"id":"61b-fa22-mt2/8","n":"8","t":"8. Data Structures Design (750 pts)","b":[{"s":[{"p":"Add a removeEvery(int x) operation to the Proj 1A LinkedListDeque (hard-coded to integers), which removes all instances of x. Methods must run in O(k + log N) time on average, where k is the number of x’s in the deque and N its size. Naive Θ(N) solutions get no credit."},{"c":"public class LinkedListDeque {\n    private Node sentinel;\n    private int size;\n    public void addFirst(int item) { … }\n    public int removeFirst() { … }\n    public int get(int index) { … }\n    …\n}","lang":"java"}]},{"id":34,"l":[{"p":"(a) Which single additional instance variable makes this possible? (The exam asked you to write one, then describe addFirst and removeEvery.)"}],"k":"mc","o":["TreeMap<Integer, ArrayList<Node>> tmap","TreeMap<Integer, Integer> counts","ArrayList<Integer> items","int[] positions"],"a":0,"topics":["LINKED_LISTS","ADTS"],"x":"addFirst: after creating node n, add it to tmap’s list for x (making a new list if x isn’t there yet). removeEvery(x): remove x from tmap and unlink every Node in the returned list from the deque. Each node is found directly, so that’s O(k) plus the O(log N) TreeMap lookup.","part":"a"}],"topics":null}],"by":["Hug"]},{"id":"61b-fa23-final","t":"Fall 2023 Final","src":{"exam":"https://drive.google.com/file/d/1VcTEqbaK-BpuYej3w4so27tFLaSm2Rin/view","sol":"https://drive.google.com/file/d/1DkfpFEoKFBGTkkzDcCnD9vuHRVRws7R7/view","topics":"fa23-final"},"p":[{"id":"61b-fa23-final/1","n":"1","t":"1. Final Curry","b":[{"s":[{"p":"For each statement, answer true or false."}]},{"id":1,"l":[{"p":"(a) With more than |V|-1 edges and a unique heaviest edge, that edge cannot be in any MST."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) If a graph has more than |V|-1 edges and two edges have equal weight, it must have multiple MSTs."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"b"},{"id":3,"l":[{"p":"(c) Negate all weights and run an MST algorithm to obtain a maximum spanning tree."}],"k":"blank","a":["true"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"c"},{"id":4,"l":[{"p":"(d) An MST gives the shortest path between any pair of vertices."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"d"},{"id":5,"l":[{"p":"(e) MSD radix sort remains correct with heapsort on each digit."}],"k":"blank","a":["true"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"e"},{"id":6,"l":[{"p":"(f) LSD radix sort remains correct with heapsort on each digit."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"f"},{"id":7,"l":[{"p":"(g) Reversing a min-heap array always gives a max-heap representation."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"g"},{"id":8,"l":[{"p":"(h) With an admissible consistent heuristic, A* can visit more vertices than Dijkstra to reach a destination."}],"k":"blank","a":["false"],"topics":["MSTS","RADIX_SORTS","HEAPS","SHORTEST_PATHS"],"topicsBy":"site","part":"h"}],"topics":null},{"id":"61b-fa23-final/2","n":"2","t":"2. Next Episode","b":[{"s":[{"p":"(a) Destructively reorder a linked list so even-indexed nodes come first in their original order, then odd-indexed nodes in their original order."},{"c":"Episode reverseFaroShuffle(Episode head) {\n  if (head == null) return null;\n  Episode even = head;\n  Episode odd = head.next;\n  Episode oddHead = odd;\n  while (odd != null && odd.next != null) {\n    even.next = odd.next;\n    even = even.next;\n    odd.next = even.next;\n    odd = odd.next;\n  }\n  even.next = oddHead;\n  return head;\n}","lang":"java"}]},{"id":9,"l":[{"p":"Loop condition"}],"k":"blank","a":["odd != null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":10,"l":[{"p":"Loop condition continuation"}],"k":"blank","a":["odd.next != null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":11,"l":[{"p":"Link even node to next even"}],"k":"blank","a":["odd.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":12,"l":[{"p":"Advance even cursor"}],"k":"blank","a":["even.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":13,"l":[{"p":"Link odd node to next odd"}],"k":"blank","a":["even.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":14,"l":[{"p":"Advance odd cursor"}],"k":"blank","a":["odd.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":15,"l":[{"p":"Attach odd list after even list"}],"k":"blank","a":["oddHead"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"s":[{"p":"(b) For each statement, give CE, RE, OK, or its printed output. The classes use the overloads shown in the code."},{"c":"Rating rating = new Rating();\nAudienceRating audRating = new AudienceRating();\nProfessionalRating profRating = new ProfessionalRating();\nRating ratingProf = new ProfessionalRating();\nRating[] ratings = new Rating[10];\nratings[1].judgeRating(ratingProf);\nrating.judgeRating(audRating);\n((ProfessionalRating) rating).judgeRating(rating);\nrating.judgeRating((ProfessionalRating) ratingProf);","lang":"java"}]},{"id":16,"l":[{"p":"Line 1: create Rating"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":17,"l":[{"p":"Line 2: create AudienceRating"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":18,"l":[{"p":"Line 3: create ProfessionalRating"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":19,"l":[{"p":"Line 4: assign ProfessionalRating to Rating"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":20,"l":[{"p":"Line 5: create Rating array"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":21,"l":[{"p":"Line 6: ratings[1].judgeRating(ratingProf)"}],"k":"blank","a":["RE"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":22,"l":[{"p":"Line 7: rating.judgeRating(audRating)"}],"k":"blank","a":["True"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":23,"l":[{"p":"Line 8: cast rating to ProfessionalRating and call"}],"k":"blank","a":["RE"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":24,"l":[{"p":"Line 9: call overload with cast argument"}],"k":"blank","a":["Very True"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa23-final/3","n":"3","t":"3. Asymptotics","b":[{"s":[{"c":"void q1(int N) {\n  for (int i=1; i<N; i+=1)\n    for (int j=1; j<N; j*=2) {}\n}\nvoid q2(int N) {\n  if (N<=1) return;\n  if (randomBitIsEven()) { for (int i=0;i<N/2;i++) {} q2(N-1); }\n  else q2(N-4);\n}\ndouble q3(double N) {\n  if (N<=10) return 1;\n  double C=N; while (C>1) C/=2;\n  return q3(Math.sqrt(N));\n}\ndouble q4(double N) {\n  if (N<=10) return 1;\n  double C=N; while (C>1) C/=2;\n  return q4(Math.sqrt(N)) + q4(Math.sqrt(N));\n}","lang":"java"}]},{"id":25,"l":[{"p":"(a) q1 runtime"}],"k":"blank","a":["Theta(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":26,"l":[{"p":"(b) q2 best case"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":27,"l":[{"p":"(b) q2 worst case"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":28,"l":[{"p":"(c) q3 runtime"}],"k":"blank","a":["Theta(log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":29,"l":[{"p":"(d)(1) q4 recursion tree height h"}],"k":"blank","a":["Theta(log log N)"],"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","part":"d"},{"id":30,"l":[{"p":"(d)(2) q4 runtime in terms of N and h"}],"k":"blank","a":["Theta(h log N)"],"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-fa23-final/4","n":"4","t":"4. Evil Sets","b":[{"s":[{"p":"(a) For each array, entries are parent pointers or negative root sizes. Select all valid weighted quick-union states without path compression."}]},{"id":31,"l":[{"p":"Which states are valid?"}],"k":"sata","o":["(i) [-1,-1,-1,-1,-1,-1]","(ii) [-5,0,3,0,0,0]","(iii) [-6,5,0,0,0,1]","(iv) [0,-6,1,0,0,0]","None of the above"],"a":[0],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"s":[{"p":"(b) Initial parent array by index 0..11: [-3,-2,0,7,9,1,2,-5,3,-2,8,3]."}]},{"id":32,"l":[{"p":"(b)(1) Are indices 0 and 9 connected?"}],"k":"blank","a":["false"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":33,"l":[{"p":"(b)(2) Are indices 10 and 11 connected?"}],"k":"blank","a":["true"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":34,"l":[{"p":"(b)(3) Are the sets containing 6 and 5 the same size?"}],"k":"blank","a":["false"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"s":[{"p":"Using WQUPC, with ties choosing the smaller root:"}]},{"id":35,"l":[{"p":"(b)(4) Parent/size array after union(10,5), starting from the given array"}],"k":"blank","a":["-3,7,0,7,9,1,2,-7,7,-2,7,3"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":36,"l":[{"p":"(b)(5) Minimum number of union operations to fully connect and reduce height to 1"}],"k":"blank","a":["4"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-fa23-final/5","n":"5","t":"5. Bushy Trees","b":[{"s":[{"p":"(a) LLRB diagram: root 313 has red left link to 100 and black right link to unknown ?. Node 100 has black children 10 and 188; 10 has black children 8 and 61, and 61 has red child 47. Node 188 has red left child 164 and black right child 189; 164 has black children 162 and 184; 162 has red child 161. The unknown node has dotted (unknown-color) children 625 and 928; 625 has dotted children 448 and 644; 448 has black child 347; 928 has dotted child 646."}]},{"id":37,"l":[{"p":"(a)(1) Value of the unknown node"}],"k":"blank","a":["645"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":38,"l":[{"p":"(a)(2) Which nodes must have a red edge to their parent?"}],"k":"sata","o":["347","448","625","644","646","None of the above"],"a":[0,2,4],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":39,"l":[{"p":"(a)(3) Insert 88: rotateLeft count"}],"k":"blank","a":["1"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":40,"l":[{"p":"(a)(3) Insert 88: rotateRight count"}],"k":"blank","a":["0"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":41,"l":[{"p":"(a)(3) Insert 88: colorFlip count"}],"k":"blank","a":["1"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":42,"l":[{"p":"(a)(4) Insert 170: rotateLeft count"}],"k":"blank","a":["0"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":43,"l":[{"p":"(a)(4) Insert 170: rotateRight count"}],"k":"blank","a":["0"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":44,"l":[{"p":"(a)(4) Insert 170: colorFlip count"}],"k":"blank","a":["0"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) Cookie-house tree: root 1; children 4 and 3; 4 has children 0 and 6; 3 has children 2 and 5; 6 has children 7 and 10; 5 has right child 9; 7 has left child 8."}]},{"id":45,"l":[{"p":"(b)(1) Total cookies sold by preorder fish on six houses"}],"k":"blank","a":["26"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":46,"l":[{"p":"(b)(2) Total cookies sold by right-left-root chips on six houses"}],"k":"blank","a":["37"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":47,"l":[{"p":"(c) Which four lines produce the specified first 12 sales?"}],"k":"mc","o":["sellCookies(house); fishDoubleDip(house.left); fishDoubleDip(house.right); sellCookies(house);","sellCookies(house); fishDoubleDip(house.right); fishDoubleDip(house.left); sellCookies(house);","fishDoubleDip(house.left); sellCookies(house); fishDoubleDip(house.right); sellCookies(house);","sellCookies(house); fishDoubleDip(house.left); sellCookies(house); fishDoubleDip(house.right);"],"a":0,"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-fa23-final/6","n":"6","t":"6. Snack Scores","b":[{"s":[{"p":"HashSet buckets use Math.floorMod(hashCode, bucketCount). Current four buckets: 0→Cookies; 1→Chocolates→Fudge; 2→Eggnog; 3→Candy Canes→Chestnuts."}]},{"id":48,"l":[{"p":"(a) Bucket for new snack with hashCode -1, without resize"}],"k":"blank","a":["3"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":49,"l":[{"p":"(b) Which changed Candy Canes ratings make lookup fail?"}],"k":"sata","o":["-19","-13","0","10","15","19","None of the above"],"a":[0,2,3],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":50,"l":[{"p":"(c) Which hashCodes change bucket index when capacity doubles from 4 to 8?"}],"k":"sata","o":["-9","-8","-3","0","5","11","None of the above"],"a":[0,2,4],"topics":["HASHING"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-fa23-final/7","n":"7","t":"7. Priority Queue","b":[{"id":51,"l":[{"p":"(a) Which arrays can be max-heaps? (index 0 is unused.)"}],"k":"sata","o":["[-,7,6,1,4,5,2,3]","[-,1,7,6,5,4,3,2]","[-,7,3,6,2,1,5,4]","[-,7,4,6,5,3,2,1]","[-,7,6,3,1,2,4,5]","[-,7,6,5,4,3,2,1]"],"a":[2,5],"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) MiddleHeap keeps left as a max-heap and right as a min-heap. left holds the lower half and is equal in size to right or has one extra item."},{"c":"int deleteMiddle() {\n  int k = left.deleteMax();\n  if (left.size() < right.size()) left.insert(right.deleteMin());\n  return k;\n}\nvoid insert(int k) {\n  if (left.isEmpty()) { left.insert(k); return; }\n  if (k < left.findMax()) left.insert(k);\n  else right.insert(k);\n  if (left.size() > right.size()+1) right.insert(left.deleteMax());\n  if (left.size() < right.size()) left.insert(right.deleteMin());\n}","lang":"java"}]},{"id":52,"l":[{"p":"(b) deleteMiddle: restore balance"}],"k":"blank","a":["left.insert(right.deleteMin())"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":53,"l":[{"p":"(b) insert: initialize first item"}],"k":"blank","a":["left.insert(k);"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":54,"l":[{"p":"(b) insert: put lower-half item in left"}],"k":"blank","a":["left.insert(k);"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":55,"l":[{"p":"(b) insert: put upper-half item in right"}],"k":"blank","a":["right.insert(k);"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":56,"l":[{"p":"(b) If left too large, move its maximum"}],"k":"blank","a":["right.size() + 1"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":57,"l":[{"p":"(b) Move left maximum into right"}],"k":"blank","a":["right.insert(left.deleteMax());"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":58,"l":[{"p":"(b) If left too small, compare sizes"}],"k":"blank","a":["left.size() < right.size()"],"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":59,"l":[{"p":"(b) Move right minimum into left"}],"k":"blank","a":["left.insert(right.deleteMin());"],"topics":["HEAPS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-fa23-final/8","n":"8","t":"8. Lots of Graphite","b":[{"s":[{"p":"Directed weighted edges: S→A(1), S→C(6), S→B(7), A→D(1), A→C(4), D→C(2), D→E(1), C→B(2), C→E(2), B→E(2). Alphabetical tie-breaking. A* heuristics: S=7,A=6,B=2,C=4,D=6,E=0."}]},{"id":60,"l":[{"p":"(a) Dijkstra visit order from S?"}],"k":"mc","o":["S,A,D,C,E,B","S,A,C,B,D,E","S,A,D,E,C,B","S,A,B,C,D,E","S,A,D,C,B,E","None"],"a":2,"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":61,"l":[{"p":"(b) Which are valid topological orders?"}],"k":"sata","o":["S,A,D,C,E,B","S,A,C,B,D,E","S,A,D,E,C,B","S,A,B,C,D,E","S,A,D,C,B,E","None"],"a":[4],"topics":["TOPOLOGICAL_SORT"],"topicsBy":"site","part":"b"},{"id":62,"l":[{"p":"(c) A* visit order from S to E?"}],"k":"mc","o":["S,A,D,E,B","S,A,B,E","S,A,D,E,C,B","S,A,D,C,B,E","S,A,D,E","None"],"a":4,"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-fa23-final/9","n":"9","t":"9. World Wide Web","b":[{"s":[{"p":"Undirected graph edge weights: AB=1, AD=3, BC=4, CD=7, DF=12, BE=4, EG=3, BG=1, BH=4, GH=5, CI=4, HI=4, IJ=10."}]},{"id":63,"l":[{"p":"(a) Prim from C, edges in order (include given BC)"}],"k":"blank","a":["BC,AB,BG,AD,EG,BH,CI,IJ,DF"],"topics":["MSTS"],"topicsBy":"site","part":"a"},{"id":64,"l":[{"p":"(b) Which edges could be 5th in Kruskal with unknown tie-break?"}],"k":"sata","o":["AB","AD","BC","BE","BG","BH","CD","CI","DF","GH","HI","IJ"],"a":[2,5,7,10],"topics":["MSTS"],"topicsBy":"site","part":"b"},{"id":65,"l":[{"p":"(c) If all weights are halved, every original MST remains an MST: T/F"}],"k":"blank","a":["true"],"topics":["MSTS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-fa23-final/10","n":"10","t":"10. Sorting Out the Situation","b":[{"s":[{"c":"void beben(int[] arr) {\n  for (int i=arr.length-1; i>=0; i--) {\n    for (int j=0; j<i; j++) {\n      if (arr[j] >= arr[j+1]) swap(arr,j,j+1);\n    }\n  }\n}","lang":"java"}]},{"id":66,"l":[{"p":"(a)(1) Beben sorts in place: T/F"}],"k":"blank","a":["true"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":67,"l":[{"p":"(a)(2) Beben is stable: T/F"}],"k":"blank","a":["false"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":68,"l":[{"p":"(a)(3) Insertion sort makes strictly fewer swaps than Beben: Always/Sometimes/Never"}],"k":"blank","a":["Sometimes"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":69,"l":[{"p":"(a)(4) Selection sort makes strictly fewer swaps than Beben: Always/Sometimes/Never"}],"k":"blank","a":["Sometimes"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":70,"l":[{"p":"(b)(1) Sort a million random distinct numbers without extra memory. Best choice?"}],"k":"mc","o":["Quicksort with Hoare partition","Mergesort","Insertion sort","Selection sort","Counting sort"],"a":0,"topics":["SORTING","COMPARISON_SORTS"],"topicsBy":"site","part":"b"},{"id":71,"l":[{"p":"(b)(2) One random swap in an otherwise sorted array. Best choice?"}],"k":"mc","o":["Quicksort with Hoare partition","Mergesort","Insertion sort","Selection sort","Counting sort"],"a":2,"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":72,"l":[{"p":"(b)(3) Stable sort of integer ratings 1–5. Best choice?"}],"k":"mc","o":["Quicksort with Hoare partition","Mergesort","Insertion sort","Selection sort","Counting sort"],"a":4,"topics":["SORTING","RADIX_SORTS"],"topicsBy":"site","part":"b"},{"id":73,"l":[{"p":"(b)(4) Sort an already sorted list. Best choice?"}],"k":"mc","o":["Quicksort with Hoare partition","Mergesort","Insertion sort","Selection sort","Counting sort"],"a":2,"topics":["SORTING"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-fa23-final/11","n":"11","t":"11. Belt of Heapolyta","b":[{"s":[{"p":"Belts have distinct weights and one magic belt whose comparison is inverted against all other belts. The two lightest and two heaviest belts are nonmagic."},{"p":"(a) Input belts: [3*,6,2,5,1,0,4,7]. Match each algorithm to its output label: a) [3*,0,1,2,4,5,6,7]; b) [0,1,2,4,5,6,7,3*]; c) [6,3*,0,1,2,4,5,7]; d) [0,3*,1,2,4,5,6,7]; e) [4,5,6,7,3*,0,1,2]; f) [0,1,6,3*,2,4,5,7]; g) [0,1,2,3*,4,5,6,7]; h) does not terminate; i) none."}]},{"id":74,"l":[{"p":"(a)(1) Insertion Sort output label"}],"k":"blank","a":["c"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":75,"l":[{"p":"(a)(2) 3-way Quicksort, first item pivot, output label"}],"k":"blank","a":["e"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":76,"l":[{"p":"(a)(3) Hoare Quicksort, first item pivot, output label"}],"k":"blank","a":["e"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":77,"l":[{"p":"(a)(4) Beben sort output label"}],"k":"blank","a":["c"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":78,"l":[{"p":"(b) One valid nine-belt input giving at least 16 inversions among nonmagic belts after 3-way quicksort"}],"k":"blank","a":["5*,1,2,3,4,6,7,8,9"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Find the magic belt once, remove it, heap-sort the nonmagic belts, then scan the sorted list and insert the magic belt at the position determined by comparing it to existing belts."}]},{"id":79,"l":[{"p":"(c) First step"}],"k":"blank","a":["Call findMagicBelt once and remove that belt"],"topics":["SORTING"],"topicsBy":"site","part":"c"},{"id":80,"l":[{"p":"(c) Sort remaining belts"}],"k":"blank","a":["Run heapSort on the nonmagic belts"],"topics":["SORTING","HEAPS"],"topicsBy":"site","part":"c"},{"id":81,"l":[{"p":"(c) Reinsert magic belt"}],"k":"blank","a":["Scan and insert before the first belt lighter than the magic belt"],"topics":["SORTING"],"topicsBy":"site","part":"c"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa23-mt1","t":"Fall 2023 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1t65JX1RtaEoSyU05hi0b9i7aPMmqLrDV/view","sol":"https://drive.google.com/file/d/1XJOuVk9IXIbzNlNUuVBodUEHQQYrMSDy/view","topics":"fa23-mt1"},"p":[{"id":"61b-fa23-mt1/1","n":"1","t":"1. Hot Curry (10.0 pts)","b":[{"id":1,"l":[{"p":"(a) In Java, every if condition must also have an else clause."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"part":"a"},{"id":2,"l":[{"p":"(b) System.out.println returns a String."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"part":"b"},{"id":3,"l":[{"p":"(c) An instance method with no arguments can call static methods."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"part":"c"},{"id":4,"l":[{"p":"(d) An int[] of length 1 behaves exactly the same as an int when passed into a method."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"x":"The method gets a reference to the same array, so changes to it are visible to the caller.","part":"d"},{"id":5,"l":[{"p":"(e) You can call a private method from a public method in the same class."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"part":"e"},{"id":6,"l":[{"p":"(f) You can call a public method from a private method in the same class."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"part":"f"},{"id":7,"l":[{"p":"(g) Passing all tests always means your code is failproof."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"part":"g"},{"id":8,"l":[{"p":"(h) An interface can extend a class."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"part":"h"},{"id":9,"l":[{"p":"(i) You can always cast a class to its parent class and/or parent interface(s)."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"part":"i"},{"id":10,"l":[{"p":"(j) A class can be both Comparable and Iterable."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"part":"j"},{"id":11,"l":[{"p":"(k) What is the result of new Dog() == new Dog(), assuming there are no errors?"}],"k":"mc","o":["true","false"],"a":1,"topics":["JAVA"],"x":"Two separate objects.","part":"k"},{"s":[{"c":"class Ch<E> {\n    static E se() {\n        return null;\n    }\n}","lang":"java"}]},{"id":12,"l":[{"p":"(l) The code above compiles."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA"],"x":"A static method belongs to no instance, so the class’s type parameter E means nothing there.","part":"l"}],"topics":null},{"id":"61b-fa23-mt1/2","n":"2","t":"2. Java Cat-astrophe (15.0 pts)","b":[{"s":[{"c":"public class Cat {\n    public void scratch(Cat c) { System.out.println(\"scratchy scratch\"); }\n    public void meow(Cat c) { System.out.println(\"meow\"); }\n}\n\npublic class Siamese extends Cat {\n    public void scratch(Cat c) { System.out.println(\"big scratch\"); }\n    public void scratch(Siamese s) { System.out.println(\"fat scratch\"); }\n    public void scratch(Calico c) { System.out.println(\"fighting scratch\"); }\n    public void meow(Cat c) { System.out.println(\"purr\"); }\n}\n\npublic class Calico extends Cat {\n    public void scratch(Cat c) { System.out.println(\"regular scratch\"); }\n    public void scratch(Calico c) { System.out.println(\"light scratch\"); }\n    public void meow(Siamese s) { System.out.println(\"meep\"); }\n}","lang":"java"},{"p":"For each line, write CE for a compile error, RE for a runtime error, OK if it runs but prints nothing, or what it prints. If a line errors, assume the program continues as if it weren’t there."},{"c":"Cat midori = new Cat();                  // a\nCat tofu = new Siamese();                // b\nCalico fish = new Cat();                 // c\nCalico cliff = new Calico();             // d\nCalico minou = new Siamese();            // e\nSiamese luna = new Siamese();            // f\ncliff.meow(luna);                        // g\n((Cat) cliff).meow(luna);                // h\nmidori.meow(luna);                       // i\n((Cat) cliff).scratch(tofu);             // j\nCat.scratch(tofu);                       // k\nmidori.scratch(cliff);                   // l\nmidori.scratch((Calico) tofu);           // m\ncliff.meow(midori);                      // n\ntofu.scratch(midori);                    // o","lang":"java"}]},{"id":13,"l":[{"p":"(a)"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":14,"l":[{"p":"(b)"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"b"},{"id":15,"l":[{"p":"(c)"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"part":"c"},{"id":16,"l":[{"p":"(d)"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"d"},{"id":17,"l":[{"p":"(e)"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"A Siamese isn’t a Calico.","part":"e"},{"id":18,"l":[{"p":"(f)"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"f"},{"id":19,"l":[{"p":"(g)"}],"k":"blank","a":["meep"],"topics":["INHERITANCE","DMS"],"x":"Calico’s meow(Siamese) is the best match for a Siamese argument.","part":"g"},{"id":20,"l":[{"p":"(h)"}],"k":"blank","a":["meow"],"topics":["INHERITANCE","DMS"],"x":"Through a Cat reference only meow(Cat) is visible, and Calico doesn’t override that one.","part":"h"},{"id":21,"l":[{"p":"(i)"}],"k":"blank","a":["meow"],"topics":["INHERITANCE","DMS"],"part":"i"},{"id":22,"l":[{"p":"(j)"}],"k":"blank","a":["regular scratch"],"topics":["INHERITANCE","DMS"],"x":"scratch(Cat) is chosen at compile time; cliff is a Calico at runtime.","part":"j"},{"id":23,"l":[{"p":"(k)"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"scratch isn’t static.","part":"k"},{"id":24,"l":[{"p":"(l)"}],"k":"blank","a":["scratchy scratch"],"topics":["INHERITANCE","DMS"],"part":"l"},{"id":25,"l":[{"p":"(m)"}],"k":"blank","a":["RE"],"topics":["INHERITANCE","DMS"],"x":"tofu is a Siamese, so the cast to Calico fails at runtime.","part":"m"},{"id":26,"l":[{"p":"(n)"}],"k":"blank","a":["meow"],"topics":["INHERITANCE","DMS"],"part":"n"},{"id":27,"l":[{"p":"(o)"}],"k":"blank","a":["big scratch"],"topics":["INHERITANCE","DMS"],"x":"tofu’s static type is Cat, so scratch(Cat) is chosen; Siamese overrides it.","part":"o"}],"topics":null},{"id":"61b-fa23-mt1/3","n":"3","t":"3. Printer Problems (25.0 pts)","b":[{"s":[{"p":"A PrintJob has List<String> pages and int numCopies (both positive). A Printer is an iterator: sendJob adds a job to the back of its jobs deque; next returns the next page, printing numCopies collated copies of the first job (pages \"1\", \"2\", \"3\" with 4 copies print 123123123123) and removing the job when done; hasNext says whether a page is left. You may use getFirst and getLast on the Deque."},{"c":"public class Printer implements Iterator<String> {\n    public Deque<PrintJob> jobs;\n    public int currPage;\n    public int currCopy;\n\n    public Printer() {\n        this.jobs = new ArrayDeque<PrintJob>();\n        ⟪a⟫;\n        ⟪b⟫;\n    }\n\n    public void sendJob(PrintJob job) {\n        ⟪c⟫;\n    }\n\n    @Override\n    public boolean hasNext() {\n        return !this.jobs.isEmpty();\n    }\n\n    @Override\n    public String next() {\n        if (⟪d⟫) {\n            throw new NoSuchElementException(\"No more pages to print.\");\n        }\n        PrintJob currJob = ⟪e⟫;\n        String nextPage = ⟪f⟫;\n        this.currPage = ⟪g⟫;\n        if (currPage == currJob.pages.size()) {\n            ⟪h⟫;\n            ⟪i⟫;\n        }\n        if (currCopy == currJob.numCopies) {\n            ⟪j⟫;\n            ⟪k⟫;\n            ⟪l⟫;\n        }\n        return nextPage;\n    }\n}","lang":"java","f":{"a":"this.currPage = 0","b":"this.currCopy = 0","c":"this.jobs.addLast(job)","d":"!this.hasNext()","e":"this.jobs.getFirst()","f":"currJob.pages.get(currPage)","g":"this.currPage + 1","h":"this.currCopy += 1","i":"this.currPage = 0","j":"this.jobs.removeFirst()","k":"this.currCopy = 0","l":"this.currPage = 0"}}]},{"id":28,"l":[{"p":"(a) Constructor, first blank"}],"k":"blank","a":["this.currPage = 0","currPage = 0","this.currCopy = 0","currCopy = 0"],"topics":["ITERATORS"],"part":"a"},{"id":29,"l":[{"p":"(a) Constructor, second blank"}],"k":"blank","a":["this.currCopy = 0","currCopy = 0","this.currPage = 0","currPage = 0"],"topics":["ITERATORS"],"part":"a"},{"id":30,"l":[{"p":"(a) sendJob"}],"k":"blank","a":["this.jobs.addLast(job)","jobs.addLast(job)"],"topics":["ITERATORS"],"part":"a"},{"id":31,"l":[{"p":"(a) next: if (____) throw"}],"k":"blank","a":["!this.hasNext()","!hasNext()","this.jobs.isEmpty()","jobs.isEmpty()"],"topics":["ITERATORS"],"part":"a"},{"id":32,"l":[{"p":"(a) PrintJob currJob = ____"}],"k":"blank","a":["this.jobs.getFirst()","jobs.getFirst()"],"topics":["ITERATORS"],"part":"a"},{"id":33,"l":[{"p":"(a) String nextPage = ____"}],"k":"blank","a":["currJob.pages.get(currPage)"],"topics":["ITERATORS"],"part":"a"},{"id":34,"l":[{"p":"(a) this.currPage = ____"}],"k":"blank","a":["this.currPage + 1","currPage + 1"],"topics":["ITERATORS"],"part":"a"},{"id":35,"l":[{"p":"(a) Finished a copy, first line"}],"k":"blank","a":["this.currCopy += 1","currCopy += 1","currCopy++"],"topics":["ITERATORS"],"part":"a"},{"id":36,"l":[{"p":"(a) Finished a copy, second line"}],"k":"blank","a":["this.currPage = 0","currPage = 0"],"topics":["ITERATORS"],"part":"a"},{"id":37,"l":[{"p":"(a) Finished the job, first line"}],"k":"blank","a":["this.jobs.removeFirst()","jobs.removeFirst()"],"topics":["ITERATORS"],"part":"a"},{"id":38,"l":[{"p":"(a) Finished the job, second line"}],"k":"blank","a":["this.currCopy = 0","currCopy = 0"],"topics":["ITERATORS"],"part":"a"},{"id":39,"l":[{"p":"(a) Finished the job, third line"}],"k":"blank","a":["this.currPage = 0","currPage = 0"],"topics":["ITERATORS"],"x":"this. is optional throughout; resetting currPage here is redundant after the copy block already did it.","part":"a"},{"s":[{"p":"(b) Partway through printing (at least one page printed, at least one left), you update a PrintJob pj you kept a reference to, between calls to next and hasNext. Then you call next until hasNext returns false. Select all that could happen."}]},{"id":40,"l":[{"p":"(b) i. You add finitely many pages to the end (pj.pages.addLast(...))"}],"k":"sata","o":["The PrintJob finishes as if the job hadn’t been updated","The PrintJob finishes as if the job had been updated from the start","The PrintJob finishes, but some copies look like the old version, and some copies look like the new version","The PrintJob never finishes","The Printer crashes"],"a":[1,2],"topics":["ITERATORS"],"part":"b"},{"id":41,"l":[{"p":"(b) ii. You remove some (but not all) pages from the end (pj.pages.removeLast())"}],"k":"sata","o":["The PrintJob finishes as if the job hadn’t been updated","The PrintJob finishes as if the job had been updated from the start","The PrintJob finishes, but some copies look like the old version, and some copies look like the new version","The PrintJob never finishes","The Printer crashes"],"a":[1,2,4],"topics":["ITERATORS"],"x":"If currPage is already past the new last page, get(currPage) throws.","part":"b"},{"id":42,"l":[{"p":"(b) iii. You increase the number of copies (pj.numCopies += 100)"}],"k":"sata","o":["The PrintJob finishes as if the job hadn’t been updated","The PrintJob finishes as if the job had been updated from the start","The PrintJob never finishes","The Printer crashes"],"a":[1],"topics":["ITERATORS"],"part":"b"},{"id":43,"l":[{"p":"(b) iv. You decrease the number of copies (pj.numCopies -= 100), still positive"}],"k":"sata","o":["The PrintJob finishes as if the job hadn’t been updated","The PrintJob finishes as if the job had been updated from the start","The PrintJob never finishes","The Printer crashes"],"a":[1,2],"topics":["ITERATORS"],"x":"If currCopy has already passed the new numCopies, currCopy == numCopies is never true again.","part":"b"}],"topics":null},{"id":"61b-fa23-mt1/4","n":"4","t":"4. Card Deck (30.0 pts)","b":[{"s":[{"c":"public class CardDeck {\n    public class Card {\n        public static final String[] SUITS = new String[]{\"Hearts\", \"Clubs\", \"Diamonds\", \"Spades\"};\n        public static final String[] RANKS = new String[]{\"Ace\", \"2\", \"3\", \"4\", \"5\",\n            \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\"};\n        public int suitIndex;\n        public int rankIndex;\n\n        public Card(int suitIndex, int rankIndex) { ... }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj instanceof Card card) {\n                return this.suitIndex == card.suitIndex && this.rankIndex == card.rankIndex;\n            }\n            return false;\n        }\n    }\n\n    public List<Card> cards;\n\n    public CardDeck() {\n        cards = new ArrayList<>();\n        createDeck();\n    }\n\n    private void createDeck() { /* part a */ }\n    public void faroShuffle() { /* part b */ }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (obj instanceof CardDeck cardDeck) {\n            return this.cards.equals(cardDeck.cards);\n        }\n        return false;\n    }\n}","lang":"java"},{"p":"(a) createDeck adds 52 unique cards, one per rank and suit, in any order."},{"c":"private void createDeck() {\n    ⟪a⟫\n        ⟪b⟫\n            ⟪c⟫;\n        }\n    }\n}","lang":"java","f":{"a":"for (int i = 0; i < Card.SUITS.length; i++) {","b":"for (int j = 0; j < Card.RANKS.length; j++) {","c":"cards.add(new Card(i, j))"}}]},{"id":44,"l":[{"p":"(a) Outer loop"}],"k":"blank","a":["for (int i = 0; i < Card.SUITS.length; i++) {","for (int i = 0; i < 4; i++) {","for (int i = 0; i < Card.SUITS.length; i += 1) {"],"topics":["LISTS"],"part":"a"},{"id":45,"l":[{"p":"(a) Inner loop"}],"k":"blank","a":["for (int j = 0; j < Card.RANKS.length; j++) {","for (int j = 0; j < 13; j++) {","for (int j = 0; j < Card.RANKS.length; j += 1) {"],"topics":["LISTS"],"part":"a"},{"id":46,"l":[{"p":"(a) Body"}],"k":"blank","a":["cards.add(new Card(i, j))","this.cards.add(new Card(i, j))"],"topics":["LISTS"],"part":"a"},{"s":[{"p":"(b) A faro shuffle splits the deck into two equal halves and interweaves them perfectly: [1, 2, 3, 4, 5, 6] becomes [1, 4, 2, 5, 3, 6]. There are always 52 cards."},{"c":"public void faroShuffle() {\n    List<Card> cardCopy = new ArrayList<>(cards);\n    for (int i = 0; i < cards.size() / 2; i += 1) {\n        this.cards.set(⟪d⟫);\n        this.cards.set(⟪e⟫);\n    }\n}","lang":"java","f":{"d":"2 * i, cardCopy.get(i)","e":"2 * i + 1, cardCopy.get(i + this.cards.size() / 2)"}}]},{"id":47,"l":[{"p":"(b) First set(____)"}],"k":"blank","a":["2 * i, cardCopy.get(i)"],"topics":["LISTS"],"part":"b"},{"id":48,"l":[{"p":"(b) Second set(____)"}],"k":"blank","a":["2 * i + 1, cardCopy.get(i + this.cards.size() / 2)","2 * i + 1, cardCopy.get(i + cards.size() / 2)","2 * i + 1, cardCopy.get(i + 26)"],"topics":["LISTS"],"part":"b"},{"s":[{"p":"(c) How many iterations does each while loop run? (8 faro shuffles return a 52-card deck to its original order.) Write inf if it never ends."},{"c":"// (i)\nCardDeck deck = new CardDeck();\nCardDeck deck2 = deck;\ndeck2.faroShuffle();\nwhile (deck2 != deck) {\n    deck2.faroShuffle();\n}\n\n// (ii)\nCardDeck deck = new CardDeck();\nCardDeck deck2 = deck;\ndeck2.faroShuffle();\nwhile (!deck2.equals(deck)) {\n    deck2.faroShuffle();\n}\n\n// (iii)\nCardDeck deck = new CardDeck();\nCardDeck deck2 = new CardDeck();\ndeck2.faroShuffle();\nwhile (deck2 != deck) {\n    deck2.faroShuffle();\n}\n\n// (iv)\nCardDeck deck = new CardDeck();\nCardDeck deck2 = new CardDeck();\ndeck2.faroShuffle();\nwhile (!deck2.equals(deck)) {\n    deck2.faroShuffle();\n}","lang":"java"}]},{"id":49,"l":[{"p":"(c) (i)"}],"k":"blank","a":["0"],"topics":["JAVA","LISTS","EQUALS"],"x":"deck2 and deck are the same object.","part":"c"},{"id":50,"l":[{"p":"(c) (ii)"}],"k":"blank","a":["0"],"topics":["JAVA","LISTS","EQUALS"],"part":"c"},{"id":51,"l":[{"p":"(c) (iii)"}],"k":"blank","a":["inf","infinite","∞"],"topics":["JAVA","LISTS","EQUALS"],"x":"Two separate objects are never ==.","part":"c"},{"id":52,"l":[{"p":"(c) (iv)"}],"k":"blank","a":["7"],"topics":["JAVA","LISTS","EQUALS"],"x":"After 1 shuffle before the loop, 7 more make 8.","part":"c"},{"s":[{"p":"(d) A comparator for “higher card wins”: Ace = 1, Jack = 11, Queen = 12, King = 13, numbers as themselves; equal ranks are compared by suit, Hearts < Clubs < Diamonds < Spades."},{"c":"class SimpleGameComparator implements Comparator<Card> {\n    @Override\n    public int compare(Card c1, Card c2) {\n        if ([1]) {\n            return [2];\n        }\n        return [3];\n    }\n}","lang":"java"}]},{"id":53,"l":[{"p":"(d) [1]"}],"k":"mc","o":["c1.rankIndex == c2.rankIndex","c1.suitIndex == c2.suitIndex"],"a":0,"topics":["COMPARATORS"],"part":"d"},{"id":54,"l":[{"p":"(d) [2]"}],"k":"mc","o":["c1.rankIndex - c2.rankIndex","c1.suitIndex - c2.suitIndex","c2.rankIndex - c1.rankIndex","c2.suitIndex - c1.suitIndex"],"a":1,"topics":["COMPARATORS"],"part":"d"},{"id":55,"l":[{"p":"(d) [3]"}],"k":"mc","o":["c1.rankIndex - c2.rankIndex","c1.suitIndex - c2.suitIndex","c2.rankIndex - c1.rankIndex","c2.suitIndex - c1.suitIndex"],"a":0,"topics":["COMPARATORS"],"part":"d"}],"topics":null},{"id":"61b-fa23-mt1/5","n":"5","t":"5. I Signed an NDA (20.0 pts)","b":[{"s":[{"p":"(a) NDArray stores D-dimensional data of width W (a W × W × … × W array). D ≥ 1 and W ≥ 1."},{"c":"public class NDArray {\n    public int value;\n    public int dimension;\n    public NDArray[] arr;\n\n    public NDArray(int D, int W) {\n        dimension = D;\n        if (⟪a⟫) { return; }\n        arr = ⟪b⟫;\n        for (⟪c⟫) {\n            ⟪d⟫;\n        }\n    }\n}","lang":"java","f":{"a":"dimension == 0","b":"new NDArray[W]","c":"int i = 0; i < W; i++","d":"arr[i] = new NDArray(D - 1, W)"}}]},{"id":56,"l":[{"p":"(a) if (____) return"}],"k":"blank","a":["dimension == 0","D == 0"],"topics":["JAVA","ARRAYS"],"part":"a"},{"id":57,"l":[{"p":"(a) arr = ____"}],"k":"blank","a":["new NDArray[W]"],"topics":["JAVA","ARRAYS"],"part":"a"},{"id":58,"l":[{"p":"(a) The loop header"}],"k":"blank","a":["int i = 0; i < W; i++","int i = 0; i < W; i += 1","int i = 0; i < arr.length; i++"],"topics":["JAVA","ARRAYS"],"part":"a"},{"id":59,"l":[{"p":"(a) The loop body"}],"k":"blank","a":["arr[i] = new NDArray(D - 1, W)"],"topics":["JAVA","ARRAYS"],"part":"a"},{"s":[{"p":"(b) get returns the item at List<Integer> coords; e.g. for a 2-D NDArray representing [[5, 4], [1, 9]], get(List.of(0, 1)) returns 4. Hint: List’s subList."},{"c":"public int get(List<Integer> coords) {\n    if (coords.size() != dimension) {\n        throw new IllegalArgumentException();\n    }\n    if (⟪e⟫) {\n        ⟪f⟫;\n    }\n    int index = coords.get(0);\n    return ⟪g⟫;\n}","lang":"java","f":{"e":"coords.isEmpty()","f":"return this.value","g":"this.arr[index].get(coords.subList(1, coords.size()))"}}]},{"id":60,"l":[{"p":"(b) The base case: if (____)"}],"k":"blank","a":["coords.isEmpty()","coords.size() == 0","dimension == 0","coords.size() == 1"],"topics":["JAVA","ARRAYS"],"part":"b"},{"id":61,"l":[{"p":"(b) Its body"}],"k":"blank","a":["return this.value","return value","return arr[coords.get(0)].value"],"topics":["JAVA","ARRAYS"],"x":"With coords.size() == 1, return arr[coords.get(0)].value instead.","part":"b"},{"id":62,"l":[{"p":"(b) return ____"}],"k":"blank","a":["this.arr[index].get(coords.subList(1, coords.size()))","arr[index].get(coords.subList(1, coords.size()))"],"topics":["JAVA","ARRAYS"],"part":"b"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa23-mt2","t":"Fall 2023 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1rT67b4j7ek12SHC1d5LwLVV085QZpRCW/view","sol":"https://drive.google.com/file/d/1VgzKzWCXydHqPp7oieUdwBDfxnr_F1EI/view","topics":"fa23-mt2"},"p":[{"id":"61b-fa23-mt2/1","n":"1","t":"1. Ghost Curry (16.0 pts)","b":[{"id":1,"l":[{"p":"(a) Say f(n) ∈ Θ(g(n)), and g(n) is strictly positive and increasing. Mark all that are always true."}],"k":"sata","o":["f(n) ∈ O(g(n))","f(n) ∈ Ω(g(n))","f(n) ∈ O(log(g(n)))","f(n) ∈ Ω(log(g(n)))","f(n) ∈ O(n · g(n))","f(n) ∈ Ω(n · g(n))","None of the above"],"a":[0,1,3,4],"topics":["ASYMPTOTICS"],"x":"Θ gives both O and Ω of g. g grows at least as fast as log g, so f ∈ Ω(log g), and f ∈ O(n·g) because n·g grows at least as fast as g. The other two bounds are too tight.","part":"a"},{"id":2,"l":[{"p":"(b) A data structure with a time complexity of Θ(1) for all its operations always runs faster on all inputs than a data structure with a time complexity of Θ(log n) for the same operations."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"Asymptotic bounds hide constants: for small inputs the Θ(log n) structure can be faster.","part":"b"},{"id":3,"l":[{"p":"(c) A fully connected disjoint set without path compression has find() run in Θ(1)."}],"k":"mc","o":["True","False"],"a":1,"topics":["DISJOINT_SETS"],"x":"Without path compression, nodes can be several links below the root, so find walks up a tree.","part":"c"},{"id":4,"l":[{"p":"(d) Inserting into a Binary Search Tree is O(log N), where N is the number of elements."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS","TREE_TRAVERSALS"],"x":"A spindly BST makes insertion Θ(N).","part":"d"},{"id":5,"l":[{"p":"(e) A 2-3 tree can contain a node with 2 elements as the root."}],"k":"mc","o":["True","False"],"a":0,"topics":["B_TREES"],"part":"e"},{"id":6,"l":[{"p":"(f) Our HashMap runtime analyses assume hashCode runs in constant time."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS","HASHING"],"part":"f"},{"id":7,"l":[{"p":"(g) In Hibbard deletion, you can replace the deleted node with either the right-most node in the left subtree or the left-most node in the right subtree, if they exist."}],"k":"mc","o":["True","False"],"a":0,"topics":["RED_BLACK_TREES"],"x":"Those are the predecessor and successor.","part":"g"},{"id":8,"l":[{"p":"(h) Two objects are always equal if they have the same hash, assuming the hashCode() function is valid."}],"k":"mc","o":["True","False"],"a":1,"topics":["HASHING"],"x":"Different objects can collide.","part":"h"},{"id":9,"l":[{"p":"(i) Two objects are always unequal if they have different hashes, assuming the hashCode() function is valid."}],"k":"mc","o":["True","False"],"a":0,"topics":["HASHING"],"x":"Equal objects must have equal hashes, so different hashes mean unequal objects.","part":"i"},{"id":10,"l":[{"p":"(j) The asymptotic runtime for all methods of a 2-3-4 tree is the same as for a 2-3 tree."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS","B_TREES"],"part":"j"},{"s":[{"p":"(k) Consider this class:"},{"c":"public class Ben {\n    public int x;\n    public int y;\n    public int z;\n\n    @Override\n    public boolean equals(Object o) {\n        if (o instanceof Ben b) {\n            return this.x == b.x && this.y == b.y;\n        }\n        return false;\n    }\n\n    @Override\n    public int hashCode() { return /* answer choices here */ }\n}","lang":"java"}]},{"id":11,"l":[{"p":"(k) Select all of the valid hashCode implementations for the class Ben."}],"k":"sata","o":["0;","x + y + z;","x * 625 - y;","z;","None of the above"],"a":[0,2],"topics":["HASHING"],"x":"equals ignores z, so two equal Bens can have different z. A valid hashCode may only use x and y (or nothing).","part":"k"},{"id":12,"l":[{"p":"(l) You are implementing an undo feature in a graphic design program: users should be able to undo the most recent action they performed. Which data structure is ideal for managing the history of actions?"}],"k":"mc","o":["ArrayList","LLRB Tree","Heap","HashMap","Stack"],"a":4,"topics":["ADTS"],"part":"l"},{"id":13,"l":[{"p":"(m) You are developing a chat application that shows messages in chronological order. Messages can be inserted after the newest message, and older messages may be deleted or modified regardless of timestamp. Which data structure is best suited for maintaining messages?"}],"k":"mc","o":["ArrayList","LLRB Tree","Heap","HashMap","Stack"],"a":1,"topics":["ADTS"],"also":[0],"x":"LLRB Tree was the intended answer; staff also gave full credit for ArrayList.","part":"m"},{"id":14,"l":[{"p":"(n) You are building a weather application that stores information about cities, including their names and weather conditions. Users should be able to quickly look up weather data for a city by its name. Which data structure is the most appropriate?"}],"k":"mc","o":["ArrayList","LLRB Tree","Heap","HashMap","Stack"],"a":3,"topics":["ADTS"],"part":"n"}],"topics":null},{"id":"61b-fa23-mt2/2","n":"2","t":"2. Tree Questions (16.0 pts)","b":[{"s":[{"p":"(a) Given the following 2-3 tree:"},{"c":"             [36]\n           /      \\\n        [8]        [74]\n       /   \\      /    \\\n    [3]  [21 29] [52 61] [77 100]","lang":"txt"}]},{"id":15,"l":[{"p":"(a) 1. There is an order of insertions that creates this 2-3 tree such that 36 was inserted after 3."}],"k":"mc","o":["True","False"],"a":0,"topics":["B_TREES"],"part":"a"},{"s":[{"p":"(a) 2. We insert 53, 23, 44, 47 into the tree above, in that order."}]},{"id":16,"l":[{"p":"(a) 2(a) What element(s) are in the root node? (Separate them with commas.)"}],"k":"blank","a":["36, 53","36 53"],"topics":["B_TREES"],"part":"a"},{"id":17,"l":[{"p":"(a) 2(b) How many nodes are there with 2 elements?"}],"k":"blank","a":["3"],"topics":["B_TREES"],"x":"53 makes [52 53 61], which splits and pushes 53 up: [53 74]. 23 joins [21 23 29], pushing 23 up to [8 23]. 44 and 47 make [44 47 52], pushing 47 up to [47 53 74], which splits and pushes 53 to the root: [36 53]. The 2-element nodes are then [8 23], [36 53] and [77 100].","part":"a"},{"s":[{"p":"(b) Inserting 25 into the LLRB below (red links labeled red) gives the tree on the right. Which operations return it to a valid LLRB?"},{"c":"     10                          10\n    /  \\                        /  \\\n   5    20         →           5    20\n       / red                       /  \\\n     15                   red    15    25   red","lang":"txt"}]},{"id":18,"l":[{"p":"(b) Operation 1"}],"k":"mc","o":["rotateLeft(5)","rotateLeft(10)","rotateLeft(15)","rotateLeft(20)","rotateRight(10)","rotateRight(20)","colorFlip(10)","colorFlip(20)","colorFlip(25)","None (no more operations)"],"a":7,"topics":["RED_BLACK_TREES"],"part":"b"},{"id":19,"l":[{"p":"(b) Operation 2"}],"k":"mc","o":["rotateLeft(5)","rotateLeft(10)","rotateLeft(15)","rotateLeft(20)","rotateRight(10)","rotateRight(20)","colorFlip(10)","colorFlip(20)","colorFlip(25)","None (no more operations)"],"a":1,"topics":["RED_BLACK_TREES"],"part":"b"},{"id":20,"l":[{"p":"(b) Operation 3"}],"k":"mc","o":["rotateLeft(5)","rotateLeft(10)","rotateLeft(15)","rotateLeft(20)","rotateRight(10)","rotateRight(20)","colorFlip(10)","colorFlip(20)","colorFlip(25)","None (no more operations)"],"a":9,"topics":["RED_BLACK_TREES"],"x":"20 has two red children, so colorFlip(20). That makes 10–20 a right-leaning red link, so rotateLeft(10). Nothing else is needed.","part":"b"},{"s":[{"p":"(c) Each tree is written node(left, right); a * marks a node whose link to its parent is red. Which are not well-formed LLRBs?"},{"c":"(i)   64(47(4(*1, -), 63), 140(121, 160))\n(ii)  133(*87(63(*16, -), 90), 169(*156, -))\n(iii) 88(*11(10, 49(*17, 77)), 183)\n(iv)  10(7, 72(*108(52, -), 152))\n(v)   12(*11(10, -), 15)","lang":"txt"}]},{"id":21,"l":[{"p":"(c) Select all that are not well-formed LLRBs."}],"k":"sata","o":["(i)","(ii)","(iii)","(iv)","(v)"],"a":[2,3,4],"topics":["RED_BLACK_TREES"],"x":"(iii): root-to-null paths have different numbers of black links (via 49–77 there are two). (iv): 108 is the left child of 72, which breaks the BST order. (v): the path through 11 to 10 has two black links, the path to 15 only one.","part":"c"},{"s":[{"p":"(d) Now a 2-3-4 tree. Its root holds three values (X X X) and has four children A, B, C, D (values not shown)."}]},{"id":22,"l":[{"p":"(d) 1. What is the maximum number of values that can be added without causing the node with 3 Xs to split?"}],"k":"blank","a":["8"],"topics":["B_TREES"],"x":"Each of the four children can take two more values before it splits and pushes a value up: 4 × 2 = 8.","part":"d"},{"id":23,"l":[{"p":"(d) 2. What is the minimum number of values that can be added to cause the node with 3 Xs to split?"}],"k":"blank","a":["3"],"topics":["B_TREES"],"x":"Three values into one child fill it to four and split it, pushing a value into the full root, which splits.","part":"d"}],"topics":null},{"id":"61b-fa23-mt2/3","n":"3","t":"3. A Hole-y Cheese (18.0 pts)","b":[{"s":[{"p":"Sam has a cheese that is infinitely wide but of limited height, with many circular holes. Can you go from the bottom surface to the top? Two intersecting holes connect, and a hole that touches the bottom or top surface connects to that surface."},{"c":"public class Hole {\n    // ...implementation not shown...\n\n    // Checks whether this hole intersects with the passed in hole.\n    public boolean intersectsWithHole(Hole other) { ... }\n\n    // Checks whether this hole intersects with the bottom.\n    public boolean intersectsWithBottom() { ... }\n\n    // Checks whether this hole intersects with the top.\n    public boolean intersectsWithTop() { ... }\n}","lang":"java"},{"p":"Complete topBottomConnected, which returns whether it is possible to go from the top to the bottom, given a List of Hole objects."},{"c":"public boolean topBottomConnected(List<Hole> holes) {\n    WeightedQuickUnion q = new WeightedQuickUnion(holes.size() + 2);\n    int bottom = holes.size();\n    int top = holes.size() + 1;\n\n    for (⟪a⟫) {\n        if (⟪b⟫) {\n            ⟪c⟫;\n        }\n        if (⟪d⟫) {\n            ⟪e⟫;\n        }\n    }\n    for (int i = 0; i < holes.size(); i++) {\n        for (⟪f⟫) {\n            if (⟪g⟫) {\n                ⟪h⟫;\n            }\n        }\n    }\n    return ⟪i⟫;\n}","lang":"java","f":{"a":"int i = 0; i < holes.size(); i++","b":"holes.get(i).intersectsWithBottom()","c":"q.union(i, bottom)","d":"holes.get(i).intersectsWithTop()","e":"q.union(i, top)","f":"int j = i + 1; j < holes.size(); j++","g":"holes.get(i).intersectsWithHole(holes.get(j))","h":"q.union(i, j)","i":"q.isConnected(bottom, top)"}}]},{"id":24,"l":[{"p":"(a) The first loop’s header"}],"k":"blank","a":["int i = 0; i < holes.size(); i++","int i = 0; i < holes.size(); i += 1"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"a"},{"id":25,"l":[{"p":"(b) The first if"}],"k":"blank","a":["holes.get(i).intersectsWithBottom()"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"b"},{"id":26,"l":[{"p":"(c) Inside it"}],"k":"blank","a":["q.union(i, bottom)","q.union(bottom, i)"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"c"},{"id":27,"l":[{"p":"(d) The second if"}],"k":"blank","a":["holes.get(i).intersectsWithTop()"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"d"},{"id":28,"l":[{"p":"(e) Inside it"}],"k":"blank","a":["q.union(i, top)","q.union(top, i)"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"e"},{"id":29,"l":[{"p":"(f) The inner loop’s header"}],"k":"blank","a":["int j = i + 1; j < holes.size(); j++","int j = i + 1; j < holes.size(); j += 1","int j = 0; j < holes.size(); j++","int j = 0; j < holes.size(); j += 1"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"f"},{"id":30,"l":[{"p":"(g) The inner if"}],"k":"blank","a":["holes.get(i).intersectsWithHole(holes.get(j))","holes.get(j).intersectsWithHole(holes.get(i))"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"g"},{"id":31,"l":[{"p":"(h) Inside it"}],"k":"blank","a":["q.union(i, j)","q.union(j, i)"],"topics":["DISJOINT_SETS","PERCOLATION"],"part":"h"},{"id":32,"l":[{"p":"(i) return ____"}],"k":"blank","a":["q.isConnected(bottom, top)","q.isConnected(top, bottom)"],"topics":["DISJOINT_SETS","PERCOLATION"],"x":"Give each hole an index and add two extra items for the bottom and top surfaces. Union holes with the surfaces they touch and with each other; the cheese is passable exactly when bottom and top end up connected.","part":"i"}],"topics":null},{"id":"61b-fa23-mt2/4","n":"4","t":"4. Heaps of Fun (16.0 pts)","b":[{"s":[{"p":"1. A binary MinHeap contains A, B, C and D, with A < B < C < D."}]},{"id":33,"l":[{"p":"1(a) Which element(s) could possibly be the root?"}],"k":"sata","o":["A","B","C","D","None of the above"],"a":[0],"topics":["HEAPS"]},{"id":34,"l":[{"p":"1(b) Which element(s) could possibly be one edge away from the root?"}],"k":"sata","o":["A","B","C","D","None of the above"],"a":[1,2,3],"topics":["HEAPS"]},{"id":35,"l":[{"p":"1(c) Which element(s) could possibly be two edges away from the root?"}],"k":"sata","o":["A","B","C","D","None of the above"],"a":[2,3],"topics":["HEAPS"],"x":"With 4 items there is one node two edges down, and it needs two smaller ancestors, so only C or D."},{"s":[{"p":"2. A MinHeap holds the numbers 1, 2, …, 1023, stored in an array with index 0 empty."}]},{"id":36,"l":[{"p":"2(a) What is the minimum index that could contain 8?"}],"k":"blank","a":["2"],"topics":["HEAPS"]},{"id":37,"l":[{"p":"2(a) And the maximum index?"}],"k":"blank","a":["255"],"topics":["HEAPS"],"x":"8 needs at least its ancestors to be smaller: at most 7 of them, so depth at most 7 (indices up to 255). At the top, it can sit right under 1 at index 2."},{"id":38,"l":[{"p":"2(b) If 8 is at its minimum possible index, which other numbers can only be at exactly one index? (List the numbers, separated by commas.)"}],"k":"blank","a":["1, 2","1 2"],"topics":["HEAPS"]},{"id":39,"l":[{"p":"2(b) Their indices, in the same order"}],"k":"blank","a":["1, 3","1 3"],"topics":["HEAPS"]},{"id":40,"l":[{"p":"2(c) If 8 is at its maximum possible index, which other numbers can only be at exactly one index?"}],"k":"blank","a":["1, 2, 3, 4, 5, 6, 7","1 2 3 4 5 6 7"],"topics":["HEAPS"]},{"id":41,"l":[{"p":"2(c) Their indices, in the same order"}],"k":"blank","a":["1, 3, 7, 15, 31, 63, 127","1 3 7 15 31 63 127"],"topics":["HEAPS"],"x":"At index 255, 8’s ancestors are at 127, 63, 31, 15, 7, 3, 1 and must be exactly 7, 6, 5, 4, 3, 2, 1 from the bottom up."},{"s":[{"p":"3. A MaxHeap holds the numbers 1, 2, …, 1023, stored in an array with index 0 empty."}]},{"id":42,"l":[{"p":"3(a) What is the minimum index that could contain 8?"}],"k":"blank","a":["128"],"topics":["HEAPS"]},{"id":43,"l":[{"p":"3(a) And the maximum index?"}],"k":"blank","a":["1023"],"topics":["HEAPS"],"x":"In a max heap 8 can only have descendants smaller than it (at most 7), so it must be in the bottom levels: index 128 or later; any leaf, up to 1023, works."},{"id":44,"l":[{"p":"3(b) If 8 is at its minimum possible index, which other numbers can only be at exactly one index?"}],"k":"blank","a":["1023"],"topics":["HEAPS"]},{"id":45,"l":[{"p":"3(b) Their indices, in the same order"}],"k":"blank","a":["1"],"topics":["HEAPS"]},{"id":46,"l":[{"p":"3(c) If 8 is at its maximum possible index, which other numbers can only be at exactly one index?"}],"k":"blank","a":["1023"],"topics":["HEAPS"]},{"id":47,"l":[{"p":"3(c) Their indices, in the same order"}],"k":"blank","a":["1"],"topics":["HEAPS"],"x":"Only the maximum, 1023, is forced: it’s always at the root."}],"topics":null},{"id":"61b-fa23-mt2/5","n":"5","t":"5. BST To MinHeap (16.0 pts)","b":[{"s":[{"p":"Eric and Justin convert a Binary Search Tree into a MinHeap with the same elements (the PriorityQueue is implemented like the MinHeap from lecture). Eric says N insertions at O(log N) each take O(N log N); Justin claims it can be done in O(N)."}]},{"id":48,"l":[{"p":"(a) Select all the conditions where MinHeap insertion is a constant-time operation."}],"k":"sata","o":["You are inserting the largest element into the heap","You are inserting the smallest element into the heap","When the heap is balanced and has an equal number of left and right children for all nodes","None of the above"],"a":[0],"topics":["TREE_TRAVERSALS"],"x":"The largest element never swims up. The smallest swims all the way to the root.","part":"a"},{"s":[{"p":"(b) Implement toPQ, which must be O(N). You may only use publicly accessible methods of the PriorityQueue."},{"c":"public class BSTSet<E extends Comparable<E>> {\n    class Node {\n        E elem;\n        Node left;  // A subtree containing all elements less than elem\n        Node right; // A subtree containing all elements greater than elem\n        public Node(E elem) { this.elem = elem; }\n    }\n    public Node root; // ... binary search tree implementation not shown ...\n\n    public PriorityQueue<E> toPQ() {\n        PriorityQueue<E> result = new PriorityQueue<E>();\n        helper(this.root, result);\n        return result;\n    }\n\n    private void helper(Node node, PriorityQueue<E> pq) {\n        if (⟪a⟫) {\n            ⟪b⟫;\n            ⟪c⟫;\n            ⟪d⟫;\n        }\n    }\n}","lang":"java","f":{"a":"node != null","b":"helper(node.left, pq)","c":"pq.add(node.elem)","d":"helper(node.right, pq)"}}]},{"id":49,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["node != null","null != node"],"topics":["TREE_TRAVERSALS"],"part":"b"},{"id":50,"l":[{"p":"(b) First line"}],"k":"blank","a":["helper(node.left, pq)"],"topics":["TREE_TRAVERSALS"],"part":"b"},{"id":51,"l":[{"p":"(b) Second line"}],"k":"blank","a":["pq.add(node.elem)"],"topics":["TREE_TRAVERSALS"],"part":"b"},{"id":52,"l":[{"p":"(b) Third line"}],"k":"blank","a":["helper(node.right, pq)"],"topics":["TREE_TRAVERSALS"],"x":"An in-order traversal adds the elements in increasing order, so each one is the largest so far and inserts in constant time: O(N) in total.","part":"b"}],"topics":null},{"id":"61b-fa23-mt2/6","n":"6","t":"6. Asymptotics (18.0 pts)","b":[{"s":[{"p":"Give the best- and worst-case runtimes of the functions below."},{"c":"public static void a(int N) {\n    for (int i = 1; i < N; i += 1) {\n        for (int j = 1; j < i * i; j += 1) {\n            System.out.println(\"a\");\n        }\n    }\n}","lang":"java"}]},{"id":53,"l":[{"p":"(a) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":8,"topics":["ASYMPTOTICS"],"part":"a"},{"id":54,"l":[{"p":"(a) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":8,"topics":["ASYMPTOTICS"],"x":"1² + 2² + … + N² = Θ(N³).","part":"a"},{"s":[{"c":"public static void b(int N) {\n    if (N <= 1) {\n        return;\n    }\n    for (int i = 0; i < N; i += 2) {\n        System.out.println(\"b\");\n    }\n    b(N / 3);\n    b(N / 3);\n    b(N / 3);\n}","lang":"java"}]},{"id":55,"l":[{"p":"(b) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":5,"topics":["ASYMPTOTICS"],"part":"b"},{"id":56,"l":[{"p":"(b) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":5,"topics":["ASYMPTOTICS"],"x":"Each level of calls does about N/2 work in total, and there are log₃ N levels.","part":"b"},{"s":[{"c":"public static void c(int N) {\n    Random rand = new Random();\n    for (int i = 1; i < N; i *= 2) {\n        for (int j = 0; j != rand.nextInt(0, i); j += 1) {\n            System.out.println(\"c\");\n        }\n    }\n}","lang":"java"}]},{"id":57,"l":[{"p":"(c) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":2,"topics":["ASYMPTOTICS"],"part":"c"},{"id":58,"l":[{"p":"(c) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":13,"topics":["ASYMPTOTICS"],"x":"The inner loop stops only when j happens to equal a fresh random number; if j passes it, the loop can run forever.","part":"c"},{"s":[{"c":"public static void d(int[] arr) {\n    int N = arr.length;\n    BSTSet<Integer> tree = new BSTSet<>();\n    /* Assume that BST implements a binary search tree\n     * with no self-balancing optimizations, as seen in lecture */\n    for (int i = 0; i < N; i += 1) {\n        tree.insert(arr[i]);\n    }\n}","lang":"java"}]},{"id":59,"l":[{"p":"(d) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS"],"part":"d"},{"id":60,"l":[{"p":"(d) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":6,"topics":["ASYMPTOTICS"],"x":"Best: all values equal, so each insert stops at the root. Worst: sorted input builds a spindly tree.","part":"d"},{"s":[{"c":"public static void e(int N) {\n    if (N <= 0) { return; }\n    if (N % 2 == 0) { return; }\n    e(N - 1);\n    e(N - 2);\n}","lang":"java"}]},{"id":61,"l":[{"p":"(e) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":0,"topics":["ASYMPTOTICS"],"part":"e"},{"id":62,"l":[{"p":"(e) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS"],"x":"Even N returns at once. For odd N, e(N − 1) is even and returns, so only the e(N − 2) chain continues: about N/2 calls.","part":"e"},{"s":[{"c":"public static void f(int N) {\n    if (N == 1) { return; }\n    if (isPowerOfTwo(N)) {\n        f(N / 2);\n    } else {\n        f(N - 1);\n    }\n}\npublic static boolean isPowerOfTwo(int N) {\n    if (N == 1) {\n        return true;\n    } else if (N % 2 != 0 || N == 0) {\n        return false;\n    } else {\n        return isPowerOfTwo(N / 2);\n    }\n}","lang":"java"}]},{"id":63,"l":[{"p":"(f) Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":3,"topics":["ASYMPTOTICS"],"part":"f"},{"id":64,"l":[{"p":"(f) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS"],"x":"Best: N is a power of two, so log N calls each spend Θ(log N) checking. Worst: N just above a power of two steps down by 1 about N/2 times, and odd numbers fail the check at once.","part":"f"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa24-final","t":"Fall 2024 Final","src":{"exam":"https://drive.google.com/file/d/1QSg0vDkz3x1SdErX0Y_-3rwFhtj-rYdc/view","sol":"https://drive.google.com/file/d/1U5HqcxO89Epuj7YQbDIkzy_128dFB3ui/view","topics":"fa24-final"},"p":[{"id":"61b-fa24-final/1","n":"1","t":"1. Potpourri (8 pts)","b":[{"id":1,"l":[{"p":"(a) Java iterators use the yield keyword instead of return."}],"k":"mc","o":["True","False"],"a":1,"topics":["ITERATORS","JAVA"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) A function receiving a list of length N must take at least Ω(N) time."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":3,"l":[{"p":"(c) Select every true statement about checking if an unsorted N-item array contains 1."}],"k":"sata","o":["Best-case O(1)","Best-case Ω(N)","Worst-case Ω(log N)","Worst-case Θ(N)","None of the above"],"a":[0,2,3],"topics":["ASYMPTOTICS","ARRAYS"],"topicsBy":"site","part":"c"},{"id":4,"l":[{"p":"(d) An LLRB is always exactly twice as tall as its corresponding B-tree."}],"k":"mc","o":["True","False"],"a":1,"topics":["RED_BLACK_TREES","B_TREES"],"topicsBy":"site","part":"d"},{"id":5,"l":[{"p":"(e) Calling null.hashCode() in Java results in an error."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA"],"topicsBy":"site","part":"e"}],"topics":null},{"id":"61b-fa24-final/2","n":"2","t":"2. Do It Aditya’s Way! (15 pts)","b":[{"s":[{"p":"Define superclass > subclass. Unrelated classes are incomparable. A full ordering lists each subclass before its superclass whenever they are related."}]},{"id":6,"l":[{"p":"(a) If A > B and B > C, then A > C."}],"k":"mc","o":["True","False"],"a":0,"topics":["INHERITANCE"],"topicsBy":"site","part":"a"},{"id":7,"l":[{"p":"(b) If A appears after B in a full ordering, then necessarily A > B."}],"k":"mc","o":["True","False"],"a":1,"topics":["INHERITANCE"],"topicsBy":"site","part":"b"},{"id":8,"l":[{"p":"(c) Describe an O(N+M) full-ordering algorithm in at most three sentences."}],"k":"blank","a":["Build a DAG with one vertex per class and an edge from each subclass to its superclass. Return a topological ordering of the DAG."],"topics":["INHERITANCE","GRAPH_TRAVERSALS"],"topicsBy":"site","part":"c"},{"id":9,"l":[{"p":"(d) Final element in a full ordering of every non-primitive Java class"}],"k":"blank","a":["Object"],"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"d"},{"s":[{"p":"The pictured max-heap of classes has Glorp at root; children Foo and Snapp; grandchildren Jurp, Bram, Wert, Laip in that order. Every parent is a superclass of its children; additional superclass relations may exist. Each class has a no-arg constructor and its own toString."}]},{"id":10,"l":[{"p":"(e) Glorp g = new Bram();"}],"k":"mc","o":["Never Error","Always Error","Sometimes Error"],"a":0,"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"e"},{"id":11,"l":[{"p":"(f) Foo f = new Wert();"}],"k":"mc","o":["Never Error","Always Error","Sometimes Error"],"a":2,"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"f"},{"id":12,"l":[{"p":"(g) Glorp g = new Snapp(); ((Wert) g).toString();"}],"k":"mc","o":["Glorp.toString always called","Always Error","Wert.toString always called","Not Enough Information"],"a":1,"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"g"},{"id":13,"l":[{"p":"(h) Laip l = new Wert(); ((Snapp) l).toString();"}],"k":"mc","o":["Laip.toString always called","Always Error","Wert.toString always called","Not Enough Information"],"a":3,"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"h"}],"topics":null},{"id":"61b-fa24-final/3","n":"3","t":"3. The Golden Apples of Yokeyrin (21 pts)","b":[{"s":[{"p":"Rooms are vertices 1–100 in a weighted directed graph. Anirudh starts at room 100 and Heracles at room 1; they move simultaneously, may wait, and may meet only in a room. A meeting is guaranteed. For the implementation below, adj maps each room to a list of outgoing edges; State has int room,time and Edge has int dest,weight."},{"c":"private class StateComparator ⟪a⟫ {\n  @Override\n  public int compare(State o1, State o2) {\n    ⟪b⟫\n  }\n}\nprivate Map<Integer, Integer> dijkstras(int source, Map<Integer, List<Edge>> adj) {\n  Map<Integer, Integer> distTo = new HashMap<>();\n  PriorityQueue<State> states = ⟪c⟫;\n  states.add(new State(source, 0));\n  while (!states.isEmpty()) {\n    State curr = states.poll();\n    if (!distTo.containsKey(curr.room)) {\n      ⟪d⟫\n      for (Edge e : adj.get(curr.room)) {\n        State nextRoom = ⟪e⟫;\n        ⟪f⟫\n      }\n    }\n  }\n  return distTo;\n}","lang":"java","f":{"a":"implements Comparator<State>","b":"return o1.time - o2.time;","c":"new PriorityQueue<>(new StateComparator())","d":"distTo.put(curr.room, curr.time);","e":"new State(e.dest, curr.time + e.weight)","f":"states.add(nextRoom);"}}]},{"id":14,"l":[{"p":"(a) Implement the comparator"}],"k":"blank","a":["implements Comparator<State>"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"id":15,"l":[{"p":"(a) Compare by time"}],"k":"blank","a":["return o1.time - o2.time;"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"id":16,"l":[{"p":"(a) Initialize the priority queue"}],"k":"blank","a":["new PriorityQueue<>(new StateComparator())"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"id":17,"l":[{"p":"(a) Record settled distance"}],"k":"blank","a":["distTo.put(curr.room, curr.time);"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"id":18,"l":[{"p":"(a) Make next state"}],"k":"blank","a":["new State(e.dest, curr.time + e.weight)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"id":19,"l":[{"p":"(a) Add state to fringe"}],"k":"blank","a":["states.add(nextRoom);"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"c":"public int leastTime(Map<Integer, List<Edge>> adj) {\n  Map<Integer, Integer> herc = ⟪g⟫;\n  Map<Integer, Integer> ani = ⟪h⟫;\n  int lowestTime = Integer.MAX_VALUE;\n  for (int i = 1; i <= 100; i++) {\n    if (⟪i⟫ && ⟪j⟫) {\n      int currTime = ⟪k⟫;\n      lowestTime = ⟪l⟫;\n    }\n  }\n  return lowestTime;\n}","lang":"java","f":{"g":"dijkstras(1, adj)","h":"dijkstras(100, adj)","i":"herc.containsKey(i)","j":"ani.containsKey(i)","k":"Math.max(herc.get(i), ani.get(i))","l":"Math.min(lowestTime, currTime)"}}]},{"id":20,"l":[{"p":"(b) Heracles distances"}],"k":"blank","a":["dijkstras(1, adj)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"},{"id":21,"l":[{"p":"(b) Anirudh distances"}],"k":"blank","a":["dijkstras(100, adj)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"},{"id":22,"l":[{"p":"(b) Heracles can reach room"}],"k":"blank","a":["herc.containsKey(i)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"},{"id":23,"l":[{"p":"(b) Anirudh can reach room"}],"k":"blank","a":["ani.containsKey(i)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"},{"id":24,"l":[{"p":"(b) Time until both are there"}],"k":"blank","a":["Math.max(herc.get(i), ani.get(i))"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"},{"id":25,"l":[{"p":"(b) Update best meeting time"}],"k":"blank","a":["Math.min(lowestTime, currTime)"],"topics":["SHORTEST_PATHS","JAVA"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-fa24-final/4","n":"4","t":"4. Sorting (18 pts)","b":[{"id":26,"l":[{"p":"(a) Bottom-up heapify [7,2,2,4,5,8,9] into a max heap."}],"k":"mc","o":["[9,8,5,4,7,2,2]","[9,5,8,4,2,7,2]","[2,4,2,7,5,8,9]","[9,5,8,2,4,2,7]"],"a":1,"topics":["HEAPS","SORTING"],"topicsBy":"site","part":"a"},{"id":27,"l":[{"p":"(b) One in-place heapsort iteration after bottom-up heapification."}],"k":"mc","o":["[5,4,8,2,2,7,9]","[2,5,8,4,2,7,9]","[8,7,4,5,2,2,9]","[8,5,7,4,2,2,9]"],"a":3,"topics":["HEAPS","SORTING"],"topicsBy":"site","part":"b"},{"id":28,"l":[{"p":"(c) MSD radix sort [123,312,279,189,423,275] after the first two digits."}],"k":"mc","o":["[123,189,275,279,312,423]","[123,189,279,275,312,423]","[312,123,423,275,279,189]","[312,123,423,279,275,189]"],"a":1,"topics":["RADIX_SORTS","SORTING"],"topicsBy":"site","part":"c"},{"id":29,"l":[{"p":"(d) LSD radix sort [123,312,279,189,423,275] after processing the last two digits."}],"k":"mc","o":["[123,189,275,279,312,423]","[123,189,279,275,312,423]","[312,123,423,275,279,189]","[312,123,423,279,275,189]"],"a":2,"topics":["RADIX_SORTS","SORTING"],"topicsBy":"site","part":"d"},{"s":[{"p":"For (e–h), give best- and worst-case runtimes for N distinct items."}]},{"id":30,"l":[{"p":"(e) Mergesort generalized to k=3 equal subarrays: best case"}],"k":"blank","a":["Θ(N log N)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"e"},{"id":31,"l":[{"p":"(e) k=3: worst case"}],"k":"blank","a":["Θ(N log N)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"e"},{"id":32,"l":[{"p":"(f) k=N: best case"}],"k":"blank","a":["Θ(N²)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"f"},{"id":33,"l":[{"p":"(f) k=N: worst case"}],"k":"blank","a":["Θ(N²)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"f"},{"id":34,"l":[{"p":"(g) Quicksort puts the pivot at the left-most position in the right subarray: best case"}],"k":"blank","a":["Θ(N²)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"g"},{"id":35,"l":[{"p":"(g) Same variant: worst case"}],"k":"blank","a":["Θ(∞)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"g"},{"id":36,"l":[{"p":"(h) Quicksort puts the pivot at the right-most position in the right subarray: best case"}],"k":"blank","a":["Θ(N log N)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"h"},{"id":37,"l":[{"p":"(h) Same variant: worst case"}],"k":"blank","a":["Θ(N²)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"h"}],"topics":null},{"id":"61b-fa24-final/5","n":"5","t":"5. Binary Tries (16 pts)","b":[{"s":[{"p":"A binary trie maps strings over {0,1}; the empty key is allowed. Insert, in order, keys/values: 101→5, 011→6, 100→1, 010→2, 111→7, 001→4, 11→3, 0→8."}]},{"id":38,"l":[{"p":"(a) Value stored at key \"101\""}],"k":"blank","a":["5"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":39,"l":[{"p":"(a) Value stored at key \"011\""}],"k":"blank","a":["6"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":40,"l":[{"p":"(a) Value stored at key \"100\""}],"k":"blank","a":["1"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":41,"l":[{"p":"(a) Value stored at key \"010\""}],"k":"blank","a":["2"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":42,"l":[{"p":"(a) Value stored at key \"111\""}],"k":"blank","a":["7"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":43,"l":[{"p":"(a) Value stored at key \"001\""}],"k":"blank","a":["4"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":44,"l":[{"p":"(a) Value stored at key \"11\""}],"k":"blank","a":["3"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":45,"l":[{"p":"(a) Value stored at key \"0\""}],"k":"blank","a":["8"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"id":46,"l":[{"p":"(b) Worst-case nodes for N distinct keys, each B characters long"}],"k":"blank","a":["Θ(NB)"],"topics":["TRIES","ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"s":[{"c":"public V put(String key, V value) {\n  Node n = root;\n  for (char c : key.toCharArray()) {\n    if (⟪a⟫) {\n      if (⟪b⟫) ⟪c⟫\n      ⟪d⟫\n    } else if (⟪e⟫) {\n      if (⟪f⟫) ⟪g⟫\n      ⟪h⟫\n    } else {\n      throw new IllegalArgumentException(\"Key must contain only 0s and 1s\");\n    }\n  }\n  ⟪i⟫\n  return value;\n}","lang":"java","f":{"a":"c == '0'","b":"n.zero == null","c":"n.zero = new Node();","d":"n = n.zero;","e":"c == '1'","f":"n.one == null","g":"n.one = new Node();","h":"n = n.one;","i":"n.value = value;"}}]},{"id":47,"l":[{"p":"(c) Check for zero"}],"k":"blank","a":["c == '0'"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":48,"l":[{"p":"(c) Missing zero-child check"}],"k":"blank","a":["n.zero == null"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":49,"l":[{"p":"(c) Create zero child"}],"k":"blank","a":["n.zero = new Node();"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":50,"l":[{"p":"(c) Follow zero child"}],"k":"blank","a":["n = n.zero;"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":51,"l":[{"p":"(c) Check for one"}],"k":"blank","a":["c == '1'"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":52,"l":[{"p":"(c) Missing one-child check"}],"k":"blank","a":["n.one == null"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":53,"l":[{"p":"(c) Create one child"}],"k":"blank","a":["n.one = new Node();"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":54,"l":[{"p":"(c) Follow one child"}],"k":"blank","a":["n = n.one;"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":55,"l":[{"p":"(c) Store value at key node"}],"k":"blank","a":["n.value = value;"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-fa24-final/6","n":"6","t":"6. Natalia MST (22 pts)","b":[{"s":[{"p":"A Natalia MST is a minimum-weight spanning tree containing exactly one edge across a specified cut. In the pictured six-vertex graph, cut sides are {P,Q,R} and {X,Y,Z}. Edges and weights: P-Q 5, P-R 3, Q-X 4, Q-Y 2, R-Y 1, X-Y 7, X-Z 5."}]},{"id":56,"l":[{"p":"(a) Select all edges in the Natalia MST."}],"k":"sata","o":["P-Q","Q-X","R-Y","X-Z","P-R","Q-Y","X-Y"],"a":[0,2,3,4,6],"topics":["MSTS"],"topicsBy":"site","part":"a"},{"id":57,"l":[{"p":"(b) Does every connected graph and cut admit a Natalia MST?"}],"k":"mc","o":["True","False"],"a":1,"topics":["MSTS"],"topicsBy":"site","part":"b"},{"id":58,"l":[{"p":"(b) Give a counterexample with at most four vertices"}],"k":"blank","a":["A three-vertex path A—B—C with cut {A,C} | {B}. Both path edges cross the cut, so every spanning tree uses two crossing edges and none has exactly one."],"topics":["MSTS"],"topicsBy":"site","part":"b"},{"id":59,"l":[{"p":"(c) If a Natalia MST exists, must its weight equal the unrestricted MST weight?"}],"k":"mc","o":["True","False"],"a":1,"topics":["MSTS"],"topicsBy":"site","part":"c"},{"id":60,"l":[{"p":"(d) Which modified algorithms always produce a Natalia MST?"}],"k":"sata","o":["Build separate MSTs on both cut sides, then add the minimum crossing edge.","Add the minimum crossing edge, delete all other crossing edges, then run Prim from the joined endpoints.","Run Prim on the full graph, then delete all but the minimum crossing edge.","Add the maximum edge weight to every crossing edge, then run Kruskal.","None of the above"],"a":[0,1,3],"topics":["MSTS"],"topicsBy":"site","part":"d"},{"id":61,"l":[{"p":"(e) Give an O(E) repair algorithm after deleting edge e from given Natalia MST N"}],"k":"blank","a":["If e is not in N, return N. If e is its crossing-cut edge, replace it with the lightest remaining edge across the original cut. Otherwise e split N into two components: find those components by DFS, then add the lightest edge of G′ crossing between them."],"topics":["MSTS","GRAPH_TRAVERSALS"],"topicsBy":"site","part":"e"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa24-mt1","t":"Fall 2024 Midterm 1","src":{"exam":"https://drive.google.com/file/d/10NunD17-SlYqwasw0WTaeGo2NkFr8EJO/view","sol":"https://drive.google.com/file/d/1aPFbJ_6iF_DIxW3gjJHPBAUUh-u2QG1i/view","topics":"fa24-mt1"},"p":[{"id":"61b-fa24-mt1/1","n":"1","t":"1. Football? (8.0 pts)","b":[{"s":[{"c":"public class Athlete {\n    public void g() {\n        Athlete curr = (FootballPlayer) this;\n        p(curr);\n    }\n    public void p(Athlete curr) {\n        curr.celebration();\n    }\n    public void celebration() {\n        System.out.println(\"Let's go\");\n    }\n    public Athlete spawn() {\n        System.out.println(\"spawn Athlete\");\n        return new Athlete();\n    }\n}\n\npublic class FootballPlayer extends Athlete {\n    @Override\n    public void celebration() {\n        System.out.println(\"Let's goooal\");\n    }\n    @Override\n    public Athlete spawn() {\n        System.out.println(\"spawn Footballer\");\n        return new FootballPlayer();\n    }\n}","lang":"java"},{"p":"(a) For each line of main, write CE for a compile error, RE for a runtime error, OK if it runs but prints nothing, or what it prints. If a line errors, assume the program continues as if it weren’t there."},{"c":"Athlete messi = new FootballPlayer();               // (1)\nFootballPlayer brady = new Athlete();               // (2)\nAthlete thiago = messi.spawn();                     // (3)\nFootballPlayer lionel = (FootballPlayer) messi;     // (4)\nmessi.g();                                          // (5)\nthiago.g();                                         // (6)","lang":"java"}]},{"id":1,"l":[{"p":"(a) Line 1"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":2,"l":[{"p":"(a) Line 2"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"An Athlete isn’t necessarily a FootballPlayer.","part":"a"},{"id":3,"l":[{"p":"(a) Line 3"}],"k":"blank","a":["spawn Footballer","spawn FootballPlayer"],"topics":["INHERITANCE","DMS"],"x":"Dynamic method selection: messi is a FootballPlayer.","part":"a"},{"id":4,"l":[{"p":"(a) Line 4"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":5,"l":[{"p":"(a) Line 5"}],"k":"blank","a":["Let's goooal"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":6,"l":[{"p":"(a) Line 6"}],"k":"blank","a":["Let's goooal"],"topics":["INHERITANCE","DMS"],"x":"thiago is a FootballPlayer at runtime, so the cast in g succeeds.","part":"a"},{"id":7,"l":[{"p":"(b) Which method signatures would, added by itself, allow messi.f(messi) to compile?"}],"k":"sata","o":["public void f(FootballPlayer x), added to class Athlete.","public void f(FootballPlayer x), added to class FootballPlayer.","public void f(Athlete x), added to class Athlete.","public void f(Athlete x), added to class FootballPlayer."],"a":[2],"topics":["INHERITANCE","DMS"],"x":"The compiler only knows messi is an Athlete, so f must be in Athlete and accept an Athlete.","part":"b"}],"topics":null},{"id":"61b-fa24-mt1/2","n":"2","t":"2. Potpourri (9.0 pts)","b":[{"id":8,"l":[{"p":"(a) Which are valid features of a Java interface?"}],"k":"sata","o":["Private methods","Public methods","Constructors"],"a":[1],"topics":["JAVA","INHERITANCE"],"part":"a"},{"id":9,"l":[{"p":"(b) A class can implement multiple interfaces."}],"k":"mc","o":["True","False"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"b"},{"id":10,"l":[{"p":"(c) Which statement best describes the test-driven development cycle?"}],"k":"mc","o":["Write tests → Refactor code → Write code","Write tests → Write code → Refactor code","Write code → Refactor code → Write tests"],"a":1,"topics":["TESTING"],"part":"c"},{"id":11,"l":[{"p":"(d) What is the primary purpose of the “Refactor” phase in test-driven development?"}],"k":"mc","o":["To reduce code complexity and improve design while keeping the tests passing.","To rewrite test cases that are failing.","To add additional features to the code."],"a":0,"topics":["TESTING"],"part":"d"},{"id":12,"l":[{"p":"(e) Which statements about access modifiers are true?"}],"k":"sata","o":["If a public method relies on a helper function to work, the helper function must be public.","If a private method relies on a helper function to work, the helper function must be private.","Private methods and variables can be accessed by subclasses.","Protected methods and variables can be accessed by subclasses.","The value of a private variable can be accessed via a public method."],"a":[3,4],"topics":["JAVA","ABSTRACTION"],"part":"e"},{"s":[{"c":"// (f)\npublic static <T> void swap(T[] array) {\n    T temp = array[0];\n    array[0] = array[1];\n    array[1] = temp;\n}\npublic static void main(String[] args) {\n    Integer[] values = new Integer[]{10, 20};\n    swap(values);\n    System.out.println(values[0]);\n}","lang":"java"}]},{"id":13,"l":[{"p":"(f) What does main print?"}],"k":"mc","o":["10","20"],"a":1,"topics":["JAVA","ARRAYS"],"x":"The method changes the array’s contents, which the caller shares.","part":"f"},{"s":[{"c":"// (g)\npublic static <T> void swap(T x, T y) {\n    T temp = y;\n    y = x;\n    x = temp;\n}\npublic static void main(String[] args) {\n    Integer x = 10;\n    Integer y = 20;\n    swap(x, y);\n    System.out.println(x);\n}","lang":"java"}]},{"id":14,"l":[{"p":"(g) What does main print?"}],"k":"mc","o":["10","20"],"a":0,"topics":["JAVA","ARRAYS"],"x":"Java passes copies of references; reassigning the parameters doesn’t affect the caller’s variables.","part":"g"}],"topics":null},{"id":"61b-fa24-mt1/3","n":"3","t":"3. What Even Is Static? (6.0 pts)","b":[{"s":[{"c":"public class Q3 {\n    private int instanceVar = 0;\n    private static int staticVar = 1;\n\n    public void instanceMethod() {\n        // Code here for part a\n    }\n    public static void staticMethod() {\n        // Code here for part b\n    }\n    public static void main(String[] args) {\n        Q3 obj = new Q3();\n        // Code here for part c\n    }\n}","lang":"java"}]},{"id":15,"l":[{"p":"(a) Which lines, added to instanceMethod by themselves, compile?"}],"k":"sata","o":["System.out.println(instanceVar);","System.out.println(staticVar);","staticMethod();"],"a":[0,1,2],"topics":["JAVA"],"part":"a"},{"id":16,"l":[{"p":"(b) Which lines, added to staticMethod by themselves, compile?"}],"k":"sata","o":["System.out.println(instanceVar);","System.out.println(staticVar);","instanceMethod();"],"a":[1],"topics":["JAVA"],"x":"A static method has no this, so it can’t use instance members.","part":"b"},{"id":17,"l":[{"p":"(c) Which lines, added to the end of main by themselves, compile?"}],"k":"sata","o":["Q3.instanceMethod();","Q3.staticMethod();","obj.instanceMethod();"],"a":[1,2],"topics":["JAVA"],"part":"c"}],"topics":null},{"id":"61b-fa24-mt1/4","n":"4","t":"4. Crossword (18.0 pts)","b":[{"s":[{"p":"A crossword is an N by N char array with black squares as #. For example, the first row of an 11-by-11 puzzle might read # M A D A M # P E A #, containing the horizontal words MADAM and PEA."},{"p":"(a) transpose returns a new matrix that flips the input over its diagonal, so the element at (i, j) moves to (j, i)."},{"c":"private static char[][] transpose(char[][] matrix) {\n    int n = matrix.length;\n    char[][] result = ⟪a⟫;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            ⟪b⟫;\n        }\n    }\n    return result;\n}","lang":"java","f":{"a":"new char[n][n]","b":"result[i][j] = matrix[j][i]"}}]},{"id":18,"l":[{"p":"(a) result = ____"}],"k":"blank","a":["new char[n][n]"],"topics":["ARRAYS"],"part":"a"},{"id":19,"l":[{"p":"(a) The loop body"}],"k":"blank","a":["result[i][j] = matrix[j][i]","result[j][i] = matrix[i][j]"],"topics":["ARRAYS"],"part":"a"},{"s":[{"p":"(b) validCrossword checks that all horizontal and vertical words are valid according to validWord(String), which returns false on an empty string. The border is all #. You may use transpose and a StringBuilder (append(char), toString())."},{"c":"public static boolean validCrossword(char[][] crossword) {\n    return ⟪c⟫;\n}\n\nprivate static boolean verifyRows(char[][] crossword) {\n    int n = crossword.length;\n    for (int i = 0; i < n; i++) {\n        StringBuilder word = new StringBuilder(); // Resets word to empty string\n        for (⟪d⟫) {\n            if (⟪e⟫) {\n                ⟪f⟫;\n            } else {\n                String s = ⟪g⟫;\n                if (⟪h⟫) {\n                    return false;\n                }\n                ⟪i⟫;\n            }\n        }\n    }\n    return ⟪j⟫;\n}","lang":"java","f":{"c":"verifyRows(crossword) && verifyRows(transpose(crossword))","d":"char c : crossword[i]","e":"c != '#'","f":"word.append(c)","g":"word.toString()","h":"s.length() > 0 && !validWord(s)","i":"word = new StringBuilder()","j":"true"}}]},{"id":20,"l":[{"p":"(b) validCrossword returns"}],"k":"blank","a":["verifyRows(crossword) && verifyRows(transpose(crossword))","verifyRows(transpose(crossword)) && verifyRows(crossword)"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":21,"l":[{"p":"(b) The inner loop header"}],"k":"blank","a":["char c : crossword[i]"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":22,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["c != '#'"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":23,"l":[{"p":"(b) Inside the if"}],"k":"blank","a":["word.append(c)"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":24,"l":[{"p":"(b) String s = ____"}],"k":"blank","a":["word.toString()"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":25,"l":[{"p":"(b) if (____) return false"}],"k":"blank","a":["s.length() > 0 && !validWord(s)","!s.isEmpty() && !validWord(s)","!s.equals(\"\") && !validWord(s)"],"topics":["ARRAYS","ITERATION"],"x":"Two #s in a row give an empty word, which isn’t a word at all, so skip it.","part":"b"},{"id":26,"l":[{"p":"(b) Then reset the word"}],"k":"blank","a":["word = new StringBuilder()"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":27,"l":[{"p":"(b) verifyRows returns ____ at the end"}],"k":"blank","a":["true"],"topics":["ARRAYS","ITERATION"],"x":"Each word ends at a #, and the border guarantees every row ends with one.","part":"b"}],"topics":null},{"id":"61b-fa24-mt1/5","n":"5","t":"5. Tiebreakers (15.0 pts)","b":[{"s":[{"p":"TiebreakingComparator<T> takes a List of Comparators: it compares with the first; if that says equal, with the second; and so on, returning the first non-equal result, or equality if all are used. Don’t call any Comparator more times than necessary."},{"c":"public class TiebreakingComparator<T> implements Comparator<T> {\n    ⟪a⟫;\n\n    public TiebreakingComparator(⟪b⟫ lst) {\n        ⟪c⟫;\n    }\n\n    @Override\n    public int compare(T a, T b) {\n        for (⟪d⟫) {\n            ⟪e⟫;\n            if (⟪f⟫) {\n                ⟪g⟫;\n            }\n        }\n        ⟪h⟫;\n    }\n}","lang":"java","f":{"a":"List<Comparator<T>> lst","b":"List<Comparator<T>>","c":"this.lst = lst","d":"Comparator<T> c : lst","e":"int result = c.compare(a, b)","f":"result != 0","g":"return result","h":"return 0"}}]},{"id":28,"l":[{"p":"The instance variable"}],"k":"blank","a":["List<Comparator<T>> lst","private List<Comparator<T>> lst"],"topics":["LISTS","COMPARATORS"]},{"id":29,"l":[{"p":"The constructor’s parameter type"}],"k":"blank","a":["List<Comparator<T>>"],"topics":["LISTS","COMPARATORS"]},{"id":30,"l":[{"p":"The constructor body"}],"k":"blank","a":["this.lst = lst"],"topics":["LISTS","COMPARATORS"]},{"id":31,"l":[{"p":"The loop header"}],"k":"blank","a":["Comparator<T> c : lst"],"topics":["LISTS","COMPARATORS"]},{"id":32,"l":[{"p":"First line of the loop"}],"k":"blank","a":["int result = c.compare(a, b)"],"topics":["LISTS","COMPARATORS"]},{"id":33,"l":[{"p":"if (____)"}],"k":"blank","a":["result != 0"],"topics":["LISTS","COMPARATORS"]},{"id":34,"l":[{"p":"Inside the if"}],"k":"blank","a":["return result"],"topics":["LISTS","COMPARATORS"]},{"id":35,"l":[{"p":"After the loop"}],"k":"blank","a":["return 0"],"topics":["LISTS","COMPARATORS"]}],"topics":null},{"id":"61b-fa24-mt1/6","n":"6","t":"6. Linked Links (34.0 pts)","b":[{"s":[{"p":"Each node of an Ordinal contains only a pointer to another Ordinal. 0 is null, 1 is Ordinal(null), 2 is Ordinal(Ordinal(null)), and in general n is Ordinal(n − 1). All inputs represent nonnegative integers."},{"c":"public class Ordinal {\n    public Ordinal rest;\n\n    public Ordinal(Ordinal rest) {\n        this.rest = rest;\n    }\n}\n\nOrdinal succ(Ordinal curr) {      // (a) returns n + 1\n    return ⟪a⟫;\n}\n\nOrdinal pred(Ordinal curr) {      // (b) returns n - 1\n    if (curr == null) {\n        throw new java.lang.IllegalArgumentException();\n    }\n    return ⟪b⟫;\n}","lang":"java","f":{"a":"new Ordinal(curr)","b":"curr.rest"}}]},{"id":36,"l":[{"p":"(a) succ returns"}],"k":"blank","a":["new Ordinal(curr)"],"topics":["LINKED_LISTS"],"part":"a"},{"id":37,"l":[{"p":"(b) pred returns"}],"k":"blank","a":["curr.rest"],"topics":["LINKED_LISTS"],"part":"b"},{"s":[{"p":"From here on you may use pred and succ."},{"c":"Ordinal add(Ordinal a, Ordinal b) {       // (c) returns a + b\n    while (⟪c⟫) {\n        ⟪d⟫;\n        ⟪e⟫;\n    }\n    return ⟪f⟫;\n}\n\nOrdinal floordiv(Ordinal a, Ordinal b) {  // (d) returns a / b, rounded down\n    Ordinal result = ⟪g⟫;\n    final Ordinal bcopy = b;\n    while (⟪h⟫) {\n        ⟪i⟫;\n        ⟪j⟫;\n        if (⟪k⟫) {\n            ⟪l⟫;\n            ⟪m⟫;\n        }\n    }\n    return ⟪n⟫;\n}","lang":"java","f":{"c":"a != null","d":"a = pred(a)","e":"b = succ(b)","f":"b","g":"null","h":"a != null","i":"a = pred(a)","j":"b = pred(b)","k":"b == null","l":"result = succ(result)","m":"b = bcopy","n":"result"}}]},{"id":38,"l":[{"p":"(c) while (____)"}],"k":"blank","a":["a != null"],"topics":["LINKED_LISTS","ITERATION"],"part":"c"},{"id":39,"l":[{"p":"(c) First line"}],"k":"blank","a":["a = pred(a)"],"topics":["LINKED_LISTS","ITERATION"],"part":"c"},{"id":40,"l":[{"p":"(c) Second line"}],"k":"blank","a":["b = succ(b)"],"topics":["LINKED_LISTS","ITERATION"],"part":"c"},{"id":41,"l":[{"p":"(c) return ____"}],"k":"blank","a":["b"],"topics":["LINKED_LISTS","ITERATION"],"x":"Move one unit from a to b at a time.","part":"c"},{"id":42,"l":[{"p":"(d) result starts as"}],"k":"blank","a":["null"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":43,"l":[{"p":"(d) while (____)"}],"k":"blank","a":["a != null"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":44,"l":[{"p":"(d) First line of the loop"}],"k":"blank","a":["a = pred(a)"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":45,"l":[{"p":"(d) Second line"}],"k":"blank","a":["b = pred(b)"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":46,"l":[{"p":"(d) if (____)"}],"k":"blank","a":["b == null"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":47,"l":[{"p":"(d) Inside the if, first line"}],"k":"blank","a":["result = succ(result)"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":48,"l":[{"p":"(d) Inside the if, second line"}],"k":"blank","a":["b = bcopy"],"topics":["LINKED_LISTS","ITERATION"],"part":"d"},{"id":49,"l":[{"p":"(d) return ____"}],"k":"blank","a":["result"],"topics":["LINKED_LISTS","ITERATION"],"x":"Count down a and b together; every time b reaches 0, one whole b fit, so add 1 and start b over.","part":"d"},{"s":[{"p":"(e) Make Ordinal Iterable: the iterator over n returns n − 1, n − 2, …, 1, 0 (not n itself). Assume n > 0."},{"c":"public class Ordinal implements Iterable<Ordinal> {\n    Ordinal rest;\n    public Ordinal(Ordinal rest) {\n        this.rest = rest;\n    }\n\n    public Iterator<Ordinal> iterator() {\n        return ⟪o⟫;\n    }\n\n    private class OrdinalIterator ⟪p⟫ {\n        Ordinal curr;\n        public OrdinalIterator(Ordinal curr) {\n            ⟪q⟫;\n        }\n\n        @Override\n        public boolean hasNext() {\n            return ⟪r⟫;\n        }\n\n        @Override\n        public Ordinal next() {\n            if (curr == null) {\n                throw new java.util.NoSuchElementException();\n            }\n            ⟪s⟫;\n            return ⟪t⟫;\n        }\n    }\n}","lang":"java","f":{"o":"new OrdinalIterator(this)","p":"implements Iterator<Ordinal>","q":"this.curr = curr","r":"curr != null","s":"curr = curr.rest","t":"curr"}}]},{"id":50,"l":[{"p":"(e) iterator() returns"}],"k":"blank","a":["new OrdinalIterator(this)"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":51,"l":[{"p":"(e) OrdinalIterator ____"}],"k":"blank","a":["implements Iterator<Ordinal>"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":52,"l":[{"p":"(e) The constructor body"}],"k":"blank","a":["this.curr = curr"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":53,"l":[{"p":"(e) hasNext returns"}],"k":"blank","a":["curr != null"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":54,"l":[{"p":"(e) First line of next"}],"k":"blank","a":["curr = curr.rest"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":55,"l":[{"p":"(e) next returns"}],"k":"blank","a":["curr"],"topics":["LINKED_LISTS","ITERATORS"],"x":"Step first, then return, so n itself is never returned and the last value returned is 0 (null).","part":"e"}],"topics":null},{"id":"61b-fa24-mt1/7","n":"7","t":"7. Infinite Linked Links (10.0 pts)","b":[{"s":[{"p":"Continuing Linked Links (all parts correctly implemented): ω, the smallest infinite ordinal, is built like this. Beyond it, 1 + ω is Ordinal(ω), 2 + ω is Ordinal(1 + ω), and so on. These are infinite ordinals; those for nonnegative integers are finite ordinals."},{"c":"public static Ordinal inf() {\n    Ordinal omega = new Ordinal(null);\n    omega.rest = omega;\n    return omega;\n}","lang":"java"}]},{"id":56,"l":[{"p":"(a) It is still possible to construct ω (possibly by changing inf) if rest is final, with no other changes to Ordinal."}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA","LINKED_LISTS"],"x":"A final rest is set once, in the constructor, and the object can’t point to itself before it exists.","part":"a"},{"id":57,"l":[{"p":"(b) succ(ω) == ω"}],"k":"mc","o":["True","False"],"a":1,"topics":["LINKED_LISTS"],"x":"succ makes a new object.","part":"b"},{"id":58,"l":[{"p":"(c) pred(ω) == ω"}],"k":"mc","o":["True","False"],"a":0,"topics":["LINKED_LISTS"],"x":"ω points to itself.","part":"c"},{"id":59,"l":[{"p":"(d) Which can occur if add is called with at least one infinite ordinal?"}],"k":"sata","o":["add returns an infinite ordinal.","add returns a finite ordinal.","add infinite-loops or crashes."],"a":[0,2],"topics":["LINKED_LISTS"],"x":"Depending on which argument the loop walks down, it either returns an infinite ordinal or never ends.","part":"d"},{"id":60,"l":[{"p":"(e) add(a, b) always behaves the same as add(b, a) (both loop or crash, or both return the same value)."}],"k":"mc","o":["True","False"],"a":1,"topics":["LINKED_LISTS"],"x":"Walking down a finite input ends; walking down ω never does.","part":"e"},{"id":61,"l":[{"p":"(f) floordiv(ω, b) returns ω if b is a finite ordinal."}],"k":"mc","o":["True","False"],"a":1,"topics":["LINKED_LISTS"],"x":"It loops forever.","part":"f"},{"id":62,"l":[{"p":"(g) floordiv(a, ω) returns 0 if a is a finite ordinal."}],"k":"mc","o":["True","False"],"a":0,"topics":["LINKED_LISTS"],"x":"a reaches null long before b would, so result stays 0.","part":"g"},{"id":63,"l":[{"p":"(h) What is the result of inf() == inf()?"}],"k":"mc","o":["true","false"],"a":1,"topics":["JAVA","EQUALS"],"x":"Each call builds a separate object.","part":"h"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa24-mt2","t":"Fall 2024 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1AUw_VlBuBA6LMK8R1vrAboXtPToF2EtE/view","sol":"https://drive.google.com/file/d/1mfUTBjPFYjwCq5dThr3j2iDGR_Xdx_f4/view","topics":"fa24-mt2"},"p":[{"id":"61b-fa24-mt2/1","n":"1","t":"1. 61Buff (15.0 pts)","b":[{"s":[{"p":"Aditya has organized a one-on-one arm wrestling competition among all of 61B’s TAs and represents the leaderboard as a binary tree: all nodes to the left of a node represent TAs who performed worse, and all nodes to the right represent TAs who performed better."},{"p":"The current leaderboard, from first place to last, is [Aditya, Erik, Natalia, Anniyat, Vanessa, Circle, Anirudh], and this is the tree Aditya draws:"},{"c":"               Anniyat\n             /         \\\n        Circle           Erik\n        /    \\          /    \\\n  Anirudh  Vanessa  Natalia  Aditya","lang":"txt"}]},{"id":1,"l":[{"p":"(a) Which tree traversal gives the leaderboard in order from best arm wrestler to worst?"}],"k":"mc","o":["Pre-order","In-order","Post-order","Level order","None of the above"],"a":4,"topics":["BSTS","TREE_TRAVERSALS"],"x":"Pre-order: Anniyat, Circle, Anirudh, Vanessa, Erik, Natalia, Aditya. In-order: Anirudh, Circle, Vanessa, Anniyat, Erik, Natalia, Aditya. Post-order: Anirudh, Vanessa, Circle, Natalia, Aditya, Erik, Anniyat. None is best to worst.","part":"a"},{"id":2,"l":[{"p":"(b) Which tree traversal gives the reverse ordering of the leaderboard (worst to best)?"}],"k":"mc","o":["Pre-order","In-order","Post-order","Level order","None of the above"],"a":1,"topics":["BSTS","TREE_TRAVERSALS"],"x":"In-order visits worse (left) before better (right): Anirudh, Circle, Vanessa, Anniyat, Erik, Natalia, Aditya.","part":"b"},{"s":[{"p":"(c) Consider a function that finds the leader of a (potentially unbalanced) leaderboard tree. Answer in terms of N, the total number of TAs in the tree."}]},{"id":3,"l":[{"p":"(c) Best case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":0,"topics":["ASYMPTOTICS","BSTS"],"part":"c"},{"id":4,"l":[{"p":"(c) Worst case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":3,"topics":["ASYMPTOTICS","BSTS"],"x":"The leader is the rightmost node. If every node has only a left child, the root is the leader: Θ(1). If every node has only a right child, you walk all N nodes to the bottom: Θ(N).","part":"c"},{"s":[{"p":"Aditya now claims the same diagram is a min-heap (first place is towards the root). (d) Each TA assumes their placement was the best possible one that could have yielded this heap. What is the best possible placement for each TA below?"}]},{"id":5,"l":[{"p":"(d) Circle"}],"k":"mc","o":["1","2","3","4","5","6","7"],"a":1,"topics":["HEAPS"],"x":"Anniyat is above Circle, so Circle can’t be 1st, but can be 2nd.","part":"d"},{"id":6,"l":[{"p":"(d) Anniyat"}],"k":"mc","o":["1","2","3","4","5","6","7"],"a":0,"topics":["HEAPS"],"x":"Anniyat is at the top of the heap, so 1st is the only possible placement.","part":"d"},{"id":7,"l":[{"p":"(d) Aditya"}],"k":"mc","o":["1","2","3","4","5","6","7"],"a":2,"topics":["HEAPS"],"x":"Erik and Anniyat are above Aditya, so the best is 3rd (with Erik 2nd).","part":"d"},{"s":[{"p":"To avoid ambiguity, Aditya now shows the match results as a directed graph: each vertex is a TA, each edge is a match pointing from the winner to the loser, and two TAs can’t face each other twice."}]},{"id":8,"l":[{"p":"(e) If there are no cycles in this graph, then there is always an unambiguous first-place TA."}],"k":"mc","o":["True","False"],"a":1,"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT"],"x":"A → C and B → C has no cycle, but nothing says whether A or B is first. Two separate components have the same problem.","part":"e"},{"id":9,"l":[{"p":"(f) If there are as many edges as there are vertices in the graph, then each TA must have faced every other TA in a match exactly once."}],"k":"mc","o":["True","False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"x":"A → B → C → D → E → A has 5 vertices and 5 edges, but B and D never faced each other.","part":"f"}],"topics":null},{"id":"61b-fa24-mt2/2","n":"2","t":"2. Disjoint Runtimes (18.0 pts)","b":[{"s":[{"p":"In each part, give the best- and worst-case runtime in Θ notation, with respect to N. For all Weighted Quick Union variants, connect tiebreaks by connecting the lower-indexed root underneath the higher-indexed root."},{"c":"public static void f1(int N, QuickUnion qu) {\n    Random rand = new Random();\n    for (int i = 0; i < N; i += 1) {\n        qu.connect(rand.nextInt(N), rand.nextInt(N));\n    }\n    for (int i = 0; i < N; i += 1) {\n        if (!qu.isConnected(rand.nextInt(N), rand.nextInt(N))) {\n            System.out.println(\"Dylan\");\n        }\n    }\n}","lang":"java"}]},{"id":10,"l":[{"p":"(a) f1 best case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":3,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"part":"a"},{"id":11,"l":[{"p":"(a) f1 worst case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":6,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"x":"Best: rand always returns 0, so every connect and isConnected is constant time. Worst: the connects build a spindly tree (4 under 3 under 2 under 1 under 0…), then every isConnected(4, 4) climbs Θ(N) links, N times.","part":"a"},{"s":[{"p":"(b) The same code, but with a WeightedQuickUnion (and printing \"Gaston\")."}]},{"id":12,"l":[{"p":"(b) f2 best case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":3,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"part":"b"},{"id":13,"l":[{"p":"(b) f2 worst case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":5,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"x":"A WQU’s height is at most Θ(log N), so each of the N isConnected calls takes Θ(log N).","part":"b"},{"s":[{"p":"(c) The same code, but with a WeightedQuickUnionPathCompression (and printing \"Hamuy\"). Its isConnected and connect each run in Θ(α(N)) amortized time."}]},{"id":14,"l":[{"p":"(c) f3 best case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":3,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"part":"c"},{"id":15,"l":[{"p":"(c) f3 worst case"}],"k":"mc","o":["Θ(1)","Θ(α(N))","Θ(log N)","Θ(N)","Θ(N α(N))","Θ(N log N)","Θ(N²)"],"a":4,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"x":"Each of the N calls costs Θ(α(N)) amortized.","part":"c"}],"topics":null},{"id":"61b-fa24-mt2/3","n":"3","t":"3. Unstable Matching Algorithm (32.0 pts)","b":[{"s":[{"p":"In preparation for Project 3, Anniyat devises a new partner-matching scheme using a StrangeHashSet<E>, which behaves as a HashSet except that: it starts with one bucket; it resizes when any bucket contains 3 or more elements (which can trigger several resizes in a single add); each resize doubles the number of buckets; and its method List<E>[] getBuckets() returns an array whose ith List holds the values in the ith bucket (in any order)."},{"p":"(a) We create a new StrangeHashSet<Integer> and insert, in order, [5, 6, 1, 10, 13, 4]. The hashCode of an Integer is itself. What does getBuckets() return? Write each bucket as a list like [5, 4], or [] if it is empty."}]},{"id":16,"l":[{"p":"Bucket 0"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"]},{"id":17,"l":[{"p":"Bucket 1"}],"k":"blank","a":["[1]","1"],"topics":["HASHING"]},{"id":18,"l":[{"p":"Bucket 2"}],"k":"blank","a":["[10]","10"],"topics":["HASHING"]},{"id":19,"l":[{"p":"Bucket 3"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"]},{"id":20,"l":[{"p":"Bucket 4"}],"k":"blank","a":["[4]","4"],"topics":["HASHING"]},{"id":21,"l":[{"p":"Bucket 5"}],"k":"blank","a":["[5, 13]","5, 13","[13, 5]","13, 5"],"topics":["HASHING"]},{"id":22,"l":[{"p":"Bucket 6"}],"k":"blank","a":["[6]","6"],"topics":["HASHING"]},{"id":23,"l":[{"p":"Bucket 7"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"x":"5, 6, 1 fill the one bucket, so it doubles to [6] [5, 1]. 10 goes to bucket 0, then 13 makes [5, 1, 13], doubling to 4 buckets: [] [5, 1, 13] [6, 10] [], still 3 in bucket 1, so 8 buckets: [] [1] [10] [] [] [5, 13] [6] []. Finally 4 goes to bucket 4."},{"s":[{"p":"Each student submits a unique password, stored in a (regular) Set<String> passwords. Then this matchmaking algorithm runs:"},{"c":"public class Matching {\n    /** Pairs the students with passwords a and b. */\n    private static void pair(String a, String b) { ... } // Implementation omitted.\n\n    /** Pairs all students according to their passwords. With an odd number of students, pairs all but one\n     *  and returns the unpaired student's password; otherwise pairs everyone and returns null. */\n    public static String pairAllStudents(Set<String> passwords) {\n        while (passwords.size() > 1) {\n            // 1: Create a new StrangeHashSet.\n            StrangeHashSet<String> matcher = new StrangeHashSet<>();\n\n            // 2: Insert all passwords into the StrangeHashSet.\n            for (String s : passwords) {\n                matcher.add(s);\n            }\n\n            // 3: If any bucket contains exactly two passwords, pair the corresponding students.\n            //    Then remove both passwords from passwords.\n            for (List<String> bkt : matcher.getBuckets()) {\n                if (bkt.size() == 2) {\n                    pair(bkt.get(0), bkt.get(1));\n                    passwords.remove(bkt.get(0));\n                    passwords.remove(bkt.get(1));\n                }\n            }\n        } // 4: Repeat Steps 1-3 until there are fewer than two students unpaired.\n\n        // 5: If there's one student unpaired, return the password of that student.\n        if (passwords.size() == 1) {\n            return passwords.toArray()[0];\n        }\n        // 6: Otherwise return null.\n        return null;\n    }\n}","lang":"java"},{"p":"(b) We run pairAllStudents on these students: Alice’s password hashes to 5, Bob’s to 6, Cyrus’s to 1, Diana’s to 10, Eve’s to 13, and Fred’s to 4. What are the resulting pairs?"}]},{"id":24,"l":[{"p":"(b) Alice is paired with"}],"k":"mc","o":["Bob","Cyrus","Diana","Eve","Fred"],"a":3,"topics":["HASHING"],"part":"b"},{"id":25,"l":[{"p":"(b) Bob is paired with"}],"k":"mc","o":["Alice","Cyrus","Diana","Eve","Fred"],"a":2,"topics":["HASHING"],"part":"b"},{"id":26,"l":[{"p":"(b) Cyrus is paired with"}],"k":"mc","o":["Alice","Bob","Diana","Eve","Fred"],"a":4,"topics":["HASHING"],"x":"Round 1 builds the table from (a): only bucket 5 has exactly two, so Alice (5) and Eve (13) pair. Round 2 with 6, 1, 10, 4 ends with buckets [4] [1] [6, 10] [], so Bob and Diana pair. Round 3 puts 1 and 4 in one bucket: Cyrus and Fred.","part":"b"},{"s":[{"p":"For the rest of the question, assume that all passwords have distinct hash codes, unless otherwise stated."}]},{"id":27,"l":[{"p":"(c) Which of the following statements are true? Select all that apply."}],"k":"sata","o":["Assume that hash codes range from 0 to 2ᵇ − 1 for some integer b. When inserting all students into a single StrangeHashSet, at most b resizes occur.","If a bucket contains three items immediately before a resize, it is possible for the items to end up in three different buckets after the resize.","In each iteration of the while loop, at least one pair of students will be created.","In each iteration of the while loop, at least half of the remaining students will be paired.","If an iteration of the while loop requires k resizes when adding all students to the StrangeHashSet, then the next iteration of the while loop will require strictly fewer than k resizes.","pairAllStudents is guaranteed to terminate.","None of the above"],"a":[0,2,4,5],"topics":["HASHING"],"x":"After b resizes there are 2ᵇ buckets, one per possible hash code, so no bucket can hold 3. Doubling splits bucket k into buckets k and n + k only, so three items can’t reach three buckets. The last resize of a round always leaves a bucket of exactly two, so every round pairs someone, and removing that pair means the next round needs fewer resizes; together these guarantee termination. Part (b)’s first round paired only 2 of 6 students.","part":"c"},{"id":28,"l":[{"p":"(d) Mia and Sebastian coordinate their passwords. Mia’s password hashes to 0. What should Sebastian’s hash be to maximize the chance he is paired with Mia? Hash codes range from 0 to 2³² − 1, and two students may not share a hash code."}],"k":"blank","a":["2^31","2**31","2³¹","2147483648","1 << 31"],"topics":["HASHING"],"x":"To stay in bucket 0 with Mia however many buckets there are (2, 4, 8, …), Sebastian’s hash must be a multiple of every power of two that can occur. The largest power of two in range is 2³¹.","part":"d"},{"s":[{"p":"(e) For each modification of pairAllStudents below, which lists of password hashes make it loop forever? Each modification is independent. (The exam asked for one list of at most five hashes, or “Impossible”.)"}]},{"id":29,"l":[{"p":"(e) 1. Instead of doubling the number of buckets on a resize, we triple it."}],"k":"sata","o":["[0, 1, 2]","[0, 3, 6]","[1, 2, 3, 4, 5]","[0, 1]","[4, 8, 9]","None: it’s impossible"],"a":[0,1,4],"topics":["HASHING"],"x":"A loop happens when each bucket ends up with one item, so nobody pairs. [0, 1, 2] and [4, 8, 9] split one per bucket after tripling; [0, 3, 6] does after two triplings. [1, 2, 3, 4, 5] leaves [1, 4] and [2, 5] to pair; any two items pair at once.","part":"e"},{"id":30,"l":[{"p":"(e) 2. Two passwords may share a hash code, but no three passwords share the same hash code."}],"k":"mc","o":["Some list loops forever","Impossible"],"a":1,"topics":["HASHING"],"x":"Two equal hashes always land together, so after enough resizes they sit in a bucket of exactly two and pair. Trying [0, 0] or [0, 0, 2] shows it terminates.","part":"e"},{"id":31,"l":[{"p":"(e) 3. Exactly one hash code is shared by three passwords, and all other passwords have unique hash codes."}],"k":"sata","o":["[0, 0, 0]","[0, 0, 2]","[12, 12, 12]","[0, 1, 2]","None: it’s impossible"],"a":[0,2],"topics":["HASHING"],"x":"Three equal hashes stay in the same bucket however many times it doubles, so the first StrangeHashSet resizes forever. [0, 0, 2] has only two equal hashes, and [0, 1, 2] none.","part":"e"},{"id":32,"l":[{"p":"(e) 4. The StrangeHashSet begins with two buckets instead of one."}],"k":"sata","o":["[0, 1]","[0, 2, 4, 1]","[0]","[0, 2]","None: it’s impossible"],"a":[0,1],"topics":["HASHING"],"x":"One even and one odd hash sit alone in buckets 0 and 1, so nobody pairs, ever. [0, 2, 4, 1] pairs 0 and 4, leaving [1, 2], the same situation. A single item skips the loop; [0, 2] pairs immediately.","part":"e"}],"topics":null},{"id":"61b-fa24-mt2/4","n":"4","t":"4. Fix LLRB (23.0 pts)","b":[{"s":[{"p":"(a) Convert the 2-3 tree below into its corresponding Left-Leaning Red-Black Tree. (The exam had a fill-in table; this site asks about the result in three parts.)"},{"c":"          [10 20]\n        /    |    \\\n     [5]   [15]   [25 30]","lang":"txt"}]},{"id":33,"l":[{"p":"(a) Which value is at the root of the LLRB?"}],"k":"mc","o":["5","10","15","20","25","30"],"a":3,"topics":["B_TREES","RED_BLACK_TREES"],"part":"a"},{"id":34,"l":[{"p":"(a) Which values are in red nodes (the link to their parent is red)?"}],"k":"sata","o":["5","10","15","20","25","30"],"a":[1,4],"topics":["B_TREES","RED_BLACK_TREES"],"part":"a"},{"id":35,"l":[{"p":"(a) Which value is the root’s right child?"}],"k":"mc","o":["5","10","15","25","30","None"],"a":4,"topics":["B_TREES","RED_BLACK_TREES"],"x":"[10 20] becomes 20 with red left child 10 (children 5 and 15); [25 30] becomes 30 with red left child 25.","part":"a"},{"s":[{"p":"(b) Write convert, a function that takes a 2-3 tree and converts it to its corresponding LLRB. In a 2-node, keys[1] and children[2] are null. In a 3-node, keys[0] and keys[1] are not null, and keys[0] < keys[1]."},{"c":"public class TwoThreeTreeNode {\n    public Integer[] keys;\n    public TwoThreeTreeNode[] children;\n\n    // Creates a 2-node\n    public TwoThreeTreeNode(Integer key) {\n        this.keys = new Integer[]{key, null};\n        this.children = new TwoThreeTreeNode[]{null, null, null}; // Ordered from left to right\n    }\n}\n\npublic class LLRB {\n    public LLRBNode root;\n\n    public class LLRBNode {\n        public int key;\n        public LLRBNode left, right;\n        public boolean isRed;\n\n        public LLRBNode(int key, boolean isRed) {\n            this.key = key;\n            this.isRed = isRed;\n        }\n    }\n\n    public LLRB(TwoThreeTreeNode node) {\n        root = convert(node);\n    }\n\n    private LLRBNode convert(TwoThreeTreeNode root) {\n        if (root == null) {\n            return null;\n        }\n        if (⟪a⟫) {\n            LLRBNode node = ⟪b⟫;\n            ⟪c⟫;\n            ⟪d⟫;\n            return node;\n        }\n        LLRBNode leftChild = ⟪e⟫;\n        LLRBNode parent = ⟪f⟫;\n        parent.left = leftChild;\n        ⟪g⟫;\n        ⟪h⟫;\n        ⟪i⟫;\n        return parent;\n    }\n}","lang":"java","f":{"a":"root.keys[1] == null","b":"new LLRBNode(root.keys[0], false)","c":"node.left = convert(root.children[0])","d":"node.right = convert(root.children[1])","e":"new LLRBNode(root.keys[0], true)","f":"new LLRBNode(root.keys[1], false)","g":"leftChild.left = convert(root.children[0])","h":"leftChild.right = convert(root.children[1])","i":"parent.right = convert(root.children[2])"}}]},{"id":36,"l":[{"p":"(b) if (____) — a 2-node"}],"k":"blank","a":["root.keys[1] == null","root.children[2] == null","root.keys[1] == null && root.children[2] == null","root.keys[1] == null || root.children[2] == null","root.keys[0] != null && root.keys[1] == null"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":37,"l":[{"p":"(b) LLRBNode node = ____"}],"k":"blank","a":["new LLRBNode(root.keys[0], false)"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":38,"l":[{"p":"(b) First line after it (either child; the two lines can go in either order)"}],"k":"blank","a":["node.left = convert(root.children[0])","node.right = convert(root.children[1])"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":39,"l":[{"p":"(b) Second line"}],"k":"blank","a":["node.right = convert(root.children[1])","node.left = convert(root.children[0])"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":40,"l":[{"p":"(b) LLRBNode leftChild = ____"}],"k":"blank","a":["new LLRBNode(root.keys[0], true)"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":41,"l":[{"p":"(b) LLRBNode parent = ____"}],"k":"blank","a":["new LLRBNode(root.keys[1], false)"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":42,"l":[{"p":"(b) First of the last three lines (in any order)"}],"k":"blank","a":["leftChild.left = convert(root.children[0])","leftChild.right = convert(root.children[1])","parent.right = convert(root.children[2])","parent.left.left = convert(root.children[0])","parent.left.right = convert(root.children[1])"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":43,"l":[{"p":"(b) Second of the last three lines (in any order)"}],"k":"blank","a":["leftChild.left = convert(root.children[0])","leftChild.right = convert(root.children[1])","parent.right = convert(root.children[2])","parent.left.left = convert(root.children[0])","parent.left.right = convert(root.children[1])"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":44,"l":[{"p":"(b) Third of the last three lines (in any order)"}],"k":"blank","a":["leftChild.left = convert(root.children[0])","leftChild.right = convert(root.children[1])","parent.right = convert(root.children[2])","parent.left.left = convert(root.children[0])","parent.left.right = convert(root.children[1])"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"A 2-node becomes one black node. A 3-node becomes a black parent (the larger key) with a red left child (the smaller key): the three subtrees go, in order, to the red child’s left and right and the parent’s right. leftChild.left and parent.left.left are the same.","part":"b"}],"topics":null},{"id":"61b-fa24-mt2/5","n":"5","t":"5. Yokeyrin’s Cave (12.0 pts)","b":[{"s":[{"p":"Anirudh the Adventurer is in a cave with 100 rooms, numbered 1 to 100. He starts in Room 1 and must reach Room 100 as fast as possible. From each room he can move to any adjacent room in one minute."},{"p":"Fill out shortestTime. Input: Map<Integer, Set<Integer>> adj, which maps each room (1–100) to the set of all adjacent rooms. Output: the minimum number of minutes needed to go from Room 1 to Room 100, or −1 if it is impossible."},{"c":"public class Queue<T> {\n    /** Creates a new queue */\n    public Queue() { ... }\n    /** Adds item to the back of the queue */\n    public void add(T item) { ... }\n    /** Removes and returns the front item of the queue */\n    public T remove() { ... }\n    /** Returns true if the queue has no elements */\n    public boolean isEmpty() { ... }\n}\n\npublic class CaveStory {\n    private static class State {\n        public int room;\n        public int mins;\n\n        public State(int room, int mins) {\n            this.room = room;\n            this.mins = mins;\n        }\n    }\n\n    public static int shortestTime(Map<Integer, Set<Integer>> adj) {\n        Set<Integer> traversed = new HashSet<>();\n        Queue<State> options = new Queue<>();\n        options.add(new State(1, 0));\n\n        while (!options.isEmpty()) {\n            State curr = options.remove();\n            if (⟪a⟫) {\n                ⟪b⟫;\n            }\n            if (⟪c⟫) {\n                ⟪d⟫;\n                for (⟪e⟫) {\n                    ⟪f⟫;\n                }\n            }\n        }\n        return -1; // No path exists\n    }\n}","lang":"java","f":{"a":"curr.room == 100","b":"return curr.mins","c":"!traversed.contains(curr.room)","d":"traversed.add(curr.room)","e":"int neighbor : adj.get(curr.room)","f":"options.add(new State(neighbor, curr.mins + 1))"}}]},{"id":45,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["curr.room == 100","100 == curr.room","adj.get(curr.room).contains(100)"],"topics":["ADTS","GRAPH_TRAVERSALS"],"part":"a"},{"id":46,"l":[{"p":"(b) Inside it"}],"k":"blank","a":["return curr.mins","return curr.mins + 1"],"topics":["ADTS","GRAPH_TRAVERSALS"],"x":"return curr.mins + 1 goes with the alternative check adj.get(curr.room).contains(100).","part":"b"},{"id":47,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["!traversed.contains(curr.room)","!traversed.contains(curr.room) && !adj.get(curr.room).isEmpty()","!traversed.contains(curr.room) && adj.containsKey(curr.room)"],"topics":["ADTS","GRAPH_TRAVERSALS"],"part":"c"},{"id":48,"l":[{"p":"(d) First line inside it"}],"k":"blank","a":["traversed.add(curr.room)"],"topics":["ADTS","GRAPH_TRAVERSALS"],"part":"d"},{"id":49,"l":[{"p":"(e) The for loop’s header"}],"k":"blank","a":["int neighbor : adj.get(curr.room)","Integer neighbor : adj.get(curr.room)"],"topics":["ADTS","GRAPH_TRAVERSALS"],"part":"e"},{"id":50,"l":[{"p":"(f) Inside the for loop"}],"k":"blank","a":["options.add(new State(neighbor, curr.mins + 1))"],"topics":["ADTS","GRAPH_TRAVERSALS"],"x":"This is breadth-first search: the queue hands out rooms in order of distance, so the first time Room 100 comes out, curr.mins is the shortest time. Skip rooms already traversed. (You may name the loop variable anything, as long as (f) matches.)","part":"f"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-fa25-final","t":"Fall 2025 Final","src":{"exam":"https://drive.google.com/file/d/1f2Vp4dEXxLWpKct8qxU5emecELb3-7G3/view","sol":"https://drive.google.com/file/d/1re5hHbeSyoKX0zQBjMLxi74P7cXduNA1/view","topics":"fa25-final"},"p":[{"id":"61b-fa25-final/1","n":"1","t":"1. Welcome to 61B (6 pts)","b":[{"id":1,"l":[{"p":"Does `List<Integer> L = new List<>();` compile and run?"}],"k":"mc","o":["True","False"],"a":1,"topics":["JAVA","ADTS"],"topicsBy":"site"},{"id":2,"l":[{"p":"After gruArmy.put(1,\"kevin\"), put(2,\"stuart\"), put(1,\"bob\"), what is gruArmy.size()?"}],"k":"mc","o":["1","2","3"],"a":1,"topics":["HASHING"],"topicsBy":"site"},{"id":3,"l":[{"p":"After those puts, what does gruArmy.get(1) return?"}],"k":"mc","o":["\"kevin\"","\"stuart\"","\"bob\"","List.of(\"kevin\", \"bob\")"],"a":2,"topics":["HASHING"],"topicsBy":"site"},{"id":4,"l":[{"p":"What must be true for the foreach and compareTo code to compile?"}],"k":"sata","o":["JeopardyBoard implements Iterable","JeopardyBoard implements Iterator","Tile implements Iterable","Tile implements Iterator","Tile has a compareTo method","Tile implements Comparable","Tile implements Comparator","None"],"a":[0,4],"topics":["ITERATORS","COMPARATORS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/2","n":"2","t":"2. Implementation Inheritance (7 pts)","b":[{"s":[{"p":"MaxStringList extends ArrayList<String> and maxString returns the alphabetically last item. No edge cases required."},{"c":"@Test public void testMaxString() {\n  MaxStringList msl = new MaxStringList();\n  ⟪a⟫\n  ⟪b⟫\n  ⟪c⟫\n}","lang":"java"}]},{"id":10,"l":[{"p":"Add a first test string"}],"k":"blank","a":["msl.add(\"cat\");"],"topics":["TESTING","INHERITANCE"],"topicsBy":"site"},{"id":11,"l":[{"p":"Add a larger test string"}],"k":"blank","a":["msl.add(\"zebra\");"],"topics":["TESTING","INHERITANCE"],"topicsBy":"site"},{"id":12,"l":[{"p":"Assert expected maximum"}],"k":"blank","a":["assertThat(msl.maxString()).isEqualTo(\"zebra\");"],"topics":["TESTING","INHERITANCE"],"topicsBy":"site"},{"s":[{"c":"public String maxString() {\n  String biggest = ⟪d⟫;\n  for (String s : this) {\n    if (⟪e⟫) { ⟪f⟫ }\n  }\n  return ⟪g⟫;\n}","lang":"java"}]},{"id":13,"l":[{"p":"Initialize maximum"}],"k":"blank","a":["this.get(0)"],"topics":["INHERITANCE","SORTING"],"topicsBy":"site"},{"id":14,"l":[{"p":"Compare strings"}],"k":"blank","a":["biggest.compareTo(s) <= 0"],"topics":["INHERITANCE","SORTING"],"topicsBy":"site"},{"id":15,"l":[{"p":"Update maximum"}],"k":"blank","a":["biggest = s;"],"topics":["INHERITANCE","SORTING"],"topicsBy":"site"},{"id":16,"l":[{"p":"Return maximum"}],"k":"blank","a":["biggest"],"topics":["INHERITANCE","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/3","n":"3","t":"3. Clubs and Countries (11 pts)","b":[{"s":[{"p":"Each Club has Map<Student, Country> countryMap. Count unique students by country across clubs; each student maps to the same country in every club."},{"c":"Map<Country,Integer> counts = ⟪a⟫;\nSet<Student> uniqueStudents = ⟪b⟫;\nfor (Club club : ⟪c⟫) {\n  for (Student s : ⟪d⟫.countryMap.keySet()) {\n    Country c = ⟪e⟫.countryMap.get(s);\n    if (!⟪f⟫.contains(s)) {\n      if (!counts.containsKey(c)) {\n        ⟪g⟫\n      } else {\n        ⟪h⟫\n      }\n      ⟪i⟫\n    }\n  }\n}\nreturn counts;","lang":"java"}]},{"id":20,"l":[{"p":"Create result map"}],"k":"blank","a":["new HashMap<>()"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":21,"l":[{"p":"Create duplicate-detection set"}],"k":"blank","a":["new HashSet<>()"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":22,"l":[{"p":"Iterate clubs"}],"k":"blank","a":["allClubs"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":23,"l":[{"p":"Current club"}],"k":"blank","a":["club"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":24,"l":[{"p":"Country lookup map"}],"k":"blank","a":["club"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":25,"l":[{"p":"Unique students set"}],"k":"blank","a":["uniqueStudents"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":26,"l":[{"p":"Initialize country count"}],"k":"blank","a":["counts.put(c, 1);"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":27,"l":[{"p":"Increment count"}],"k":"blank","a":["counts.put(c, counts.get(c) + 1);"],"topics":["HASHING","ADTS"],"topicsBy":"site"},{"id":28,"l":[{"p":"Mark student counted"}],"k":"blank","a":["uniqueStudents.add(s);"],"topics":["HASHING","ADTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/4","n":"4","t":"4. Taste the Rainbow (12 pts)","b":[{"s":[{"p":"Rainbow order alternates taking an item from the back then the front. For example [1,2,3,4,5] becomes [5,1,4,2,3]."}]},{"id":40,"l":[{"p":"Next-pointer order for deque [1,2,3,4,5] after rainbowfy"}],"k":"blank","a":["sentinel → 5 → 1 → 4 → 2 → 3 → sentinel"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"s":[{"p":"For next pointers, use Node left=sentinel and Node right=sentinel.prev. During even loop iterations, link left.next to right and advance left to the old left.next. During odd iterations, link right.next to left and advance right to right.prev. Close the circle at the middle node."},{"c":"for (int i=0; i<this.size(); i++) {\n  if (i % 2 == 0) {\n    Node temp = left.next;\n    ⟪a⟫\n    ⟪b⟫\n  } else {\n    ⟪c⟫\n    ⟪d⟫\n  }\n}\n⟪e⟫","lang":"java"}]},{"id":41,"l":[{"p":"Link left to right"}],"k":"blank","a":["left.next = right;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":42,"l":[{"p":"Advance left cursor"}],"k":"blank","a":["left = temp;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":43,"l":[{"p":"Link right to left"}],"k":"blank","a":["right.next = left;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":44,"l":[{"p":"Advance right cursor"}],"k":"blank","a":["right = right.prev;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":45,"l":[{"p":"Close circular list"}],"k":"blank","a":["left.next = sentinel;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"s":[{"p":"Assume rainbowfyNexts has just been called. Rebuild all prev pointers by walking forward from sentinel through the new next chain."},{"c":"Node curr = ⟪f⟫;\nfor (int i=0; i ⟪g⟫; i++) {\n  ⟪h⟫\n  ⟪i⟫\n}","lang":"java"}]},{"id":46,"l":[{"p":"Start at sentinel"}],"k":"blank","a":["sentinel"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":47,"l":[{"p":"Visit through sentinel at end"}],"k":"blank","a":["<= this.size()"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":48,"l":[{"p":"Set next node’s prev pointer"}],"k":"blank","a":["curr.next.prev = curr;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":49,"l":[{"p":"Advance"}],"k":"blank","a":["curr = curr.next;"],"topics":["LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/5","n":"5","t":"5. Potpourri (21 pts)","b":[{"id":60,"l":[{"p":"Insert N unique integers into a BST: which statement is true?"}],"k":"mc","o":["Any order is O(N log N)","A good order exists and can always be found in O(N log N)","A good order exists but cannot always be found in O(N log N)","No order can achieve O(N log N)"],"a":1,"topics":["BSTS","ASYMPTOTICS"],"topicsBy":"site"},{"id":61,"l":[{"p":"Which traversals may change after rotateLeft on a BST?"}],"k":"sata","o":["Preorder","Inorder","Postorder"],"a":[0,2],"topics":["BSTS","TREE_TRAVERSALS"],"topicsBy":"site"},{"id":62,"l":[{"p":"For a perfectly balanced BST with hundreds of nodes, which traversal can match BFS from the root?"}],"k":"mc","o":["Preorder","Inorder","Postorder","None"],"a":3,"topics":["BSTS","TREE_TRAVERSALS"],"topicsBy":"site"},{"s":[{"p":"Min-heap shape: root P; children E,Y. E has children 40,R; Y has children 20,I. Node 40 has children N,K; R has children A,O. All values are unique integers."}]},{"id":63,"l":[{"p":"Which nodes could hold 19?"}],"k":"sata","o":["P","E","Y","R","I","N","K","A","O"],"a":[1,2,3,4,7,8],"topics":["HEAPS"],"topicsBy":"site"},{"id":64,"l":[{"p":"True runtime bounds for Weighted Quick Union without path compression?"}],"k":"sata","o":["union is O(log N)","union is O(N)","isConnected is O(1)","isConnected is O(log N)","None"],"a":[0,1,3],"topics":["DISJOINT_SETS","ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"Weighted Quick Union with path compression has parent links: 0 is root with children 1 and 2; node 2 has children 3 and 4. 5 is root with child 6. Call isConnected(3,5)."}]},{"id":65,"l":[{"p":"Parent array afterward"}],"k":"blank","a":["[-5, 0, 0, 0, 2, -2, 5]"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":66,"l":[{"p":"Worst-case time to add N strings to a hash set with linked-list buckets"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(N log N)","Θ(N²)","None"],"a":3,"topics":["HASHING","ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"Trie stores [\"a\", \"apes\", \"in\", \"inch\", \"into\"]."}]},{"id":67,"l":[{"p":"Which contains(key) calls return true?"}],"k":"sata","o":["\"\"","\"a\"","\"apes\"","\"inc\"","\"inches\""],"a":[1,2],"topics":["TRIES"],"topicsBy":"site"},{"id":68,"l":[{"p":"How many nodes are created by add(\"ape\")?"}],"k":"mc","o":["0","1","2","3","4 or more"],"a":0,"topics":["TRIES"],"topicsBy":"site"},{"id":69,"l":[{"p":"How many nodes are created by add(\"bee\")?"}],"k":"mc","o":["0","1","2","3","4 or more"],"a":3,"topics":["TRIES"],"topicsBy":"site"},{"s":[{"p":"Starting array [6,3,2,7,5,1,4,8,0,9]. Intermediate arrays: A=[5,3,4,2,0,1,6,7,8,9], B=[2,1,0,3,5,4,6,7,8,9], C=[3,6,2,5,7,1,4,0,8,9], D=[1,2,3,5,6,7,4,8,0,9]."}]},{"id":70,"l":[{"p":"Which array can be an intermediate 3-scan Quicksort state with leftmost pivot and no shuffle?"}],"k":"mc","o":["A","B","C","D"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":71,"l":[{"p":"Which array can be an intermediate state of bottom-up max-heapsort?"}],"k":"mc","o":["A","B","C","D"],"a":0,"topics":["HEAPS","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/6","n":"6","t":"6. Midterm 2 Nostalgia (25 pts)","b":[{"id":80,"l":[{"p":"Runtime of rushil: three calls on N/3 and two Θ(N) operations"}],"k":"mc","o":["Θ(N)","Θ(N log N)","Θ(N²)","Θ(3^N)","Infinite loop"],"a":1,"topics":["RECURSION","ASYMPTOTICS"],"topicsBy":"site"},{"id":81,"l":[{"p":"Runtime of lucky: outer i descends from N−1; inner loop runs 2^i times"}],"k":"mc","o":["Θ(N)","Θ(2^N)","Θ(N²)","Θ(N log N)","Infinite loop"],"a":1,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":82,"l":[{"p":"Runtime of unlucky: Θ(N) work plus two reducer(N), each Θ(N) work then calls unlucky(N/2)"}],"k":"mc","o":["Θ(N)","Θ(N log N)","Θ(N²)","Θ(2^N)","Infinite loop"],"a":1,"topics":["RECURSION","ASYMPTOTICS"],"topicsBy":"site"},{"id":83,"l":[{"p":"Dijkstra from s, with negative edges only leaving s and all later edges nonnegative: select classifications that were accepted."}],"k":"sata","o":["Always correct","Sometimes correct","Never correct"],"a":[0,1],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":84,"l":[{"p":"With unique edge weights, does Kruskal give the same MST as Prim from any start?"}],"k":"mc","o":["Always","Sometimes","Never"],"a":0,"topics":["MSTS"],"topicsBy":"site"},{"id":85,"l":[{"p":"Connected graph with even E; E/2 edges weight 6, E/2 weight −7. Does an MST have total weight ≤0?"}],"k":"mc","o":["Always","Sometimes","Never"],"a":1,"topics":["MSTS"],"topicsBy":"site"},{"id":86,"l":[{"p":"BST with 15 nodes: minimum height"}],"k":"blank","a":["3"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":87,"l":[{"p":"BST with 15 nodes: maximum height"}],"k":"blank","a":["14"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":88,"l":[{"p":"Heap with 15 nodes: minimum height"}],"k":"blank","a":["3"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":89,"l":[{"p":"Heap with 15 nodes: maximum height"}],"k":"blank","a":["3"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":90,"l":[{"p":"LLRB with 15 nodes: minimum height"}],"k":"blank","a":["3"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":91,"l":[{"p":"LLRB with 15 nodes: maximum height"}],"k":"blank","a":["5"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":92,"l":[{"p":"Connected Weighted Quick Union of 15 items: minimum height"}],"k":"blank","a":["1"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"},{"id":93,"l":[{"p":"Connected Weighted Quick Union of 15 items: maximum height"}],"k":"blank","a":["3"],"topics":["BSTS","HEAPS","RED_BLACK_TREES","DISJOINT_SETS"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/7","n":"7","t":"7. Hashing (3 pts)","b":[{"s":[{"c":"int n=1;\nfor (int i=0; i<this.length(); i++) {\n  n *= ((i+1) * charToInt(this.charAt(i)));\n}\nreturn n;","lang":"java"}]},{"id":100,"l":[{"p":"Different lowercase string with same hash as \"ab\", without overflow"}],"k":"blank","a":["ba"],"topics":["HASHING"],"topicsBy":"site"},{"id":101,"l":[{"p":"Is this hashCode valid with respect to equals?"}],"k":"mc","o":["True","False"],"a":0,"topics":["HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-fa25-final/8","n":"8","t":"8. Sort City (15 pts)","b":[{"id":110,"l":[{"p":"Long employee array already alphabetized by name; sort by birthday while keeping equal birthdays alphabetized"}],"k":"mc","o":["Insertion sort","Heapsort","Merge sort","Selection sort"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":111,"l":[{"p":"Sort a long array of integers in [0, 2147483647]"}],"k":"mc","o":["Insertion sort","Heapsort","Merge sort","Radix sort"],"a":3,"topics":["SORTING","RADIX_SORTS"],"topicsBy":"site"},{"id":112,"l":[{"p":"Sort a long array by size property in {small, medium, large}"}],"k":"mc","o":["Insertion sort","Heapsort","Counting sort","Quicksort","Merge sort"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":113,"l":[{"p":"Fastest on real-world hardware for a long array of Comparable Dogs"}],"k":"mc","o":["Insertion sort","Heapsort","Counting sort","Quicksort","Merge sort","Radix sort"],"a":3,"topics":["SORTING"],"topicsBy":"site"},{"id":114,"l":[{"p":"Sort a long Dog array already sorted except for its last five elements"}],"k":"mc","o":["Insertion sort","Heapsort","Counting sort","Quicksort","Merge sort","Radix sort"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"id":115,"l":[{"p":"Which sort has asymptotically fewest swaps in its worst case?"}],"k":"mc","o":["Insertion sort","Heapsort","Quicksort","Selection sort"],"a":3,"topics":["SORTING"],"topicsBy":"site"},{"id":116,"l":[{"p":"Advantages of Hoare partition over 3-scan partition"}],"k":"sata","o":["Runs in fewer seconds","Uses less memory","Better asymptotic worst case","Stable"],"a":[0,1],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"c":"plantSort([4,3,7,2,8])","lang":"java"}]},{"id":117,"l":[{"p":"Number of swaps plantSort performs on [4,3,7,2,8]"}],"k":"mc","o":["2","3","4","6","7","8"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":118,"l":[{"p":"plantSort best-case runtime"}],"k":"mc","o":["Θ(N)","Θ(N log N)","Θ(N²)","Θ(2^N)","Other"],"a":0,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":119,"l":[{"p":"plantSort worst-case runtime"}],"k":"mc","o":["Θ(N)","Θ(N log N)","Θ(N²)","Θ(2^N)","Other"],"a":2,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":120,"l":[{"p":"Is plantSort stable?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["SORTING"],"topicsBy":"site"}],"topics":null}],"by":["Hug","Kao"]},{"id":"61b-fa25-mt1","t":"Fall 2025 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1JgeEzo5QL3UxhZnQufMjTuL3LvuS7M3u/view","sol":"https://drive.google.com/file/d/1UMUQrPH8VGi7Rg4Y41txtG-D2ebfFUSz/view","topics":"fa25-mt1"},"p":[{"id":"61b-fa25-mt1/1","n":"1","t":"1. Map (12.0 pts)","b":[{"s":[{"p":"Fill in rankedAbove, which takes a list of Players and returns a map from each Player to their rank: the highest score has rank 1, the next-highest rank 2, and so on. For example, players with scores 500, 800, 1200 and 100 get ranks 3, 2, 1 and 4. No two players have the same score. Don’t worry about efficiency."},{"c":"public class Player {\n    public double score;\n\n    public static Map<Player, Integer> rankedAbove(List<Player> players) {\n        ⟪a⟫ results = ⟪b⟫;\n        for (Player ⟪c⟫) {\n            ⟪d⟫;\n            for (Player p2 : players) {\n                if (⟪e⟫) {\n                    ⟪f⟫;\n                }\n            }\n        }\n        return results;\n    }\n}","lang":"java","f":{"a":"Map<Player, Integer>","b":"new HashMap<>()","c":"p1 : players","d":"results.put(p1, 1)","e":"p2.score > p1.score","f":"results.put(p1, results.get(p1) + 1)"}}]},{"id":1,"l":[{"p":"(a) The type of results"}],"k":"blank","a":["Map<Player, Integer>","HashMap<Player, Integer>","TreeMap<Player, Integer>"],"topics":["ADTS","ITERATION"],"part":"a"},{"id":2,"l":[{"p":"(b) results = ____"}],"k":"blank","a":["new HashMap<>()","new TreeMap<>()","new HashMap<Player, Integer>()"],"topics":["ADTS","ITERATION"],"part":"b"},{"id":3,"l":[{"p":"(c) for (Player ____)"}],"k":"blank","a":["p1 : players"],"topics":["ADTS","ITERATION"],"part":"c"},{"id":4,"l":[{"p":"(d) First line of the loop"}],"k":"blank","a":["results.put(p1, 1)"],"topics":["ADTS","ITERATION"],"part":"d"},{"id":5,"l":[{"p":"(e) if (____)"}],"k":"blank","a":["p2.score > p1.score","p1.score < p2.score"],"topics":["ADTS","ITERATION"],"part":"e"},{"id":6,"l":[{"p":"(f) Inside the if"}],"k":"blank","a":["results.put(p1, results.get(p1) + 1)"],"topics":["ADTS","ITERATION"],"x":"Each player’s rank is 1 plus the number of players with a higher score. (Alternatively, count into a local int rank and put it once after the inner loop.)","part":"f"}],"topics":null},{"id":"61b-fa25-mt1/2","n":"2","t":"2. Equals (6.0 pts)","b":[{"s":[{"p":"Fill in equals: two GoatMeasurements are equal if and only if they have the same name and their sizes differ by at most 0.1. name is never null. Hint: Math.abs. Syntax hint: if (o instanceof Dog uddaDog)."},{"c":"public class GoatMeasurement {\n    public String name;\n    public double size;\n\n    @Override\n    public boolean equals(Object o) {\n        if (⟪a⟫) {\n            return (⟪b⟫ &&\n                    ⟪c⟫);\n        }\n        return ⟪d⟫;\n    }\n}","lang":"java","f":{"a":"o instanceof GoatMeasurement other","b":"name.equals(other.name)","c":"Math.abs(size - other.size) <= 0.1","d":"false"}}]},{"id":7,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["o instanceof GoatMeasurement other"],"topics":["EQUALS"],"part":"a"},{"id":8,"l":[{"p":"(b) The first condition"}],"k":"blank","a":["name.equals(other.name)","this.name.equals(other.name)","other.name.equals(name)"],"topics":["EQUALS"],"part":"b"},{"id":9,"l":[{"p":"(c) The second condition"}],"k":"blank","a":["Math.abs(size - other.size) <= 0.1","Math.abs(this.size - other.size) <= 0.1","Math.abs(other.size - size) <= 0.1"],"topics":["EQUALS"],"part":"c"},{"id":10,"l":[{"p":"(d) return ____"}],"k":"blank","a":["false"],"topics":["EQUALS"],"x":"Compare strings with equals, not ==.","part":"d"}],"topics":null},{"id":"61b-fa25-mt1/3","n":"3","t":"3. LinkedListDeque61B Addition (10.0 pts)","b":[{"s":[{"p":"Implement add for the Project 1 LinkedListDeque61B, which adds x at position idx: add(1, \"zoo\") changes [ant, bee, cat] to [ant, zoo, bee, cat]. idx is always within [0, size). You may not use any if statements."},{"c":"public class LinkedListDeque61B<T> implements Deque61B<T> {\n    private Node sentinel; // Circular linked list topology\n    private int size;\n\n    private class Node {\n        public T value;\n        public Node prev, next;\n        public Node(T value, Node prev, Node next) {\n            this.value = value;\n            this.prev = prev;\n            this.next = next;\n        }\n    }\n    ...\n    public void add(int idx, T x) {\n        ⟪a⟫;\n        for (⟪b⟫) {\n            ⟪c⟫;\n        }\n        ⟪d⟫;\n        ⟪e⟫;\n        ⟪f⟫;\n        ⟪g⟫;\n    }\n}","lang":"java","f":{"a":"Node curr = sentinel","b":"int i = 0; i < idx; i++","c":"curr = curr.next","d":"Node newNode = new Node(x, curr, curr.next)","e":"curr.next.prev = newNode","f":"curr.next = newNode","g":"size++"}}]},{"id":11,"l":[{"p":"(a) First line"}],"k":"blank","a":["Node curr = sentinel"],"topics":["LINKED_LISTS","DEQUES"],"part":"a"},{"id":12,"l":[{"p":"(b) The loop header"}],"k":"blank","a":["int i = 0; i < idx; i++","int i = 0; i < idx; i += 1"],"topics":["LINKED_LISTS","DEQUES"],"part":"b"},{"id":13,"l":[{"p":"(c) The loop body"}],"k":"blank","a":["curr = curr.next"],"topics":["LINKED_LISTS","DEQUES"],"part":"c"},{"id":14,"l":[{"p":"(d) Make the new node"}],"k":"blank","a":["Node newNode = new Node(x, curr, curr.next)"],"topics":["LINKED_LISTS","DEQUES"],"part":"d"},{"id":15,"l":[{"p":"(e) Next line"}],"k":"blank","a":["curr.next.prev = newNode"],"topics":["LINKED_LISTS","DEQUES"],"part":"e"},{"id":16,"l":[{"p":"(f) Next line"}],"k":"blank","a":["curr.next = newNode"],"topics":["LINKED_LISTS","DEQUES"],"part":"f"},{"id":17,"l":[{"p":"(g) Last line"}],"k":"blank","a":["size++","size += 1","size = size + 1"],"topics":["LINKED_LISTS","DEQUES"],"x":"Walk idx steps from the sentinel to the node before the new one, then link the new node between it and its next. The order of (e) and (f) matters: set curr.next last.","part":"g"}],"topics":null},{"id":"61b-fa25-mt1/4","n":"4","t":"4. A Default Method (12.0 pts)","b":[{"s":[{"p":"Implement rotateToFront, which rotates a deque left until the first element equal to x is at the front; if x isn’t there, the order must not change. Return true if x was found. For example, rotateToFront(9) changes [1, 2, 9, 3, 4, 9] to [9, 3, 4, 9, 1, 2]. x isn’t null and the deque has no nulls. You may use any Deque61B method (getFirst, removeFirst, addLast, get, size, …). You may not use new."},{"c":"public interface Deque61B<T> {\n    ...\n    default boolean rotateToFront(T x) {\n        ⟪a⟫;\n        while (⟪b⟫) {\n            if (⟪c⟫) {\n                ⟪d⟫;\n            }\n            ⟪e⟫;\n            ⟪f⟫;\n        }\n        ⟪g⟫;\n    }\n}","lang":"java","f":{"a":"int rotations = 0","b":"rotations < size()","c":"getFirst().equals(x)","d":"return true","e":"addLast(removeFirst())","f":"rotations += 1","g":"return false"}}]},{"id":18,"l":[{"p":"(a) First line"}],"k":"blank","a":["int rotations = 0"],"topics":["DEQUES","ABSTRACTION"],"part":"a"},{"id":19,"l":[{"p":"(b) while (____)"}],"k":"blank","a":["rotations < size()"],"topics":["DEQUES","ABSTRACTION"],"part":"b"},{"id":20,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["getFirst().equals(x)","x.equals(getFirst())","get(0).equals(x)"],"topics":["DEQUES","ABSTRACTION"],"part":"c"},{"id":21,"l":[{"p":"(d) Inside the if"}],"k":"blank","a":["return true"],"topics":["DEQUES","ABSTRACTION"],"part":"d"},{"id":22,"l":[{"p":"(e) Rotate by one"}],"k":"blank","a":["addLast(removeFirst())"],"topics":["DEQUES","ABSTRACTION"],"part":"e"},{"id":23,"l":[{"p":"(f) Count it"}],"k":"blank","a":["rotations += 1","rotations++","rotations = rotations + 1"],"topics":["DEQUES","ABSTRACTION"],"part":"f"},{"id":24,"l":[{"p":"(g) After the loop"}],"k":"blank","a":["return false"],"topics":["DEQUES","ABSTRACTION"],"x":"After size() rotations without finding x, the deque is back in its original order.","part":"g"}],"topics":null},{"id":"61b-fa25-mt1/5","n":"5","t":"5. Resize (10.0 pts)","b":[{"s":[{"p":"Implement resize for the Project 2 ArrayDeque61B: resize the backing array to length capacity with the items in order starting at index 0, and update nextFirst and nextLast. You may use Deque61B methods; capacity is at least the number of items. Syntax hint: Glorp[] arrayOfGenerics = (Glorp[]) new Object[61];"},{"c":"public class ArrayDeque61B<T> implements Deque61B<T> {\n    private T[] items;\n    private int size;      // Total number of items in the deque\n    private int nextFirst; // Index where addFirst will add an item if called next\n    private int nextLast;  // Index where addLast will add an item if called next\n    ...\n    private void resize(int capacity) {\n        ⟪a⟫;\n        for (⟪b⟫) {\n            ⟪c⟫;\n        }\n        ⟪d⟫;\n        ⟪e⟫;\n        ⟪f⟫;\n    }\n}","lang":"java","f":{"a":"T[] a = (T[]) new Object[capacity]","b":"int i = 0; i < size; i += 1","c":"a[i] = get(i)","d":"items = a","e":"nextFirst = items.length - 1","f":"nextLast = size"}}]},{"id":25,"l":[{"p":"(a) First line"}],"k":"blank","a":["T[] a = (T[]) new Object[capacity]"],"topics":["ARRAYS","DEQUES"],"part":"a"},{"id":26,"l":[{"p":"(b) The loop header"}],"k":"blank","a":["int i = 0; i < size; i += 1","int i = 0; i < size; i++","int i = 0; i < size(); i++"],"topics":["ARRAYS","DEQUES"],"part":"b"},{"id":27,"l":[{"p":"(c) The loop body"}],"k":"blank","a":["a[i] = get(i)"],"topics":["ARRAYS","DEQUES"],"part":"c"},{"id":28,"l":[{"p":"(d) Next line"}],"k":"blank","a":["items = a"],"topics":["ARRAYS","DEQUES"],"part":"d"},{"id":29,"l":[{"p":"(e) nextFirst"}],"k":"blank","a":["nextFirst = items.length - 1","nextFirst = capacity - 1","nextFirst = a.length - 1"],"topics":["ARRAYS","DEQUES"],"part":"e"},{"id":30,"l":[{"p":"(f) nextLast"}],"k":"blank","a":["nextLast = size"],"topics":["ARRAYS","DEQUES"],"x":"With the items at 0 … size − 1, the next addLast goes at size and the next addFirst wraps to the last index.","part":"f"}],"topics":null},{"id":"61b-fa25-mt1/6","n":"6","t":"6. Prime Factorization (16.0 pts)","b":[{"s":[{"p":"primeFactors takes an int x > 1 and returns its prime factors in increasing order; e.g. primeFactors(60) returns [2, 2, 3, 5]."},{"p":"6.1 smallestPrimeFactor returns x’s smallest prime factor, e.g. 2 for 60 and 3 for 63."},{"c":"public static int smallestPrimeFactor(int x) {\n    ⟪a⟫;\n    while (true) {\n        if (⟪b⟫) {\n            ⟪c⟫;\n        }\n        ⟪d⟫;\n    }\n}","lang":"java","f":{"a":"int i = 2","b":"x % i == 0","c":"return i","d":"i += 1"}}]},{"id":31,"l":[{"p":"6.1 (a)"}],"k":"blank","a":["int i = 2"],"topics":["ITERATION"]},{"id":32,"l":[{"p":"6.1 (b) if (____)"}],"k":"blank","a":["x % i == 0"],"topics":["ITERATION"]},{"id":33,"l":[{"p":"6.1 (c)"}],"k":"blank","a":["return i"],"topics":["ITERATION"]},{"id":34,"l":[{"p":"6.1 (d)"}],"k":"blank","a":["i += 1","i++","i = i + 1"],"topics":["ITERATION"],"x":"The first divisor found counting up from 2 is always prime."},{"s":[{"p":"6.2 addAllPrimeFactors adds all prime factors of x to factors, using recursion. You may use smallestPrimeFactor."},{"c":"public static void addAllPrimeFactors(int x, List<Integer> factors) {\n    if (⟪e⟫) {\n        ⟪f⟫;\n    }\n    ⟪g⟫;\n    ⟪h⟫;\n    ⟪i⟫;\n}","lang":"java","f":{"e":"x == 1","f":"return","g":"int spf = smallestPrimeFactor(x)","h":"factors.add(spf)","i":"addAllPrimeFactors(x / spf, factors)"}}]},{"id":35,"l":[{"p":"6.2 if (____)"}],"k":"blank","a":["x == 1","x <= 1","x < 2"],"topics":["LISTS","RECURSION"]},{"id":36,"l":[{"p":"6.2 Inside the if"}],"k":"blank","a":["return"],"topics":["LISTS","RECURSION"]},{"id":37,"l":[{"p":"6.2 Next line"}],"k":"blank","a":["int spf = smallestPrimeFactor(x)"],"topics":["LISTS","RECURSION"]},{"id":38,"l":[{"p":"6.2 Next line"}],"k":"blank","a":["factors.add(spf)"],"topics":["LISTS","RECURSION"]},{"id":39,"l":[{"p":"6.2 The recursive call"}],"k":"blank","a":["addAllPrimeFactors(x / spf, factors)"],"topics":["LISTS","RECURSION"]},{"s":[{"p":"6.3 primeFactors returns all prime factors of x in increasing order, using the helpers."},{"c":"public static List<Integer> primeFactors(int x) {\n    ⟪j⟫;\n    ⟪k⟫;\n    return ⟪l⟫;\n}","lang":"java","f":{"j":"List<Integer> factors = new ArrayList<>()","k":"addAllPrimeFactors(x, factors)","l":"factors"}}]},{"id":40,"l":[{"p":"6.3 First line"}],"k":"blank","a":["List<Integer> factors = new ArrayList<>()","List<Integer> factors = new LinkedList<>()"],"topics":["LISTS","RECURSION"]},{"id":41,"l":[{"p":"6.3 Second line"}],"k":"blank","a":["addAllPrimeFactors(x, factors)"],"topics":["LISTS","RECURSION"]},{"id":42,"l":[{"p":"6.3 return ____"}],"k":"blank","a":["factors"],"topics":["LISTS","RECURSION"]}],"topics":null},{"id":"61b-fa25-mt1/7","n":"7","t":"7. Ejection (20.0 pts)","b":[{"s":[{"p":"The eject methods remove all appearances of int y from an IntList."},{"p":"7.1 Fill in ejectND, which is non-destructive."},{"c":"public static IntList ejectND(IntList x, int y) {\n    if (⟪a⟫) {\n        ⟪b⟫;\n    }\n    if (⟪c⟫) {\n        return ⟪d⟫;\n    }\n    return new ⟪e⟫;\n}","lang":"java","f":{"a":"x == null","b":"return null","c":"x.first == y","d":"ejectND(x.rest, y)","e":"IntList(x.first, ejectND(x.rest, y))"}}]},{"id":43,"l":[{"p":"7.1 if (____)"}],"k":"blank","a":["x == null"],"topics":["LINKED_LISTS","RECURSION"]},{"id":44,"l":[{"p":"7.1 Inside it"}],"k":"blank","a":["return null"],"topics":["LINKED_LISTS","RECURSION"]},{"id":45,"l":[{"p":"7.1 if (____)"}],"k":"blank","a":["x.first == y"],"topics":["LINKED_LISTS","RECURSION"]},{"id":46,"l":[{"p":"7.1 return ____"}],"k":"blank","a":["ejectND(x.rest, y)"],"topics":["LINKED_LISTS","RECURSION"]},{"id":47,"l":[{"p":"7.1 return new ____"}],"k":"blank","a":["IntList(x.first, ejectND(x.rest, y))"],"topics":["LINKED_LISTS","RECURSION"]},{"s":[{"p":"7.2 Fill in ejectD, which is destructive. You may not use new. (Staff called this one of the most difficult questions on the exam.)"},{"c":"public static IntList ejectD(IntList x, int y) {\n    if (⟪f⟫) {\n        ⟪g⟫;\n    }\n    ⟪h⟫;\n    if (x.first == y) {\n        return ⟪i⟫;\n    }\n    return ⟪j⟫;\n}","lang":"java","f":{"f":"x == null","g":"return null","h":"x.rest = ejectD(x.rest, y)","i":"x.rest","j":"x"}}]},{"id":48,"l":[{"p":"7.2 if (____)"}],"k":"blank","a":["x == null"],"topics":["LINKED_LISTS","RECURSION"]},{"id":49,"l":[{"p":"7.2 Inside it"}],"k":"blank","a":["return null"],"topics":["LINKED_LISTS","RECURSION"]},{"id":50,"l":[{"p":"7.2 The line before the second if"}],"k":"blank","a":["x.rest = ejectD(x.rest, y)"],"topics":["LINKED_LISTS","RECURSION"]},{"id":51,"l":[{"p":"7.2 return ____ (x.first is y)"}],"k":"blank","a":["x.rest"],"topics":["LINKED_LISTS","RECURSION"]},{"id":52,"l":[{"p":"7.2 return ____"}],"k":"blank","a":["x"],"topics":["LINKED_LISTS","RECURSION"],"x":"Fix the rest of the list first, then drop this node by returning what follows it, or keep it."}],"topics":null},{"id":"61b-fa25-mt1/8","n":"8","t":"8. LEQIterator (14.0 pts)","b":[{"s":[{"p":"LEQIterator iterates over all numbers in an IntList that are less than or equal to the integer at the front of the list. For example, for IntList.of(25, 30, 10, 5, 90, 25, 80) it yields 25, 10, 5, 25. L is not null, and you don’t need to throw exceptions."},{"c":"public class LEQIterator implements Iterator<Integer> {\n    private ⟪a⟫ current;\n    private ⟪b⟫ frontNumber;\n\n    public LEQIterator(IntList L) {\n        ⟪c⟫;\n        ⟪d⟫;\n    }\n\n    public boolean hasNext() {\n        return ⟪e⟫;\n    }\n\n    public Integer next() {\n        ⟪f⟫;\n        ⟪g⟫;\n        while (⟪h⟫ &&\n               ⟪i⟫) {\n            ⟪j⟫;\n        }\n        return ⟪k⟫;\n    }\n}","lang":"java","f":{"a":"IntList","b":"int","c":"current = L","d":"frontNumber = L.first","e":"current != null","f":"int numToReturn = current.first","g":"current = current.rest","h":"current != null","i":"current.first > frontNumber","j":"current = current.rest","k":"numToReturn"}}]},{"id":53,"l":[{"p":"(a) The type of current"}],"k":"blank","a":["IntList"],"topics":["LINKED_LISTS","ITERATORS"],"part":"a"},{"id":54,"l":[{"p":"(b) The type of frontNumber"}],"k":"blank","a":["int","Integer"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":55,"l":[{"p":"(c) First line of the constructor"}],"k":"blank","a":["current = L"],"topics":["LINKED_LISTS","ITERATORS"],"part":"c"},{"id":56,"l":[{"p":"(d) Second line"}],"k":"blank","a":["frontNumber = L.first"],"topics":["LINKED_LISTS","ITERATORS"],"part":"d"},{"id":57,"l":[{"p":"(e) hasNext returns"}],"k":"blank","a":["current != null"],"topics":["LINKED_LISTS","ITERATORS"],"part":"e"},{"id":58,"l":[{"p":"(f) First line of next"}],"k":"blank","a":["int numToReturn = current.first"],"topics":["LINKED_LISTS","ITERATORS"],"part":"f"},{"id":59,"l":[{"p":"(g) Second line"}],"k":"blank","a":["current = current.rest"],"topics":["LINKED_LISTS","ITERATORS"],"part":"g"},{"id":60,"l":[{"p":"(h) First loop condition"}],"k":"blank","a":["current != null"],"topics":["LINKED_LISTS","ITERATORS"],"part":"h"},{"id":61,"l":[{"p":"(i) Second loop condition"}],"k":"blank","a":["current.first > frontNumber","frontNumber < current.first"],"topics":["LINKED_LISTS","ITERATORS"],"part":"i"},{"id":62,"l":[{"p":"(j) The loop body"}],"k":"blank","a":["current = current.rest"],"topics":["LINKED_LISTS","ITERATORS"],"part":"j"},{"id":63,"l":[{"p":"(k) return ____"}],"k":"blank","a":["numToReturn"],"topics":["LINKED_LISTS","ITERATORS"],"x":"next always leaves current on the next number to return (or null), skipping anything larger than the front number, so hasNext only needs a null check.","part":"k"}],"topics":null}],"by":["Hug","Kao"]},{"id":"61b-fa25-mt2","t":"Fall 2025 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1WNOhO4rwocWlMyz0bLerBfYCdgkTu7CH/view","sol":"https://drive.google.com/file/d/1fzNkhodp76K2_Nhvh2jOFexdyty52_lv/view","topics":"fa25-mt2"},"p":[{"id":"61b-fa25-mt2/1","n":"1","t":"1. Treevia (15.0 pts)","b":[{"s":[{"p":"Consider the tree below. The letters represent unknown integer values, and all 10 values are unique."},{"c":"              A\n          /       \\\n        B           C\n      /   \\       /   \\\n     D     E     F     G\n    / \\   /\n   H   I J","lang":"txt"}]},{"id":1,"l":[{"p":"1.1 Suppose the tree represents a max heap. Which could be the third-largest value?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","I","J"],"a":[1,2,3,4,5,6],"topics":["HEAPS"],"x":"A is the largest, so it can’t be third. Any of B–G can be: give it 8, its parent 9 and A 10 (e.g. A=10, B=8, C=9). H, I and J each have three ancestors, so at least three values are larger."},{"id":2,"l":[{"p":"1.2 Suppose the tree represents a binary search tree. Which could be the third-largest value?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","I","J"],"a":[5],"topics":["BSTS"],"x":"The three largest items are C, F and G, the ones greater than A. F is the smallest of those."},{"id":3,"l":[{"p":"1.3 Suppose the tree represents a binary search tree. We delete A using Hibbard deletion. Which nodes could become the new root?"}],"k":"sata","o":["B","C","D","E","F","G","H","I","J"],"a":[3,4],"topics":["BSTS"],"x":"Hibbard deletion replaces A with its predecessor or its successor. The predecessor (largest item smaller than A) is E; the successor (smallest item larger than A) is F."},{"id":4,"l":[{"p":"1.4 Suppose we perform an in-order tree traversal of the subtree rooted at B. Which will be the last node visited?"}],"k":"mc","o":["B","D","E","H","I","J"],"a":2,"topics":["TREE_TRAVERSALS"],"x":"The in-order traversal is H, D, I, B, J, E."},{"id":5,"l":[{"p":"1.5 The statement “F is strictly greater than J” is always true if the tree represents a ______. Select all options that could go in the blank."}],"k":"sata","o":["Min heap","Max heap","BST","None"],"a":[2],"topics":["BSTS","HEAPS"],"x":"In a BST, F > A and A > J, so F > J. In either kind of heap, F and J are in different subtrees, so their order isn’t fixed: for example a min heap with F = 6 and J = 10, or a max heap with F = 1 and J = 5."},{"id":6,"l":[{"p":"1.6 Suppose we treat the tree as an undirected graph and run a breadth-first search starting from G. Which could be the last node visited?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","I","J","None"],"a":[7,8,9],"topics":["GRAPH_TRAVERSALS"],"x":"By distance from G: G; C; F, A; B; D, E; H, I, J. No tiebreaker is given, so any of H, I and J could be last."},{"id":7,"l":[{"p":"1.7 Suppose the tree represents a binary search tree, and we want to turn it into an LLRB. Select a set of edges to turn red so that the LLRB is valid."}],"k":"sata","o":["A–B","B–D","C–F","D–H","E–J","None, the tree is already a valid LLRB with all black links."],"a":[1,4],"topics":["RED_BLACK_TREES"],"x":"Every path from the root to a null must have the same number of black links. The nulls below H, I and J are 4 black links from the root, the rest 3. Red links can only lower those counts, so make B–D and E–J red: every null is then 3 away. As a 2-3 tree: A at the root, then BD and C, then H, I, EJ, F, G."}],"topics":null},{"id":"61b-fa25-mt2/2","n":"2","t":"2. Aditya’s Potpourri (16.0 pts)","b":[{"s":[{"p":"For 2.1 and 2.2, choose whether the following arrays represent a max heap, min heap, or neither."}]},{"id":8,"l":[{"p":"2.1 [-, 1, 7, 2, 8, 15, 5, 3, 17, 9]"}],"k":"mc","o":["Min heap","Max heap","Neither"],"a":0,"topics":["HEAPS"]},{"id":9,"l":[{"p":"2.2 [-, 59, 38, 47, 26, 46, 45, 13]"}],"k":"mc","o":["Min heap","Max heap","Neither"],"a":2,"topics":["HEAPS"],"x":"46 (index 5) is a child of 38 (index 2), so this isn’t a max heap; 59 at the root rules out a min heap."},{"id":10,"l":[{"p":"2.3 From a pool of n > 75 unique integers, Aditya wants to find the 75th-smallest element. Which data structure would be best for this task?"}],"k":"mc","o":["Hash table","Linked list","Max heap","Binary search tree"],"a":2,"also":[3],"topics":["ADTS","HEAPS"],"x":"A max heap that always holds the 75 smallest items so far finds it in Θ(n): add each item, and when the heap has 76 items, remove the largest. At the end, the largest item left is the 75th-smallest. Staff also accepted binary search tree, for the reading where the structure was already built."},{"id":11,"l":[{"p":"2.4 True or false: if hashCode() is a valid hash function, then hashCode() + c is also a valid hash function, where c is a fixed integer in [−1000000, 1000000]."}],"k":"mc","o":["True","False"],"a":0,"topics":["HASHING"],"x":"Valid means equal objects get equal hash codes, and an unchanged object always gets the same code. Adding the same constant keeps both true."},{"id":12,"l":[{"p":"2.5 True or false: if hashCode() is a valid hash function, then hashCode() * c is also a valid hash function, where c is a fixed integer in [−1000000, 1000000]."}],"k":"mc","o":["True","False"],"a":0,"topics":["HASHING"],"x":"Multiplying by the same constant keeps both conditions true, just as adding one does."},{"id":13,"l":[{"p":"2.6 True or false: finding a value is asymptotically faster in a 2-3 tree than in an LLRB, because a 2-3 tree has a shorter height."}],"k":"mc","o":["True","False"],"a":1,"topics":["B_TREES","RED_BLACK_TREES"],"x":"Both find items in O(log N), so there is no asymptotic difference."},{"id":14,"l":[{"p":"2.7 Suppose we have a valid LLRB, and we add an element which creates a right-leaning red link. With no other information, select all possible operations that could be the first balancing operation after the insertion."}],"k":"sata","o":["rotateLeft()","rotateRight()","colorFlip()"],"a":[0,2],"topics":["RED_BLACK_TREES"],"x":"Adding 4 to a lone 3 needs rotateLeft. Adding 4 to 3 with a red left child 2 needs colorFlip (two red children). rotateRight is only for two consecutive left-leaning red links, which a right-leaning insertion into a valid LLRB can’t create."},{"s":[{"p":"2.9: Josh built a valid Weighted Quick Union (without path compression) with 10 items, but lost one value in the parents array: [-1, 0, 0, 0, -1, 4, 4, 5, ?, 8]. (This array uses -1 instead of -size for roots.)"},{"c":"    0          4         ?\n  / | \\       / \\        |\n 1  2  3     5   6       8\n             |           |\n             7           9","lang":"txt"}]},{"id":15,"l":[{"p":"2.9 Assuming 8 is not a root, select all items that could be the parent of 8."}],"k":"sata","o":["0","1","2","3","4","5","6","7"],"a":[0,4],"topics":["DISJOINT_SETS"],"x":"A WQU tree of height H has at least 2ᴴ items. Under 1, 2 or 3, the tree would have height 3 with only 6 items; under 5, 6 or 7, height 3 or 4 with 6 items. Under 0 or 4 it’s a valid union: union(8, 0) or union(8, 4) from the state where 8 was a root."},{"id":16,"l":[{"p":"2.10 We are building a Weighted Quick Union (without path compression), and the object initially has zero connections. What is the minimum number of union operations needed to create a tree of height 3? (A tree’s height is the number of links from the root to the bottommost leaf; a fresh WQU has height 0.)"}],"k":"mc","o":["3","5","7","15","16","31","32"],"a":2,"topics":["DISJOINT_SETS"],"x":"Height 1 takes 1 union; height 2 takes two height-1 trees plus one more union (3); height 3 takes two height-2 trees plus one more (3 + 3 + 1 = 7)."}],"topics":null},{"id":"61b-fa25-mt2/3","n":"3","t":"3. Graphery (15.0 pts)","b":[{"s":[{"p":"A directed graph with these weighted edges:"},{"c":"A → B   5\nA → C   2\nA → D   3\nA → E   5\nB → D   2\nC → B   2\nD → E   1\nE → C   20","lang":"txt"},{"p":"Suppose we run Dijkstra’s on the graph above, starting at vertex A, tiebreaking by alphabetical order."}]},{"id":17,"l":[{"p":"3.1 In what order will the vertices be visited?"}],"k":"mc","o":["A, C, D, B, E","A, D, E, C, B","A, B, C, D, E","A, B, D, E, C"],"a":0,"topics":["SHORTEST_PATHS"],"x":"Dijkstra’s visits by distance from A: A (0), C (2), D (3), then B and E (both 4), B first alphabetically."},{"id":18,"l":[{"p":"3.2 Which vertices have their distTo value updated the most number of times?"}],"k":"sata","o":["A","B","C","D","E"],"a":[1,4],"topics":["SHORTEST_PATHS"],"x":"B: ∞ → 5 (A→B) → 4 (C→B). E: ∞ → 5 (A→E) → 4 (D→E). C and D are updated once each."},{"id":19,"l":[{"p":"3.3 Suppose we replace the edge weight for A → B from 5 with −1000. Will running Dijkstra’s from A still correctly return a shortest paths tree?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["SHORTEST_PATHS"],"x":"After relaxing A → B, no other path to B is shorter than −1000, so the tree it returns is still correct."},{"id":20,"l":[{"p":"3.4 Suppose we instead replace the edge weight E → C. If this edge weight gets too small, there would no longer be a finite shortest path from A to every vertex. What is the smallest weight for edge E → C such that there is still a finite shortest path from A to every vertex?"}],"k":"blank","a":["-5"],"topics":["SHORTEST_PATHS"],"x":"C → B → D → E → C is a cycle with weight 2 + 2 + 1 + (E → C). If it were negative you could go around forever, so E → C must be at least −5."},{"id":21,"l":[{"p":"3.5 Which edge, if reversed, causes the resulting graph to have a valid topological sort?"}],"k":"mc","o":["A → B","A → C","A → D","A → E","C → B","The graph already has a valid topological sort."],"a":4,"topics":["TOPOLOGICAL_SORT"],"x":"Only DAGs have topological sorts. The cycle is C → B → D → E → C, and C → B is the only one of its edges among the choices."},{"s":[{"p":"Consider the same graph, but with undirected edges. For 3.6 to 3.9, run Prim’s algorithm from vertex A, tiebreaking alphabetically."}]},{"id":22,"l":[{"p":"3.6 First edge added to the MST:"}],"k":"mc","o":["A-B","A-C","A-D","A-E","B-C","B-D","C-E","D-E"],"a":1,"topics":["MSTS"]},{"id":23,"l":[{"p":"3.7 Second edge added to the MST:"}],"k":"mc","o":["A-B","A-C","A-D","A-E","B-C","B-D","C-E","D-E"],"a":4,"topics":["MSTS"]},{"id":24,"l":[{"p":"3.8 Third edge added to the MST:"}],"k":"mc","o":["A-B","A-C","A-D","A-E","B-C","B-D","C-E","D-E"],"a":5,"topics":["MSTS"]},{"id":25,"l":[{"p":"3.9 Fourth edge added to the MST:"}],"k":"mc","o":["A-B","A-C","A-D","A-E","B-C","B-D","C-E","D-E"],"a":7,"topics":["MSTS"],"x":"Each step adds the lightest edge leaving the tree so far: A–C (2), then B–C (2), then B–D (2), then D–E (1)."},{"id":26,"l":[{"p":"3.10 For the graph above, the MST output by Kruskal’s algorithm is ____ the same as the MST output by Prim’s algorithm (from 3.6 to 3.9)."}],"k":"mc","o":["Always","Sometimes (depends on tiebreaking)","Never"],"a":0,"topics":["MSTS"],"x":"This graph’s MST is unique, so both algorithms must output it whatever the tiebreak."}],"topics":null},{"id":"61b-fa25-mt2/4","n":"4","t":"4. Project 4E (15.0 pts)","b":[{"s":[{"p":"Project 4 ignored the definitions of words, but Aditya likes definitions. Implement the WordDefinitions class below, such that getDefinitions returns all definitions of a word."},{"p":"Reminder: synsetsFile contains definitions for each synset. Here are some example lines from the file:"},{"c":"25,chill iciness,coldness from environment\n27,chill shivering,cold feeling","lang":"txt"},{"p":"Examples based on the lines above: getDefinitions(\"chill\") should return [\"coldness from environment\", \"cold feeling\"], and getDefinitions(\"shivering\") should return [\"cold feeling\"]."},{"p":"Hint: split(String token) divides a string into an array of substrings on each appearance of token. (The exam had more blank lines than the solution uses; this site shows only the ones it uses.)"},{"c":"public class WordDefinitions {\n    public ⟪a⟫ definitions;\n\n    public WordDefinitions(String synsetsFile) {\n        definitions = ⟪b⟫;\n        In synsetIn = new In(synsetsFile);\n        while (synsetIn.hasNextLine()) {\n            String line = synsetIn.readLine();\n            ⟪c⟫ splitLine = ⟪d⟫.split(⟪e⟫);\n            ⟪f⟫ splitWords = ⟪g⟫;\n            for (⟪h⟫ : ⟪i⟫) {\n                if (⟪j⟫ == null) {\n                    ⟪k⟫;\n                }\n                ⟪l⟫;\n            }\n        }\n    }\n\n    /* Assume word exists in the synsets file. */\n    public List<String> getDefinitions(String word) {\n        ⟪m⟫;\n    }\n}","lang":"java","f":{"a":"Map<String, List<String>>","b":"new HashMap<>()","c":"String[]","d":"line","e":"\",\"","f":"String[]","g":"splitLine[1].split(\" \")","h":"String word","i":"splitWords","j":"definitions.get(word)","k":"definitions.put(word, new ArrayList<>())","l":"definitions.get(word).add(splitLine[2])","m":"return definitions.get(word)"}}]},{"id":27,"l":[{"p":"(a) The type of definitions"}],"k":"blank","a":["Map<String, List<String>>","HashMap<String, List<String>>","TreeMap<String, List<String>>","Map<String, ArrayList<String>>","HashMap<String, ArrayList<String>>","TreeMap<String, ArrayList<String>>"],"topics":["JAVA","ADTS"],"part":"a"},{"id":28,"l":[{"p":"(b) definitions = ____"}],"k":"blank","a":["new HashMap<>()","new TreeMap<>()","new HashMap<String, List<String>>()","new HashMap<String, ArrayList<String>>()","new TreeMap<String, List<String>>()","new TreeMap<String, ArrayList<String>>()"],"topics":["JAVA","ADTS"],"part":"b"},{"id":29,"l":[{"p":"(c) The type of splitLine"}],"k":"blank","a":["String[]"],"topics":["JAVA","ADTS"],"x":"split returns an array, so List<String> doesn’t work.","part":"c"},{"id":30,"l":[{"p":"(d) ____.split(…)"}],"k":"blank","a":["line"],"topics":["JAVA","ADTS"],"part":"d"},{"id":31,"l":[{"p":"(e) The argument to split"}],"k":"blank","a":["\",\""],"topics":["JAVA","ADTS"],"part":"e"},{"id":32,"l":[{"p":"(f) The type of splitWords"}],"k":"blank","a":["String[]"],"topics":["JAVA","ADTS"],"part":"f"},{"id":33,"l":[{"p":"(g) splitWords = ____"}],"k":"blank","a":["splitLine[1].split(\" \")"],"topics":["JAVA","ADTS"],"x":"The second field (index 1) holds the synset’s words, separated by spaces.","part":"g"},{"id":34,"l":[{"p":"(h) The loop variable"}],"k":"blank","a":["String word"],"topics":["JAVA","ADTS"],"part":"h"},{"id":35,"l":[{"p":"(i) What the loop goes over"}],"k":"blank","a":["splitWords"],"topics":["JAVA","ADTS"],"part":"i"},{"id":36,"l":[{"p":"(j) if (____ == null)"}],"k":"blank","a":["definitions.get(word)","getDefinitions(word)"],"topics":["JAVA","ADTS"],"part":"j"},{"id":37,"l":[{"p":"(k) Inside the if"}],"k":"blank","a":["definitions.put(word, new ArrayList<>())"],"topics":["JAVA","ADTS"],"part":"k"},{"id":38,"l":[{"p":"(l) After the if"}],"k":"blank","a":["definitions.get(word).add(splitLine[2])"],"topics":["JAVA","ADTS"],"x":"The third field (index 2) is the definition. Staff also accepted a Set-based solution (Map<String, Set<String>>, returning new ArrayList<>(definitions.get(word))).","part":"l"},{"id":39,"l":[{"p":"(m) The body of getDefinitions"}],"k":"blank","a":["return definitions.get(word)"],"topics":["JAVA","ADTS"],"part":"m"}],"topics":null},{"id":"61b-fa25-mt2/5","n":"5","t":"5. Hash Table (9.0 pts)","b":[{"s":[{"p":"Consider the class below:"},{"c":"public class MutableString {\n    public String str;\n\n    public MutableString(String s) {\n        this.str = s;\n    }\n\n    /* Changes the idx'th character of str to c. */\n    public void changeChar(int idx, char c) { ... }\n\n    /* Adds character c to the end of str. */\n    public void addChar(char c) { ... }\n\n    @Override\n    public boolean equals(Object other) {\n        if (other instanceof MutableString uddaMutableString) {\n            return this.str.equals(uddaMutableString.str);\n        }\n        return false;\n    }\n\n    @Override\n    public int hashCode() {\n        return this.str.length();\n    }\n}","lang":"java"},{"p":"Suppose we insert four items into a HashSet of MutableString objects."},{"c":"Set<MutableString> h = new HashSet<>();\n\nMutableString s1 = new MutableString(\"cat\");\nh.add(s1);\n\nh.add(new MutableString(\"fish\"));\nh.add(new MutableString(\"dog\"));\nh.add(new MutableString(\"horse\"));","lang":"java"},{"p":"5.1 Assuming the hash table has four buckets, write the results of the insertions above in each bucket. Do not worry about resizing. Refer to MutableString objects by their str values, as a list like [\"cat\", \"fish\"], or [] if the bucket is empty."}]},{"id":40,"l":[{"p":"Bucket 0"}],"k":"blank","a":["[\"fish\"]","fish","[fish]"],"topics":["HASHING"]},{"id":41,"l":[{"p":"Bucket 1"}],"k":"blank","a":["[\"horse\"]","horse","[horse]"],"topics":["HASHING"]},{"id":42,"l":[{"p":"Bucket 2"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"]},{"id":43,"l":[{"p":"Bucket 3"}],"k":"blank","a":["[\"cat\", \"dog\"]","cat, dog","[cat, dog]"],"topics":["HASHING"],"x":"All four strings differ, so all four are added. The hash code is the length: fish 4 → bucket 0, horse 5 → 1, cat 3 and dog 3 → 3."},{"id":44,"l":[{"p":"5.2 After the four insertions, we run s1.changeChar(0, 'b'), changing s1.str from \"cat\" to \"bat\". Which of the following are true?"}],"k":"sata","o":["h.contains(s1) returns true.","h.contains(new MutableString(\"bat\")) returns true.","h.contains(new MutableString(\"cat\")) returns true.","None of the above"],"a":[0,1],"topics":["EQUALS","HASHING"],"x":"Bucket 3 now holds [\"bat\", \"dog\"]. Every query string has length 3, so contains looks in bucket 3 for an equal string: \"bat\" is there, \"cat\" isn’t."},{"id":45,"l":[{"p":"5.3 Consider the hash table from 5.1, i.e. we have not changed \"cat\" to \"bat\". Suppose we run s1.addChar('s'), changing s1.str from \"cat\" to \"cats\". Which of the following are true?"}],"k":"sata","o":["h.contains(s1) returns true.","h.contains(new MutableString(\"cat\")) returns true.","h.contains(new MutableString(\"cats\")) returns true.","h.add(new MutableString(\"cats\")) adds a new element to our hash table.","None of the above"],"a":[3],"topics":["EQUALS","HASHING"],"x":"s1 stays in bucket 3, now as \"cats\". \"cats\" hashes to 4 → bucket 0, which only has \"fish\", so contains(s1) and contains(\"cats\") are false and add(\"cats\") adds a new element. \"cat\" hashes to bucket 3, which holds \"cats\" and \"dog\", so that is false too."}],"topics":null},{"id":"61b-fa25-mt2/6","n":"6","t":"6. Asymptotics Analysis (16.0 pts)","b":[{"s":[{"p":"6.1 What is the runtime of mulch in terms of N?"},{"c":"void mulch(int[] x) {\n    int N = x.length;\n    if (N <= 1) {\n        return;\n    }\n\n    int[] left = new int[N/2];\n    for (int i = 0; i < N/2; i += 1) {\n        left[i] = x[i];\n    }\n\n    mulch(left);\n    mulch(left);\n}","lang":"java"}]},{"id":46,"l":[{"p":"6.1 Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":6,"topics":["ASYMPTOTICS","RECURSION"]},{"id":47,"l":[{"p":"6.1 Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":6,"topics":["ASYMPTOTICS","RECURSION"],"x":"Each call copies half its array, then makes two calls on that half. Every level of the call tree does N/2 work in total, and there are about log N levels."},{"s":[{"p":"6.2 What is the runtime of alarmJunior in terms of N?"},{"c":"void alarmJunior(int N) {\n    alarmHelper(2, N);\n}\n\nvoid alarmHelper(int i, int N) {\n    if (i > N) {\n        return;\n    }\n\n    System.out.println(\"BEEP\");\n    alarmHelper(i*2, N/2);\n}","lang":"java"}]},{"id":48,"l":[{"p":"6.2 Runtime"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":2,"topics":["ASYMPTOTICS","RECURSION"],"x":"i doubles while N halves, so they meet after about (log N)/2 calls, each doing constant work."},{"s":[{"p":"6.3 Consider the BSTMap from Homework 9. Recall that get returns null if the item is not in the map. What is the runtime of boom in terms of N, where N = map.size()? The runtime of the compareTo method of the Laboohoo class is constant."},{"c":"void boom(BSTMap<Integer, Laboohoo> map) {\n    for (int i = 0; i < map.size(); i += 1) {\n        System.out.println(map.get(i));\n    }\n}","lang":"java"}]},{"id":49,"l":[{"p":"6.3 Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":5,"topics":["ASYMPTOTICS","BSTS"]},{"id":50,"l":[{"p":"6.3 Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":7,"topics":["ASYMPTOTICS","BSTS"],"x":"The keys aren’t necessarily 0 to N−1. Best case: the tree is N, N+1, …, 2N−1 in a spindly chain, so every get goes left from the root and falls off: Θ(1) each. Worst case: a chain N, N−1, …, 1, where get(i) walks about N − i links: N + (N−1) + … + 1 = Θ(N²)."},{"id":51,"l":[{"p":"6.4 When Edsger Dijkstra published his original algorithm, he did not use any special data structure to store the fringe. Instead, he simply scanned the distTo array, choosing the vertex with the smallest value that was not yet marked as visited. Give a tight O bound, in terms of V and/or E, for the runtime of this algorithm on a graph with V vertices and E edges, using an adjacency list. Simplify your answer."}],"k":"blank","a":["O(V^2)","V^2","O(V²)","V²","O(V*V)","Θ(V^2)","Θ(V²)"],"topics":["ASYMPTOTICS","SHORTEST_PATHS"],"x":"Each of the V iterations scans distTo in Θ(V) and relaxes at most V edges, so the total is O(V²). Without a priority queue there are no log factors."}],"topics":null},{"id":"61b-fa25-mt2/7","n":"7","t":"7. Borders (14.0 pts)","b":[{"s":[{"p":"Bob loves walking between countries, which are represented by the class below:"},{"c":"public class Country {\n    public String name;           // Name of the country.\n    public List<Country> borders; // A list of bordering countries. borders is never null.\n}","lang":"java"},{"p":"Borders go both ways, i.e. if countryA appears in countryB’s borders, then countryB appears in countryA’s borders."},{"p":"Implement the WalkManager class, which has two methods. public WalkManager(List<Country> countries): Constructor. Given the list of all N countries in the world, prepare any useful instance variables. Must run in O(N² log N) time. public boolean canWalk(Country a, Country b): Returns whether country a is reachable from country b, using one or more borders. Must run in O(log N) time."},{"p":"For example, in a world with N = 4 countries where USA borders [Canada, Mexico], Canada borders [USA], Mexico borders [USA] and Ethanland borders [] (empty list): after WalkManager wm = new WalkManager(List.of(USA, Canada, Mexico, Ethanland)), wm.canWalk(Canada, Mexico) is true (Canada to USA to Mexico) and wm.canWalk(Ethanland, USA) is false."},{"p":"Everything on the reference card has been imported, and all data structures behave according to their implementations in lecture."},{"c":"public class WalkManager {\n    // Add any instance variables below (if necessary)\n    ⟪a⟫;\n    ⟪b⟫;\n\n    public WalkManager(List<Country> countries) {\n        int N = countries.size();\n        ⟪c⟫;\n        ⟪d⟫;\n        for (int i = 0; i < ⟪e⟫; i += 1) {\n            Country curr = ⟪f⟫;\n            ⟪g⟫;\n        }\n        for (⟪h⟫) {\n            for (Country c : ⟪i⟫) {\n                ⟪j⟫;\n            }\n        }\n    }\n\n    public boolean canWalk(Country a, Country b) {\n        return ⟪k⟫;\n    }\n}","lang":"java","f":{"a":"Map<Country, Integer> wquIndex","b":"WeightedQuickUnion wqu","c":"wquIndex = new HashMap<>()","d":"wqu = new WeightedQuickUnion(N)","e":"N","f":"countries.get(i)","g":"wquIndex.put(curr, i)","h":"Country curr : countries","i":"curr.borders","j":"wqu.union(wquIndex.get(curr), wquIndex.get(c))","k":"wqu.isConnected(wquIndex.get(a), wquIndex.get(b))"}}]},{"id":52,"l":[{"p":"(a) and (b) The two instance variables, one per line"}],"k":"blank","a":["Map<Country, Integer> wquIndex\nWeightedQuickUnion wqu","WeightedQuickUnion wqu\nMap<Country, Integer> wquIndex","HashMap<Country, Integer> wquIndex\nWeightedQuickUnion wqu","WeightedQuickUnion wqu\nHashMap<Country, Integer> wquIndex"],"topics":["DISJOINT_SETS","ADTS"],"x":"Give each country an index in a Weighted Quick Union, and union every pair of bordering countries. Then canWalk is one isConnected call, O(log N). A graph like Map<Country, List<Country>> can’t answer multi-border walks in O(log N).","part":"a"},{"id":53,"l":[{"p":"(c) First line of the constructor after N"}],"k":"blank","a":["wquIndex = new HashMap<>()"],"topics":["DISJOINT_SETS","ADTS"],"part":"c"},{"id":54,"l":[{"p":"(d) Second line"}],"k":"blank","a":["wqu = new WeightedQuickUnion(N)"],"topics":["DISJOINT_SETS","ADTS"],"part":"d"},{"id":55,"l":[{"p":"(e) The loop bound"}],"k":"blank","a":["N","countries.size()"],"topics":["DISJOINT_SETS","ADTS"],"part":"e"},{"id":56,"l":[{"p":"(f) Country curr = ____"}],"k":"blank","a":["countries.get(i)"],"topics":["DISJOINT_SETS","ADTS"],"part":"f"},{"id":57,"l":[{"p":"(g) In the first loop"}],"k":"blank","a":["wquIndex.put(curr, i)"],"topics":["DISJOINT_SETS","ADTS"],"part":"g"},{"id":58,"l":[{"p":"(h) The second loop’s header"}],"k":"blank","a":["Country curr : countries"],"topics":["DISJOINT_SETS","ADTS"],"part":"h"},{"id":59,"l":[{"p":"(i) The inner loop goes over"}],"k":"blank","a":["curr.borders"],"topics":["DISJOINT_SETS","ADTS"],"part":"i"},{"id":60,"l":[{"p":"(j) Inside the inner loop"}],"k":"blank","a":["wqu.union(wquIndex.get(curr), wquIndex.get(c))","wqu.union(wquIndex.get(c), wquIndex.get(curr))"],"topics":["DISJOINT_SETS","ADTS"],"part":"j"},{"id":61,"l":[{"p":"(k) canWalk returns"}],"k":"blank","a":["wqu.isConnected(wquIndex.get(a), wquIndex.get(b))","wqu.isConnected(wquIndex.get(b), wquIndex.get(a))"],"topics":["DISJOINT_SETS","ADTS"],"part":"k"}],"topics":null}],"by":["Hug","Kao"]},{"id":"61b-fa26-sample","t":"Sample CS 61B practice","src":{"site":true},"p":[{"id":"61b-fa26-sample/1","n":"1","t":"1. Two kinds of equal","b":[{"s":[{"p":"What does this code print? Write each printed line in its blank."},{"c":"String a = new String(\"cat\");\nString b = new String(\"cat\");\nSystem.out.println(a == b);       // ⟪a⟫\nSystem.out.println(a.equals(b));  // ⟪b⟫","lang":"java","f":{"a":"false","b":"true"}}]},{"id":1,"l":[{"p":"(a) What does the first line print?"}],"k":"blank","a":["false"],"x":"new String always makes a new object, so a and b point to different objects and == compares those addresses.","hints":["== on objects compares references, not contents.","Did either line reuse an existing object?"],"explanationBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) What does the second line print?"}],"k":"blank","a":["true"],"x":"String.equals compares the characters, and both strings are \"cat\".","hints":["equals compares what the objects contain.","What does String override equals to do?"],"explanationBy":"site","part":"b"}],"topics":[{"n":"","t":["EQUALS"],"by":"site"}],"authored":true},{"id":"61b-fa26-sample/2","n":"2","t":"2. Doubling loop","b":[{"s":[{"p":"Give the tightest bound on the runtime of f in terms of N."},{"c":"static int f(int N) {\n    int count = 0;\n    for (int i = 1; i < N; i *= 2) {\n        for (int j = 0; j < i; j += 1) {\n            count += 1;\n        }\n    }\n    return count;\n}","lang":"java"}]},{"id":3,"l":[{"p":"What is the runtime of f(N)?"}],"k":"mc","o":["Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":1,"x":"The inner loop runs 1 + 2 + 4 + … + (a power of 2 below N) times. That geometric sum is less than 2N, so the work is Θ(N).","hints":["Count the total inner-loop iterations instead of multiplying the two loop counts.","Add up i over every value i takes."],"explanationBy":"site"}],"topics":[{"n":"","t":["ASYMPTOTICS"],"by":"site"}],"authored":true},{"id":"61b-fa26-sample/3","n":"3","t":"3. Weighted quick union","b":[{"s":[{"p":"A weighted quick union (union by size, no path compression) holds N items."}]},{"id":4,"l":[{"p":"What is the tightest bound on the height of its tallest tree in the worst case?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)"],"a":1,"x":"An item’s depth grows only when its tree is linked under a tree at least as large, which at least doubles the size of its tree. That can happen at most log₂ N times.","hints":["Think about what happens to the size of an item’s tree each time the item gets deeper.","How many times can a size double before it passes N?"],"explanationBy":"site"}],"topics":[{"n":"","t":["DISJOINT_SETS"],"by":"site"}],"authored":true},{"id":"61b-fa26-sample/4","n":"4","t":"4. Min-heap insertion","b":[{"s":[{"p":"A min-heap is stored in an array starting at index 1 (index 0 is unused). Its items, from index 1 on, are 1, 3, 2, 7, 4."}]},{"id":5,"l":[{"p":"Insert 0. List the heap’s items from index 1 on, separated by commas."}],"k":"blank","a":["0, 3, 1, 7, 4, 2","[0, 3, 1, 7, 4, 2]"],"x":"0 goes in at index 6. Its parent (index 3) holds 2, so they swap; then its parent (index 1) holds 1, so they swap again. The heap is now 0, 3, 1, 7, 4, 2.","hints":["A new item goes at the end, then swims up while it’s smaller than its parent.","The parent of index k is index k / 2."],"explanationBy":"site"}],"topics":[{"n":"","t":["HEAPS"],"by":"site"}],"authored":true}]},{"id":"61b-sp15-final","t":"Spring 2015 Final","src":{"exam":"https://drive.google.com/file/d/1KWp6A4QwPCTTnrSe6U9esjt_yqwpfmne/view","sol":"https://drive.google.com/file/d/1EedyBzOq87mc3DzWlY5LydVkC2QO8ufq/view","topics":"sp15-final"},"p":[{"id":"61b-sp15-final/1","n":"1","t":"1. Basic Operations (6 pts)","b":[{"s":[{"p":"Graph edges (label: endpoints, weight): A: 0–1,1; B: 0–2,4; C: 0–3,1; D: 2–1,2; E: 1–4,3; F: 1–3,4; G: 2–3,1; H: 3–4,5. Give the edges selected in order."}]},{"id":1,"l":[{"p":"(a) Kruskal MST edge labels, comma-separated"}],"k":"blank","a":["A,C,G,D,E"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) Prim MST edge labels from vertex 3"}],"k":"blank","a":["C,G,A,E"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Partition [4,1,6,2,3,7,3,4] around its leftmost item as pivot; any valid partitioning scheme is acceptable."}]},{"id":3,"l":[{"p":"One valid partitioned array"}],"k":"blank","a":["1,2,3,3,4,7,6,4"],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"(d) Sinking-based heapify [1,2,4,9,3,7,5] into a max heap."}]},{"id":4,"l":[{"p":"Resulting array"}],"k":"blank","a":["9,3,7,2,1,4,5"],"topics":["HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/2","n":"2","t":"2. Basic Operations Turbo Edition (3 pts)","b":[{"s":[{"p":"(a) Give a binary tree with preorder and inorder A,B,C,D,E. Any valid tree accepted by describing its shape."}]},{"id":5,"l":[{"p":"Which tree is valid?"}],"k":"mc","o":["A with right child B, B with right child C, C with right child D, D with right child E","A with left child B, B with left child C, C with left child D, D with left child E","Root C, left subtree A(B), right subtree D(E)","Root E with left chain D,C,B,A"],"a":0,"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"s":[{"p":"(b) Give directed edges for a graph with DFS preorder A,B,C,D,E and postorder C,B,D,E,A; ties alphabetically."}]},{"id":6,"l":[{"p":"One valid edge set (semicolon-separated)"}],"k":"blank","a":["A->B;A->D;A->E;B->C"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/3","n":"3","t":"3. Best and Worst (4.5 pts)","b":[{"id":7,"l":[{"p":"(a) Worst-case insertion sort input of five integers"}],"k":"blank","a":["5,4,3,2,1"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":8,"l":[{"p":"(b) A minimum-height BST insertion order for A through G"}],"k":"blank","a":["D,B,F,A,C,E,G"],"topics":["BSTS"],"topicsBy":"site","part":"b"},{"id":9,"l":[{"p":"(c) Worst-case amortized operation cost for the described resize policy, in terms of maximum capacity N"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp15-final/4","n":"4","t":"4. Comparative Data Structures and Algorithms (7.5 pts)","b":[{"id":10,"l":[{"p":"(a) Largest size of a binary min heap that is also a BST"}],"k":"blank","a":["1"],"topics":["HEAPS","BSTS"],"topicsBy":"site","part":"a"},{"id":11,"l":[{"p":"(b) Largest size of a binary max heap that is also a BST"}],"k":"blank","a":["2"],"topics":["HEAPS","BSTS"],"topicsBy":"site","part":"b"},{"id":12,"l":[{"p":"(c) Largest min-heap where the fifth-largest item is a child of the root"}],"k":"blank","a":["13"],"topics":["HEAPS"],"topicsBy":"site","part":"c"},{"id":13,"l":[{"p":"(d) A reason to choose Quicksort over Mergesort"}],"k":"mc","o":["Need in-place sorting or lower extra memory, and stability is unnecessary","Need guaranteed stability","Need guaranteed O(n log n) worst case without extra storage","Need efficient prefix queries"],"a":0,"topics":["SORTING"],"topicsBy":"site","part":"d"},{"id":14,"l":[{"p":"(e) When is a Trie map preferable to a HashMap?"}],"k":"mc","o":["Autocomplete or prefix queries","When keys are arbitrary objects without string structure","When only exact-key lookup is needed and memory is tight","When keys must be stored in a heap"],"a":0,"topics":["TRIES","HASHING"],"topicsBy":"site","part":"e"},{"id":15,"l":[{"p":"(f) A sound reason heaps are used for priority queues"}],"k":"mc","o":["They use less memory and have a simpler invariant; they also handle duplicates naturally","They make every operation constant time","They asymptotically outperform balanced BSTs for all operations","They guarantee sorted iteration"],"a":0,"topics":["HEAPS","ADTS"],"topicsBy":"site","part":"f"}],"topics":null},{"id":"61b-sp15-final/5","n":"5","t":"5. Syntax Mastery (2 pts)","b":[{"s":[{"c":"class Sklarp implements Iterable<Character>, Iterator<Character> {\n  char[] contents; char magicCharacter; int k;\n  Sklarp(char[] s, Character c) { contents=s; magicCharacter=c; k=0; }\n  public Iterator<Character> iterator() { return this; }\n  public boolean hasNext() { return k < contents.length; }\n  public Character next() {\n    if (k % 3 == 0) contents[k] = magicCharacter;\n    char result = contents[k]; k += 1; return result;\n  }\n  public void remove() { throw new UnsupportedOperationException(); }\n  public static void main(String[] args) {\n    Sklarp g = new Sklarp(\"Zeoidei\".toCharArray(), 'r');\n    for (Character c : g) System.out.print(c);\n    System.out.println();\n    for (Character c : g) System.out.print(c);\n    System.out.println();\n  }\n}","lang":"java"}]},{"id":16,"l":[{"p":"First output line"}],"k":"blank","a":["reoidei"],"topics":["JAVA","ITERATORS"],"topicsBy":"site"},{"id":17,"l":[{"p":"Second output line (the loop has already consumed the iterator)"}],"k":"blank","a":["empty line"],"topics":["JAVA","ITERATORS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/6","n":"6","t":"6. Runtime Analysis (2.5 pts)","b":[{"s":[{"c":"void f1(int N) { for (int i=N; i>0; i-=1) for (int j=0; j<i; j+=1) {} }\nvoid f2(int N) { for (int i=1; i<=N; i*=2) for (int j=0; j<i; j+=1) {} }\nvoid f3(int[] a) {\n  if (a.length==0) return;\n  int[] b=new int[a.length-1];\n  for (int i=0; i<b.length; i+=1) b[i]=a[i];\n  f3(b);\n}\nvoid f4(int N) { int x=N; while(x>0) x=x>>>1; }\nvoid f5(int N) { f1(N); f2(N); f3(new int[N]); f4(N); }","lang":"java"}]},{"id":18,"l":[{"p":"f1"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":19,"l":[{"p":"f2"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":20,"l":[{"p":"f3"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":21,"l":[{"p":"f4"}],"k":"blank","a":["Theta(log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":22,"l":[{"p":"f5"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/7","n":"7","t":"7. Sorting Mechanics (5 pts)","b":[{"s":[{"p":"Match intermediate-state clues to algorithms. Initial array: 4873,1874,8917,1626,4982,9132,9573,1876,6973,1897,9587,3492,9877,2212,6152,7121."}]},{"id":23,"l":[{"p":"Column 2: all values below pivot 4873 are greater, values above it smaller"}],"k":"blank","a":["Quicksort"],"topics":["SORTING"],"topicsBy":"site"},{"id":24,"l":[{"p":"Column 3: values grouped by leading digit, not sorted within groups"}],"k":"blank","a":["MSD radix sort"],"topics":["SORTING"],"topicsBy":"site"},{"id":25,"l":[{"p":"Column 4: each adjacent pair sorted, otherwise unordered"}],"k":"blank","a":["Mergesort"],"topics":["SORTING"],"topicsBy":"site"},{"id":26,"l":[{"p":"Column 5: max heap with sorted suffix"}],"k":"blank","a":["Heapsort"],"topics":["SORTING"],"topicsBy":"site"},{"id":27,"l":[{"p":"Column 6: sorted by low-order digits first"}],"k":"blank","a":["LSD radix sort"],"topics":["SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/8","n":"8","t":"8. Choosing a Sort (4 pts)","b":[{"s":[{"p":"For almost-sorted Comparable objects, k is the inversion count. Give algorithm and tight runtime."}]},{"id":28,"l":[{"p":"(a) k=O(n): algorithm"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":29,"l":[{"p":"(a) k=O(n): runtime"}],"k":"blank","a":["O(n)"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":30,"l":[{"p":"(a) k=O(n^2): algorithm"}],"k":"blank","a":["Mergesort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":31,"l":[{"p":"(a) k=O(n^2): runtime"}],"k":"blank","a":["O(n log n)"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":32,"l":[{"p":"(a) k=log(n): algorithm"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":33,"l":[{"p":"(a) k=log(n): runtime"}],"k":"blank","a":["O(n)"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":34,"l":[{"p":"(b) 32-bit int IDs, k=O(n^2): algorithm"}],"k":"blank","a":["Radix sort"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":35,"l":[{"p":"(b) 32-bit int IDs, k=O(n^2): runtime"}],"k":"blank","a":["O(n)"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":36,"l":[{"p":"(b) 32-bit int IDs, k<=5: algorithm"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":37,"l":[{"p":"(b) 32-bit int IDs, k<=5: runtime"}],"k":"blank","a":["O(n)"],"topics":["SORTING"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp15-final/9","n":"9","t":"9. Shortest Paths Algorithms (4.5 pts)","b":[{"s":[{"p":"Directed weighted edges from the diagram: A→B(1), A→D(5), B→C(3), B→H(6), C→F(2), C→G(5), D→E(4), E→H(4), F→G(2), H→G(4)."}]},{"id":38,"l":[{"p":"(a) Dijkstra visit order from A"}],"k":"blank","a":["A,B,C,D,F,H,G,E"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":39,"l":[{"p":"(b) Change E→H weight to what value or range to make Dijkstra incorrect?"}],"k":"blank","a":["-3 or less"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"b"},{"id":40,"l":[{"p":"(c) A* returned path from A to G with given heuristic"}],"k":"blank","a":["A,B,H,G"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp15-final/10","n":"10","t":"10. Hashing and Doubly Linked Lists (7 pts)","b":[{"s":[{"p":"Complete getNode, detachNode, and DLLHashMap.put. A bucket is a sentinel-based doubly linked list; getNode returns a matching node or null; detachNode unlinks it; put hashes String keys, promotes existing keys, updates values, or inserts new nodes at the front."},{"c":"DNode getNode(String k) {\n  DNode p = sentinel.next;\n  while (p != null && !p.key.equals(k)) p = p.next;\n  return p;\n}\nvoid detachNode(DNode p) {\n  p.prev.next = p.next;\n  if (p.next != null) p.next.prev = p.prev;\n  size -= 1;\n}\nvoid put(String k, String v) {\n  int index = (k.hashCode() << 1 >>> 1) % data.length;\n  DLList bucket = data[index];\n  DNode p = bucket.getNodeAndPromote(k);\n  if (p != null) p.value = v;\n  else bucket.addToFront(k, v);\n}","lang":"java"}]},{"id":41,"l":[{"p":"getNode: start cursor"}],"k":"blank","a":["sentinel.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":42,"l":[{"p":"getNode: match condition"}],"k":"blank","a":["p.key.equals(k)"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":43,"l":[{"p":"getNode: continue while cursor is non-null"}],"k":"blank","a":["p != null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":44,"l":[{"p":"detachNode: reconnect successor"}],"k":"blank","a":["p.prev.next = p.next"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":45,"l":[{"p":"detachNode: guard and reconnect predecessor"}],"k":"blank","a":["if (p.next != null) p.next.prev = p.prev"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":46,"l":[{"p":"put: bucket index expression"}],"k":"blank","a":["(k.hashCode() << 1 >>> 1) % data.length"],"topics":["HASHING"],"topicsBy":"site"},{"id":47,"l":[{"p":"put: method on bucket to lookup/promote"}],"k":"blank","a":["getNodeAndPromote(k)"],"topics":["HASHING","LINKED_LISTS"],"topicsBy":"site"},{"id":48,"l":[{"p":"put: update existing node"}],"k":"blank","a":["p.value = v"],"topics":["HASHING","LINKED_LISTS"],"topicsBy":"site"},{"id":49,"l":[{"p":"put: add new pair"}],"k":"blank","a":["bucket.addToFront(k, v)"],"topics":["HASHING","LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/12","n":"12","t":"12. Radix Sorting and Bits (8 pts)","b":[{"s":[{"p":"LSD radix sort with N keys of width W digits:"}]},{"id":50,"l":[{"p":"(a) Is insertion sort on each digit stable enough for LSD radix sort?"}],"k":"blank","a":["yes"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":51,"l":[{"p":"(a) Worst-case runtime"}],"k":"blank","a":["O(WN^2)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":52,"l":[{"p":"(b) Does heapsort on each digit preserve LSD correctness?"}],"k":"blank","a":["no"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":53,"l":[{"p":"(b) Worst-case runtime"}],"k":"blank","a":["O(WN log N)"],"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) abs(x) is implemented as x<0 ? (~x+1) : x. Identify the exceptional int and explain."}]},{"id":54,"l":[{"p":"Exceptional value and behavior"}],"k":"blank","a":["Integer.MIN_VALUE; its positive magnitude overflows and it returns itself"],"topics":["BITS"],"topicsBy":"site"},{"s":[{"p":"(d) KetchupFriend compares first by nonnegative ketchupLevel, then rednessQuotient; both are 32-bit ints. numDigits() returns 64. kthDigit(k), where 0 is least significant:"},{"c":"public int kthDigit(int k) {\n  if (k < 32) return (rednessQuotient >>> k) & 1;\n  return (ketchupLevel >>> (k - 32)) & 1;\n}","lang":"java"}]},{"id":55,"l":[{"p":"Which field supplies digits 0 through 31?"}],"k":"blank","a":["rednessQuotient"],"topics":["BITS","SORTING"],"topicsBy":"site"},{"id":56,"l":[{"p":"Which field supplies digits 32 through 63?"}],"k":"blank","a":["ketchupLevel"],"topics":["BITS","SORTING"],"topicsBy":"site"},{"id":57,"l":[{"p":"Digit expression for k<32"}],"k":"blank","a":["(rednessQuotient >>> k) & 1"],"topics":["BITS","SORTING"],"topicsBy":"site"},{"id":58,"l":[{"p":"Digit expression for k>=32"}],"k":"blank","a":["(ketchupLevel >>> (k - 32)) & 1"],"topics":["BITS","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-final/13","n":"13","t":"13. Shortest Paths Algorithm Design (5 pts)","b":[{"s":[{"p":"Directed graph with every edge weight an integer from 1 to 10. Find distances from source s in faster than standard Dijkstra. One accepted solution replaces each weight-w edge with a chain of w unit edges and runs BFS."}]},{"id":59,"l":[{"p":"(a) Which algorithm is a valid faster-than-Dijkstra design?"}],"k":"mc","o":["Replace each weight-w edge by a chain of w unit edges, then BFS","Run DFS and record first visit","Run Kruskal on the edges","Topologically sort the graph"],"a":0,"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":60,"l":[{"p":"(b) Runtime in terms of V and E"}],"k":"blank","a":["Theta(V + E)"],"topics":["SHORTEST_PATHS","ASYMPTOTICS"],"topicsBy":"site","part":"b"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp15-mt1","t":"Spring 2015 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1nMt8j8oWn0JWOzud6UCNrlg8ozexG-XQ/view","sol":"https://drive.google.com/file/d/1e8Mk1PBRWiKYGdBoauemZ4LTvv0F_MEE/view","topics":"sp15-mt1"},"p":[{"id":"61b-sp15-mt1/1","n":"1","t":"1. IntLists (1.5 pts)","b":[{"s":[{"c":"IntList a = new IntList(5, null);\nIntList b = new IntList(9, null);\nIntList c = new IntList(1, new IntList(7, b));\na.tail = c.tail;\na.tail.tail = b;\nb.tail = c.tail;\nIntList d = new IntList(9001, b.tail.tail);\n// Print A: d.tail.tail.tail.head\n// Print B: a.tail.head\nc.tail.tail = c.tail;\n// Print C: a.tail.tail.tail.tail.head","lang":"java"}]},{"id":1,"l":[{"p":"Print A"}],"k":"blank","a":["9"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":2,"l":[{"p":"Print B"}],"k":"blank","a":["7"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":3,"l":[{"p":"Print C"}],"k":"blank","a":["7"],"topics":["LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt1/2","n":"2","t":"2. The Ole Flitcharoo (3 pts)","b":[{"s":[{"c":"class Foo { int x, y; Foo(int x, int y) { this.x=x; this.y=y; } }\nstatic void switcheroo(Foo a, Foo b) { Foo temp=a; a=b; b=temp; }\nstatic void fliperoo(Foo a, Foo b) {\n    Foo temp=new Foo(a.x,a.y); a.x=b.x; a.y=b.y; b.x=temp.x; b.y=temp.y;\n}\nstatic void swaperoo(Foo a, Foo b) {\n    Foo temp=a; a.x=b.x; a.y=b.y; b.x=temp.x; b.y=temp.y;\n}\nFoo foobar=new Foo(10,20), baz=new Foo(30,40);","lang":"java"},{"p":"Give foobar and baz as x,y pairs after each call."}]},{"id":4,"l":[{"p":"After switcheroo(foobar, baz): foobar"}],"k":"blank","a":["10,20"],"topics":["JAVA"],"topicsBy":"site"},{"id":5,"l":[{"p":"After switcheroo(foobar, baz): baz"}],"k":"blank","a":["30,40"],"topics":["JAVA"],"topicsBy":"site"},{"id":6,"l":[{"p":"After fliperoo(foobar, baz): foobar"}],"k":"blank","a":["30,40"],"topics":["JAVA"],"topicsBy":"site"},{"id":7,"l":[{"p":"After fliperoo(foobar, baz): baz"}],"k":"blank","a":["10,20"],"topics":["JAVA"],"topicsBy":"site"},{"id":8,"l":[{"p":"After swaperoo(foobar, baz): foobar"}],"k":"blank","a":["10,20"],"topics":["JAVA"],"topicsBy":"site"},{"id":9,"l":[{"p":"After swaperoo(foobar, baz): baz"}],"k":"blank","a":["10,20"],"topics":["JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt1/3","n":"3","t":"3. IntList Manipulation (5 pts)","b":[{"s":[{"p":"Complete skipBy to return a new list with the first item and then every skip-th item. Assume skip > 0 and no cycles."},{"c":"if (⟪a⟫) { return ⟪b⟫; }\nIntList p = s;\nint count = skip;\nwhile (⟪c⟫) { ⟪d⟫ count--; }\nreturn new IntList(⟪e⟫);","lang":"java"}]},{"id":13,"l":[{"p":"s == null"}],"k":"blank","a":["s == null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":14,"l":[{"p":"return null"}],"k":"blank","a":["null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":15,"l":[{"p":"loop condition"}],"k":"blank","a":["p != null && count > 0"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":16,"l":[{"p":"advance p"}],"k":"blank","a":["p = p.tail;"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":17,"l":[{"p":"new node arguments"}],"k":"blank","a":["s.head, skipBy(skip, p)"],"topics":["LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt1/4","n":"4","t":"4. Debugging (7 pts)","b":[{"s":[{"p":"(a) Explain in 10 words or fewer why flavor prints Chocolate. After uncommenting chocolate.melt() and the second print, will it compile and what prints?"},{"c":"static String flavor;\nIceCream vanilla = new IceCream(\"Vanilla\");\nIceCream chocolate = new IceCream(\"Chocolate\");\nSystem.out.println(vanilla.flavor);\nchocolate.melt();\nSystem.out.println(vanilla.flavor);","lang":"java"}]},{"id":18,"l":[{"p":"(a) Why does vanilla.flavor print Chocolate?"}],"k":"mc","o":["flavor is static, so both instances share its latest value","vanilla was constructed after chocolate","melt changes every string","the compiler swaps the two references"],"a":0,"topics":["JAVA"],"topicsBy":"site","part":"a"},{"id":19,"l":[{"p":"(a) Compiles?"}],"k":"blank","a":["yes"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"id":20,"l":[{"p":"(a) Second output"}],"k":"blank","a":["melted Chocolate"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) In each case, x and y begin as two distinct int[] objects, each containing 0, 1, 2, 3, 4. Answer true, false, or not enough information."},{"c":"y = someUnknownFunction(x, y); System.out.println(x == y);","lang":"java"}]},{"id":21,"l":[{"p":"(b) After assignment from unknown function"}],"k":"blank","a":["not enough information"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"},{"s":[{"c":"anotherUnknownFunction(x, y); System.out.println(x == y);","lang":"java"}]},{"id":22,"l":[{"p":"(b) After passing arrays to unknown function"}],"k":"blank","a":["false"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"},{"s":[{"c":"System.arraycopy(x, 0, y, 0, 5); System.out.println(x == y);","lang":"java"}]},{"id":23,"l":[{"p":"(b) After System.arraycopy"}],"k":"blank","a":["false"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Give a test scenario that exposes the bug in this SentinelSSList implementation, then identify the bug."},{"c":"SentinelSSList() { sent = new StringNode(null, null); }\nSentinelSSList(String x) { sent = new StringNode(x, null); }\nString getFront() { if (sent.next == null) return null; return sent.next.item; }","lang":"java"}]},{"id":24,"l":[{"p":"(c) Which test exposes the constructor bug?"}],"k":"mc","o":["Construct with one string and check that getFront returns it","Construct an empty list and check its size","Call getFront twice on an empty list","Compare two unrelated lists"],"a":0,"topics":["LINKED_LISTS"],"topicsBy":"site","part":"c"},{"id":25,"l":[{"p":"(c) What is the bug?"}],"k":"mc","o":["The constructor stores x in the sentinel instead of its next node","getFront must return the sentinel itself","The list needs two sentinels","The constructor should set x to null"],"a":0,"topics":["LINKED_LISTS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp15-mt1/5","n":"5","t":"5. Bits (3 pts)","b":[{"s":[{"c":"int mystery(int a) {\n    int b=0;\n    for (int i=0; i<32; i++) {\n        b=b<<1; b=b|(a&1); a=a>>>1;\n    }\n    return b;\n}","lang":"java"}]},{"id":10,"l":[{"p":"What does mystery return?"}],"k":"mc","o":["The number of 1 bits","The bits of a in reverse order","The two’s complement of a","a shifted left 32 places"],"a":1,"topics":["BITS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt1/7","n":"7","t":"7. Higher Order Functions and Arrays (8 pts)","b":[{"s":[{"p":"Replace each interior cell with the longest string among its eight neighbors and itself. Edges are null and must remain null. Assume at least 3 rows and columns, equal row lengths, but not necessarily a square array. The comparator treats null as less than any String."},{"p":"(a) Complete a null-safe length comparator."},{"c":"class LengthComparator implements NullSafeStringComparator {\n  public int compare(String s1, String s2) {\n    if (s1 == null && s2 == null) return ⟪a⟫;\n    if (s1 == null) return ⟪b⟫;\n    if (s2 == null) return ⟪c⟫;\n    return ⟪d⟫;\n  }\n}","lang":"java"}]},{"id":26,"l":[{"p":"(a) both null"}],"k":"blank","a":["0"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"id":27,"l":[{"p":"(a) s1 null"}],"k":"blank","a":["-1"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"id":28,"l":[{"p":"(a) s2 null"}],"k":"blank","a":["1"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"id":29,"l":[{"p":"(a) compare lengths"}],"k":"blank","a":["s1.length() - s2.length()"],"topics":["JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) Complete max, which returns the maximum element according to sc."},{"c":"String maxStr = a[0];\nfor (⟪a⟫; ⟪b⟫; i += 1) {\n  if (⟪c⟫) { ⟪d⟫ }\n}\nreturn maxStr;","lang":"java"}]},{"id":30,"l":[{"p":"(b) loop initialization"}],"k":"blank","a":["int i = 0"],"topics":["JAVA"],"topicsBy":"site","part":"b"},{"id":31,"l":[{"p":"(b) loop condition"}],"k":"blank","a":["i < a.length"],"topics":["JAVA"],"topicsBy":"site","part":"b"},{"id":32,"l":[{"p":"(b) comparison"}],"k":"blank","a":["sc.compare(a[i], maxStr) > 0"],"topics":["JAVA"],"topicsBy":"site","part":"b"},{"id":33,"l":[{"p":"(b) update"}],"k":"blank","a":["maxStr = a[i];"],"topics":["JAVA"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Complete step. The 3-by-3 neighborhood includes the cell itself, for nine values total. Do not use ++ or --."},{"c":"String[][] stepped = new String[⟪a⟫][⟪b⟫];\nfor (int i = ⟪c⟫; ⟪d⟫; i += 1) {\n  for (int j = ⟪e⟫; j < ⟪f⟫; j += 1) {\n    String[] neighbors = ⟪g⟫;\n    int count = ⟪h⟫;\n    for (int k = -1; k <= 1; k += 1) {\n      for (int m = -1; m <= 1; m += 1) {\n        ⟪i⟫\n        ⟪j⟫\n      }\n    }\n    ⟪k⟫\n  }\n}","lang":"java"}]},{"id":34,"l":[{"p":"(c) rows"}],"k":"blank","a":["arr.length"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":35,"l":[{"p":"(c) columns"}],"k":"blank","a":["arr[0].length"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":36,"l":[{"p":"(c) first i"}],"k":"blank","a":["1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":37,"l":[{"p":"(c) i bound"}],"k":"blank","a":["i < arr.length - 1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":38,"l":[{"p":"(c) first j"}],"k":"blank","a":["1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":39,"l":[{"p":"(c) j bound"}],"k":"blank","a":["arr[0].length - 1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":40,"l":[{"p":"(c) allocate neighbors"}],"k":"blank","a":["new String[9]"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":41,"l":[{"p":"(c) initialize count"}],"k":"blank","a":["0"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":42,"l":[{"p":"(c) store neighbor"}],"k":"blank","a":["neighbors[count] = arr[i + k][j + m];"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":43,"l":[{"p":"(c) increment count"}],"k":"blank","a":["count += 1;"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"},{"id":44,"l":[{"p":"(c) select maximum"}],"k":"blank","a":["stepped[i][j] = max(neighbors, new LengthComparator());"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp15-mt1/8","n":"8","t":"8. A Robot Renegade Cop (5 pts)","b":[{"s":[{"p":"For each print line give its output or INVALID if it does not compile. For lines 6 and 9 answer “no cast” if none is needed; otherwise give the cast."},{"c":"class Robot { int energy=0; String className=\"Robot\";\n  void enervate(Robot r) { r.energy -= 5; }\n  void reportEnergy() { System.out.println(energy); }\n  void reportName() { System.out.println(className); }\n}\ninterface Police { void detain(); }\nclass Robocop extends Robot implements Police {\n  String className=\"Robocop\";\n  public void detain() { System.out.println(\"halt. citizen.\"); }\n  @Override void enervate(Robot r) { r.energy -= 20; }\n  @Override void reportEnergy() { System.out.println(energy); }\n  @Override void reportName() { System.out.println(className); }\n}\nRobocop rCop = new Robocop();\nrCop.reportEnergy(); //4   rCop.detain(); //5\nRobot r = (cast) rCop; //6\nr.reportEnergy(); //7  r.detain(); //8\nPolice p = (cast) rCop; //9\np.reportEnergy(); //10  p.detain(); //11\nr.enervate(r); rCop.enervate(r); rCop.reportEnergy(); //12\nr.energy = 100;\nr.enervate(rCop); rCop.enervate(rCop); r.reportEnergy(); //14\nr.reportName(); //15  rCop.reportName(); //16\nrCop.className = \"ketchup friend\";\nr.reportName(); //18","lang":"java"}]},{"id":45,"l":[{"p":"4 output"}],"k":"blank","a":["0"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":46,"l":[{"p":"5 output"}],"k":"blank","a":["halt. citizen."],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":47,"l":[{"p":"6 cast"}],"k":"blank","a":["no cast"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":48,"l":[{"p":"7 output"}],"k":"blank","a":["0"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":49,"l":[{"p":"8 result"}],"k":"blank","a":["INVALID"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":50,"l":[{"p":"9 cast"}],"k":"blank","a":["no cast"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":51,"l":[{"p":"10 result"}],"k":"blank","a":["INVALID"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":52,"l":[{"p":"11 output"}],"k":"blank","a":["halt. citizen."],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":53,"l":[{"p":"12 output"}],"k":"blank","a":["-40"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":54,"l":[{"p":"14 output"}],"k":"blank","a":["60"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":55,"l":[{"p":"15 output"}],"k":"blank","a":["Robocop"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":56,"l":[{"p":"16 output"}],"k":"blank","a":["Robocop"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":57,"l":[{"p":"18 output"}],"k":"blank","a":["ketchup friend"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt1/9","n":"9","t":"9. Static Shock (2 pts)","b":[{"s":[{"c":"class Shock {\n    static int bang; static Shock baby;\n    Shock() { this.bang=100; }\n    Shock(int num) { this.bang=num; baby=starter(); this.bang+=num; }\n    static Shock starter() { return new Shock(); }\n    static void shrink(Shock s) { s.bang-=1; }\n    public static void main(String[] args) {\n        Shock gear=new Shock(200);\n        System.out.println(gear.bang); // A\n        shrink(gear); shrink(starter());\n        System.out.println(gear.bang); // B\n    }\n}","lang":"java"}]},{"id":11,"l":[{"p":"Print A"}],"k":"blank","a":["300"],"topics":["JAVA"],"topicsBy":"site"},{"id":12,"l":[{"p":"Print B"}],"k":"blank","a":["99"],"topics":["JAVA"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp15-mt2","t":"Spring 2015 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1uE1QlF4YguWVp8m8UJ97R2xPC4b1NnQ5/view","sol":"https://drive.google.com/file/d/1IYt4VbzdX4dTekh6cYAC8tigpJ_LgljV/view","topics":"sp15-mt2"},"p":[{"id":"61b-sp15-mt2/1","n":"1","t":"1. Basic Operations (6 pts)","b":[{"s":[{"p":"(a) Delete 20 from this BST using the deletion procedure from class (no more than 4 references change). Trees are written value(left, right)."},{"c":"20( 15(-, 17(16, 19(18, -))), 29( 25(23(-, 24), 28), 35(33, -) ) )","lang":"txt"}]},{"id":1,"l":[{"p":"(a) Which tree can result?"}],"k":"mc","o":["19( 15(-, 17(16, 18)), 29( 25(23(-, 24), 28), 35(33, -) ) )","23( 15(-, 17(16, 19(18, -))), 29( 25(24, 28), 35(33, -) ) )","15( -, 17(16, 19(18, 29(25(23(-, 24), 28), 35(33, -)))) )","29( 15(-, 17(16, 19(18, -))), 35( 25(23(-, 24), 28), 33 ) )"],"a":0,"topics":["BSTS"],"topicsBy":"site","also":[1],"x":"The predecessor 19 or the successor 23 replaces 20; both trees are correct.","part":"a"},{"s":[{"p":"(b) Delete the smallest item from the min-heap [0, 1, 4, 8, 2, 6, 8, 9] (written as its array, without an unused first spot)."}]},{"id":2,"l":[{"p":"(b) The resulting array, separated by commas"}],"k":"blank","a":["1, 2, 4, 8, 9, 6, 8","1 2 4 8 9 6 8"],"topics":["HEAPS"],"topicsBy":"site","x":"9 moves to the root and sinks below 1, then below 2.","part":"b"},{"s":[{"p":"(c) An external-chaining hash set of Integers (hashCode is the integer itself) has 4 buckets: 0 → 8, 1 → 25, 2 → 10, 18, 3 → 15. We insert 5, which also resizes it from 4 buckets to 8."}]},{"id":3,"l":[{"p":"(c) Which bucket holds 25 afterwards?"}],"k":"blank","a":["1"],"topics":["HASHING"],"topicsBy":"site","part":"c"},{"id":4,"l":[{"p":"(c) Which bucket holds 15?"}],"k":"blank","a":["7"],"topics":["HASHING"],"topicsBy":"site","part":"c"},{"id":5,"l":[{"p":"(c) Which bucket holds 5?"}],"k":"blank","a":["5"],"topics":["HASHING"],"topicsBy":"site","part":"c"},{"id":6,"l":[{"p":"(c) Which bucket holds 10 and 18?"}],"k":"blank","a":["2"],"topics":["HASHING"],"topicsBy":"site","x":"Each item goes to its value mod 8: 8 → 0, 25 → 1, 10 and 18 → 2, 5 → 5, 15 → 7.","part":"c"},{"id":7,"l":[{"p":"(d) Which is a valid Weighted Quick Union after connect(1, 4), connect(2, 3), connect(1, 3), connect(5, 1)? (Any reasonable argument-order convention was accepted; trees are written root(children).)"}],"k":"mc","o":["3( 2, 4(1), 5 )","3( 2, 4(1(5)) )","1( 4, 3(2), 5 )","5( 1(4, 3(2)) )"],"a":0,"topics":["DISJOINT_SETS"],"topicsBy":"site","also":[2],"x":"Only roots are ever connected, and connecting 5 to the size-4 tree puts 5 directly under that tree’s root.","part":"d"}],"topics":null},{"id":"61b-sp15-mt2/2","n":"2","t":"2. Asymptotics (5 pts)","b":[{"s":[{"p":"(a) Timing experiments on PotatoSack.add, with N inserts:"},{"c":"N     Time (s)\n1     0.00\n2     0.01\n3     0.01\n6     0.03\n13    0.16\n25    0.63\n50    2.50\n100   9.97","lang":"txt"},{"p":"Approximate the runtime as aNᵇ using the data points that best show its asymptotic behavior."}]},{"id":8,"l":[{"p":"(a) b"}],"k":"blank","a":["2"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":9,"l":[{"p":"(a) a"}],"k":"blank","a":["0.001",".001","1/1000"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"log₂(9.97 / 2.5) ≈ 2, and 9.97 = a · 100² gives a ≈ 0.001.","part":"a"},{"id":10,"l":[{"p":"(b) Inserting N items into some collection takes Θ(N²). For which collections is that possible on a worst-case input (each correctly implemented)?"}],"k":"sata","o":["LinkedList","2-3 Tree Set","HeapMinPQ","LLRBST Set","Your BSTMap (from HW6)","External Chaining Hash Map","ArrayList"],"a":[0,4,5,6],"topics":["ASYMPTOTICS","ADTS"],"topicsBy":"site","x":"Balanced trees and heaps insert in O(log N). A list, an unbalanced BST and a hash map with all items colliding can each take linear time per insert.","part":"b"},{"id":11,"l":[{"p":"(c) Two correct algorithms for the same problem use the same memory, with worst-case runtimes Θ(N) and Θ(N²). Is the Θ(N) one always better?"}],"k":"mc","o":["No: for small N the Θ(N²) one can be faster, and the worst case may only occur on inputs we don’t care about","Yes: it is faster on every input","Yes: worst-case runtime is all that matters","No: Θ(N²) is always faster for large N"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp15-mt2/3","n":"3","t":"3. Exceptions (2 pts)","b":[{"s":[{"p":"writeToLog writes its argument to a log file. What does the log contain after this code runs?"},{"c":"public class QuestionThree {\n    public static void printTenth(int[] a) {\n        try {\n            writeToLog(a[10]);\n        } catch(IndexOutOfBoundsException e) {\n            writeToLog(\"No tenth item available!\");\n            throw(e);\n        }\n    }\n\n    public static void main(String[] args) {\n        printTenth(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});\n        printTenth(new int[]{0, 1, 2, 3});\n        printTenth(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});\n    }\n}","lang":"java"}]},{"id":12,"l":[{"p":"The log’s contents, one entry per line"}],"k":"blank","a":["10\nNo tenth item available!"],"topics":["JAVA"],"topicsBy":"site","x":"The second call logs the message and rethrows; nothing catches it, so the program stops before the third call."}],"topics":null},{"id":"61b-sp15-mt2/4","n":"4","t":"4. TreeTime (5 pts)","b":[{"id":13,"l":[{"p":"(a) True or false: if A and B are 2-3-4 trees with exactly the same elements, they must be identical."}],"k":"mc","o":["True","False"],"a":1,"topics":["B_TREES"],"topicsBy":"site","x":"Inserting 1, 2, 3, 4, 5 pushes up 2; inserting 2, 3, 4, 5, 1 pushes up 3. Different trees.","part":"a"},{"s":[{"p":"(b) Insert 25 into this red-black tree (a * marks a node whose link to its parent is red):"},{"c":"20( *10(5, 17(*12, -)), 40(*30, -) )","lang":"txt"}]},{"id":14,"l":[{"p":"(b) Which tree results?"}],"k":"mc","o":["20( 10(5, 17(*12, -)), 30(25, 40) )","20( *10(5, 17(*12, -)), 30(25, *40) )","25( *10(5, 17(*12, 20)), 40(*30, -) )","20( *10(5, 17(*12, -)), 40(30(*25, -), -) )"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"As a 2-3 tree it is [10 20] with children [5], [12 17], [30 40]. Inserting 25 splits [25 30 40] and pushes 30 up, which splits [10 20 30] and pushes 20 up: a new root.","part":"b"},{"s":[{"p":"(c) sumDescendants replaces each node’s value with the sum of all its descendants’ values (not including itself), and returns its original value plus all its descendants’ values. For the tree 6(4(3, 5), 8(7, 9)), calling it on 6 returns 42 and changes the tree to 36(8(0, 0), 16(0, 0))."},{"c":"public class TreeNode {\n    public TreeNode left, right;\n    public int value;\n\n    public TreeNode(int n) {\n        value = n;\n    }\n\n    /* Replaces value with sum of all of its descendants' values. */\n    public int sumDescendants() {\n        if (⟪a⟫) {\n            int oldVal = value;\n            ⟪b⟫;\n            return oldVal;\n        } else {\n            int leftSum = 0; int rightSum = 0;\n            if (left != null) {\n                ⟪c⟫;\n            }\n            if (right != null) {\n                ⟪d⟫;\n            }\n            int oldVal = value;\n            ⟪e⟫;\n            return ⟪f⟫;\n        }\n    }\n}","lang":"java","f":{"a":"left == null && right == null","b":"value = 0","c":"leftSum = left.sumDescendants()","d":"rightSum = right.sumDescendants()","e":"value = leftSum + rightSum","f":"oldVal + value"}}]},{"id":15,"l":[{"p":"(c) if (____) — a leaf"}],"k":"blank","a":["left == null && right == null","right == null && left == null"],"topics":["RECURSION"],"topicsBy":"site","part":"c"},{"id":16,"l":[{"p":"(c) In the leaf case"}],"k":"blank","a":["value = 0"],"topics":["RECURSION"],"topicsBy":"site","part":"c"},{"id":17,"l":[{"p":"(c) If there is a left child"}],"k":"blank","a":["leftSum = left.sumDescendants()"],"topics":["RECURSION"],"topicsBy":"site","part":"c"},{"id":18,"l":[{"p":"(c) If there is a right child"}],"k":"blank","a":["rightSum = right.sumDescendants()"],"topics":["RECURSION"],"topicsBy":"site","part":"c"},{"id":19,"l":[{"p":"(c) After saving oldVal"}],"k":"blank","a":["value = leftSum + rightSum","value = rightSum + leftSum"],"topics":["RECURSION"],"topicsBy":"site","part":"c"},{"id":20,"l":[{"p":"(c) return ____"}],"k":"blank","a":["oldVal + value","value + oldVal","oldVal + leftSum + rightSum"],"topics":["RECURSION"],"topicsBy":"site","x":"Each child returns the full sum of its subtree; the node’s new value is the two children’s sums, and it returns that plus its old value.","part":"c"}],"topics":null},{"id":"61b-sp15-mt2/5","n":"5","t":"5. Code Analysis (2.5 pts)","b":[{"s":[{"p":"Give the runtime of each function in Θ notation as a function of its parameters."},{"c":"public static void f1(int n) {\n    for (int i = 0; i < 2*n; i += 1) {\n        System.out.println(\"hello\");\n    }\n}\n\npublic static void f2(int n) {\n    if (n == 0) { return; }\n    f2(n/2);\n    f1(n);\n    f2(n/2);\n}\n\npublic static void f3(int n) {\n    if (n == 0) { return; }\n    f3(n/3);\n    f1(n);\n    f3(n/3);\n    f1(n);\n    f3(n/3);\n}\n\npublic static void f4(int n) {\n    if (n == 0) { return; }\n    f4(n-1);\n    f1(17);\n    f4(n-1);\n}\n\npublic static void f5(int n, int m) {\n    if (m <= 0) {\n        return;\n    } else {\n        for (int i = 0; i < n; i += 1) {\n            f5(n, m-1);\n        }\n    }\n}","lang":"java"}]},{"id":21,"l":[{"p":"f1"}],"k":"mc","o":["Θ(1)","Θ(log n)","Θ(n)","Θ(n log n)","Θ(n²)","Θ(2ⁿ)","Θ(nᵐ)","Θ(mⁿ)"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":22,"l":[{"p":"f2"}],"k":"mc","o":["Θ(1)","Θ(log n)","Θ(n)","Θ(n log n)","Θ(n²)","Θ(2ⁿ)","Θ(nᵐ)","Θ(mⁿ)"],"a":3,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"The same pattern as mergesort."},{"id":23,"l":[{"p":"f3"}],"k":"mc","o":["Θ(1)","Θ(log n)","Θ(n)","Θ(n log n)","Θ(n²)","Θ(2ⁿ)","Θ(nᵐ)","Θ(mⁿ)"],"a":3,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"Like mergesort with 3 subproblems of size n/3."},{"id":24,"l":[{"p":"f4"}],"k":"mc","o":["Θ(1)","Θ(log n)","Θ(n)","Θ(n log n)","Θ(n²)","Θ(2ⁿ)","Θ(nᵐ)","Θ(mⁿ)"],"a":5,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site"},{"id":25,"l":[{"p":"f5"}],"k":"mc","o":["Θ(1)","Θ(log n)","Θ(n)","Θ(n log n)","Θ(n²)","Θ(2ⁿ)","Θ(nᵐ)","Θ(mⁿ)"],"a":6,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt2/6","n":"6","t":"6. The Right Tool for the Job (6 pts)","b":[{"s":[{"p":"For each task, pick the data structure best suited to it (TreeMap and TreeSet use red-black trees; HashMap and HashSet use external chaining). (The exam asked for one or two structures, a short description and an O bound.)"}]},{"id":26,"l":[{"p":"Task 1) Read a text file and print all the unique words in alphabetical order. (N words.)"}],"k":"mc","o":["A TreeSet: add every word, then iterate in order. O(N log N).","A HashMap from hashCode to word. O(N).","An ArrayList, checking each word against the rest. O(N²).","A HeapMinPQ of words. O(N)."],"a":0,"topics":["BSTS","ADTS"],"topicsBy":"site","x":"A HashSet plus sorting also works but is clumsier; a map from hash code to word wouldn’t detect duplicates."},{"id":27,"l":[{"p":"Task 2) Given ArrayList<String> observed (size N_O) of very long Strings (tens of thousands of characters), check each against an already-built collection known (size N_K) of highly dissimilar Strings. Which structure for known performs best in practice?"}],"k":"mc","o":["TreeSet: O(N_O log N_K), and comparisons stop after a few characters","HashSet: O(N_O), the fastest in practice","ArrayList: O(N_O · N_K)","HeapMinPQ: O(N_O log N_K)"],"a":0,"topics":["HASHING","BSTS"],"topicsBy":"site","x":"A HashSet is O(N_O) asymptotically, but hashing a string reads all of its tens of thousands of characters; dissimilar strings compare after a few characters."},{"id":28,"l":[{"p":"Task 3) Read many 512 × 512 grayscale images (Picture objects holding an int[][]) and display the unique ones, in any order. (N images.)"}],"k":"mc","o":["A HashSet of Pictures: O(N)","A TreeMap from hashCode to Picture: O(N log N)","An ArrayList, comparing each new image to all earlier ones: O(N)","A HeapMaxPQ of Pictures: O(N log N)"],"a":0,"topics":["HASHING"],"topicsBy":"site","x":"A TreeSet also works (O(N log N)) but needs Picture to be Comparable. Keying by hash code alone treats colliding images as duplicates."},{"id":29,"l":[{"p":"Task 4) Store the email address for each username on a website anyone can register on, many times over. Usernames and emails are Strings with the default hashCode and compareTo. (N users.)"}],"k":"mc","o":["A TreeMap: O(log N) per user, and attackers can’t force collisions","A HashMap: O(1) per user even under attack","An ArrayList of pairs: O(1) per user","A HeapMinPQ: O(log N) per user"],"a":0,"topics":["HASHING","BSTS"],"topicsBy":"site","x":"String’s hashCode is well known, so attackers could register many usernames with the same hash and make a HashMap O(N) per operation."},{"id":30,"l":[{"p":"Task 5) A social network capped at K users supports Neu (create a user), Befreunden (make two users friends) and Erweiterten Netzwerk (are two users connected by a chain of friendships?), each in O(log N) worst case. Which structures?"}],"k":"mc","o":["A WeightedQuickUnion plus a HashMap from username to id","A HashMap from username to a list of friends, searched with DFS","A TreeSet of usernames","A HeapMinPQ of friendships"],"a":0,"topics":["DISJOINT_SETS","HASHING"],"topicsBy":"site","x":"Neu: O(1) to add to the map. Befreunden and Erweiterten Netzwerk: O(1) lookups plus an O(log N) connect or isConnected."}],"topics":null},{"id":"61b-sp15-mt2/7","n":"7","t":"7. GorpyCorp (2 pts)","b":[{"s":[{"c":"public class Circle {\n    HashSet<Member> members;\n    String teamName;\n\n    public int hashCode() {\n        int hashCode = 0;\n        for (Member m : members) {\n            hashCode = hashCode * 31 + m.hashCode();\n        }\n        hashCode = hashCode + teamName.hashCode();\n        return hashCode;\n    }\n\n    public int compareTo(Circle other) {\n        if (this.members.size() == other.members.size())\n            return this.teamName.compareTo(other.teamName);\n        return this.members.size() - other.members.size();\n    }\n\n    public void addMember(Member newMember) {\n        members.add(newMember);\n    }\n    ...\n}","lang":"java"},{"p":"Gorpy stores each Circle’s leader in a separate HashMap<Circle, Member> leadLinks."}]},{"id":31,"l":[{"p":"What is the most significant problem, and does using a TreeMap fix it?"}],"k":"mc","o":["Circles are mutable: after addMember, a Circle’s hash code changes and leadLinks.get can’t find it. A TreeMap doesn’t fix it: Circle isn’t Comparable, and even if it were, a Circle that changed size would be in the wrong place in the tree.","Circle doesn’t override equals, so equal Circles can coexist; a TreeMap fixes it by using compareTo.","The hashCode causes too many collisions; a TreeMap fixes it because it stays balanced.","There is no problem with this design."],"a":0,"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"The other two choices got some partial credit on the exam, but mutability is the most significant problem."}],"topics":null},{"id":"61b-sp15-mt2/8","n":"8","t":"8. By the Numbers (3.5 pts)","b":[{"s":[{"p":"Give the minimum and maximum for each. Height is the number of links from the root to the farthest leaf (a lone root has height 0)."}]},{"id":32,"l":[{"p":"The minimum height of a BST with 15 nodes"}],"k":"blank","a":["3"],"topics":["BSTS"],"topicsBy":"site"},{"id":33,"l":[{"p":"…the maximum"}],"k":"blank","a":["14"],"topics":["BSTS"],"topicsBy":"site"},{"id":34,"l":[{"p":"The minimum height of a Quick Union object with 15 elements, all connected"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":35,"l":[{"p":"…the maximum"}],"k":"blank","a":["14"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":36,"l":[{"p":"The minimum height of a Weighted Quick Union object with 15 elements, all connected"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":37,"l":[{"p":"…the maximum"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":38,"l":[{"p":"The minimum height of a 2-3-4 tree with 15 items"}],"k":"blank","a":["1"],"topics":["B_TREES"],"topicsBy":"site"},{"id":39,"l":[{"p":"…the maximum"}],"k":"blank","a":["3"],"topics":["B_TREES"],"topicsBy":"site"},{"id":40,"l":[{"p":"The minimum height of an LLRB set with 15 items"}],"k":"blank","a":["3"],"topics":["RED_BLACK_TREES"],"topicsBy":"site"},{"id":41,"l":[{"p":"…the maximum"}],"k":"blank","a":["5"],"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"Pack as many 3-nodes as possible down the left of the corresponding 2-3 tree; each adds a level."},{"id":42,"l":[{"p":"The minimum height of a binary heap with 15 items"}],"k":"blank","a":["3"],"topics":["HEAPS"],"topicsBy":"site"},{"id":43,"l":[{"p":"…the maximum"}],"k":"blank","a":["3"],"topics":["HEAPS"],"topicsBy":"site"},{"id":44,"l":[{"p":"The minimum number of items in a single bucket of a chaining hash table with 30 items and 15 buckets"}],"k":"blank","a":["0"],"topics":["HASHING"],"topicsBy":"site"},{"id":45,"l":[{"p":"…the maximum"}],"k":"blank","a":["30"],"topics":["HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp15-mt2/10","n":"10","t":"10. Quartiler (2.5 pts)","b":[{"s":[{"p":"(Staff called this problem particularly challenging.) Design a Quartiler with add(x), getTopQuartile() (the item closest to the 75th percentile; e.g. after adding 1 to 100 it returns 75, after adding 1 to 4 it returns 3) and deleteTopQuartile(), each in amortized O(log N) time and O(N) space."}]},{"id":46,"l":[{"p":"(a) Which design works?"}],"k":"mc","o":["A max-heap of the values below the top quartile, a min-heap of the values above it, and a variable holding the top quartile itself; rebalance so the lower heap stays about 3 times the size of the upper one.","A red-black tree, searching it for the top quartile on each call.","A sorted ArrayList, reading index 3N/4.","A single min-heap, removing items until 3N/4 have been removed."],"a":0,"topics":["HEAPS"],"topicsBy":"site","x":"A balanced BST that tracks subtree sizes and selects rank 3N/4 also works. A plain red-black tree search is Θ(N); a sorted list makes add linear.","part":"a"},{"id":47,"l":[{"p":"(b) With the two-heap design, after adding 5, 1, 3, 2, 4, 6, 7, 8 in that order, what is the top quartile value?"}],"k":"blank","a":["6","7"],"topics":["HEAPS"],"topicsBy":"site","x":"The lower heap holds 1–5 and the upper heap 7, 8. Under a more standard definition of quartile, 7 is also acceptable.","part":"b"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp16-final","t":"Spring 2016 Final","src":{"exam":"https://drive.google.com/file/d/1Ta5ubPr7LThYI21nI-wxcFKtH3FDZa5S/view","sol":"https://drive.google.com/file/d/1yVkqsnEyEJlN34IwahG1QsuUomCyifFJ/view","topics":"sp16-final"},"p":[{"id":"61b-sp16-final/1","n":"1","t":"1. Giraphage (8 pts)","b":[{"s":[{"p":"Directed weighted graph: A→B (3), B→D (1), D→E (1), E→G (3), G→E (1), F→G (2), C→F (8), A→C (2), B→A (2), D→A (2)."},{"p":"For DFS from A and BFS from D, visit alphabetically earlier neighbors first."}]},{"id":1,"l":[{"p":"(a) DFS visit order"}],"k":"blank","a":["ABDEGCF"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) BFS visit order"}],"k":"blank","a":["DAEBCGF"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"b"},{"s":[{"p":"For Dijkstra from A, “visit” means relax all outgoing edges. Break distance ties alphabetically."}]},{"id":3,"l":[{"p":"(c) Dijkstra visit order"}],"k":"blank","a":["ACBDEGF"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"c"},{"s":[{"p":"A* seeks a shortest path from A to G. The fixed heuristic values are h(A)=0, h(B)=3, h(C)=2, h(D)=2, h(F)=1, h(G)=0."}]},{"id":4,"l":[{"p":"(d) Which value of h(E) can make A* return the wrong shortest paths tree?"}],"k":"mc","o":["-4","1","2","5","88","14"],"a":4,"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp16-final/2","n":"2","t":"2. Sorting (8 pts)","b":[{"s":[{"p":"The exam shows an unsorted array in column 1, five intermediate arrays in columns 2–6, and the sorted array in column 7. Match columns 2–6 to insertion sort, quicksort, heapsort, LSD radix sort, and MSD radix sort. Useful clues from the printed arrays: column 2 is grouped by the thousands digit; column 3 has a sorted prefix while its suffix is untouched; column 4 is a heap with two maximum items at the end; column 5 is ordered when the thousands digit is ignored; column 6 has its first item in final position after partitioning."}]},{"id":5,"l":[{"p":"(a) Algorithm in column 2"}],"k":"blank","a":["MSD radix sort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":6,"l":[{"p":"(a) Algorithm in column 3"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":7,"l":[{"p":"(a) Algorithm in column 4"}],"k":"blank","a":["Heapsort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":8,"l":[{"p":"(a) Algorithm in column 5"}],"k":"blank","a":["LSD radix sort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":9,"l":[{"p":"(a) Algorithm in column 6"}],"k":"blank","a":["Quicksort"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":10,"l":[{"p":"(a) Column containing the sorted array"}],"k":"blank","a":["7"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":11,"l":[{"p":"(b) Which traversal of a BST prints keys in sorted order?"}],"k":"mc","o":["Preorder","Inorder","Postorder","Reverse-preorder","Reverse-postorder"],"a":1,"topics":["BSTS","SORTING"],"topicsBy":"site","part":"b"},{"id":12,"l":[{"p":"(c) Worst-case runtime of random insertion into an LLRB, then inorder traversal, in Θ notation"}],"k":"blank","a":["Θ(N log N)"],"topics":["BSTS","SORTING"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp16-final/3","n":"3","t":"3. Reverse Engineering (6 pts)","b":[{"s":[{"p":"Selection sort question uses distinct symbols. The unsorted order is [astrology, dotted triangle, plus, diamond, arc, circle, divided circle, infinity]. After an unknown number of minimum-selection iterations it is [circle, infinity, plus, diamond, astrology, arc, divided circle, dotted triangle]. For each pair, give <, >, or ? (insufficient information): (i) divided circle compared with circle; (ii) divided circle compared with astrology; (iii) divided circle compared with dotted triangle; (iv) infinity compared with dotted triangle."}]},{"id":13,"l":[{"p":"(a) Relation 1"}],"k":"blank","a":[">"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":14,"l":[{"p":"(a) Relation 2"}],"k":"blank","a":["?"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":15,"l":[{"p":"(a) Relation 3"}],"k":"blank","a":["?"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":16,"l":[{"p":"(a) Relation 4"}],"k":"blank","a":["<"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"s":[{"p":"All topological sorts of a directed graph are listed: 1234567, 1234657, 1324567, 1324657. Give a valid adjacency list. The minimal graph has edges 1→2, 1→3, 4→5, 4→6, and 6→5; vertices 1 and 4 precede 7 through the listed orders, but 7 has no required outgoing edge."}]},{"id":17,"l":[{"p":"(b) Give a valid adjacency list"}],"k":"blank","a":["1: 2,3; 2: 7; 3: 7; 4: 5,6; 5: 7; 6: 7; 7: []"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp16-final/4","n":"4","t":"4. Facts (12 pts)","b":[{"s":[{"p":"Sorting facts: from the bank {A quicksort (nonrandom, in-place Hoare, leftmost pivot), B mergesort, C selection sort, D insertion sort, E LSD radix, F MSD radix, G heapsort, N none}, list all applicable letters."}]},{"id":18,"l":[{"p":"(a) Bounded by Ω(N log N) lower bound"}],"k":"blank","a":["A, B, C"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":19,"l":[{"p":"(a) Comparison sort with worst case asymptotically better than quicksort’s worst case"}],"k":"blank","a":["B, G"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":20,"l":[{"p":"(a) Worst case performs Θ(N) pairwise swaps"}],"k":"blank","a":["C"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":21,"l":[{"p":"(a) Comparison sort that never compares the same pair twice"}],"k":"blank","a":["A, B, D"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":22,"l":[{"p":"(a) Best case Θ(log N) for some inputs"}],"k":"blank","a":["N"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"s":[{"p":"Answer True or False."}]},{"id":23,"l":[{"p":"(b) Inserting one item into a “bushy” balanced BST with N items takes Θ(log N) in all cases."}],"k":"mc","o":["True","False","Either accepted"],"a":2,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":24,"l":[{"p":"(b) Inserting one item into a heap with N items takes Θ(log N) in all cases."}],"k":"mc","o":["True","False","Either accepted"],"a":1,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":25,"l":[{"p":"(b) The height of an N-item BST is O(N)."}],"k":"mc","o":["True","False","Either accepted"],"a":0,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":26,"l":[{"p":"(b) Squaring all integer keys in a valid BST always leaves a BST."}],"k":"mc","o":["True","False","Either accepted"],"a":1,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":27,"l":[{"p":"(b) Every valid left-leaning red-black tree is a valid BST."}],"k":"mc","o":["True","False","Either accepted"],"a":0,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":28,"l":[{"p":"(b) Every valid weighted quick-union tree is a valid BST."}],"k":"mc","o":["True","False","Either accepted"],"a":1,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":29,"l":[{"p":"(b) In a max heap, the parent of the second-largest item is always the root."}],"k":"mc","o":["True","False","Either accepted"],"a":2,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":30,"l":[{"p":"(b) The parent of the parent of the third-largest item in a max heap is always the root."}],"k":"mc","o":["True","False","Either accepted"],"a":1,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":31,"l":[{"p":"(b) A perfectly balanced quadtree with N items has asymptotically the same height as a 2–3 tree with N items."}],"k":"mc","o":["True","False","Either accepted"],"a":0,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"},{"id":32,"l":[{"p":"(b) Finding all matching tiles in getMapRaster using a quadtree takes Θ(log N) in all cases."}],"k":"mc","o":["True","False","Either accepted"],"a":1,"topics":["BSTS","HEAPS","DISJOINT_SETS","K_D_TREES"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp16-final/5","n":"5","t":"5. Graph Algorithms (7.5 pts)","b":[{"s":[{"p":"For each statement, answer True or False. If false, give a counterexample with at most five vertices; weighted graph edges must have distinct weights. The exam supplies the accepted starting vertex(es)."}]},{"id":33,"l":[{"p":"(statement 1) Prim’s last edge added to an MST is always the MST’s highest-weight edge."}],"k":"blank","a":["False (counterexample; start A)"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":34,"l":[{"p":"(statement 2) The largest edge in a graph is never part of a shortest paths tree."}],"k":"blank","a":["False (counterexample; either start)"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":35,"l":[{"p":"(statement 3) With at least four vertices, DFS and BFS from the same start never visit vertices in the same order."}],"k":"blank","a":["False (counterexample; start A or D)"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":36,"l":[{"p":"(statement 4) Dijkstra always finds shortest paths in a directed acyclic graph, even if it has negative edges."}],"k":"blank","a":["False (counterexample; start A)"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"},{"id":37,"l":[{"p":"(statement 5) In every undirected graph, an SPT from any vertex has total weight at most the MST weight."}],"k":"blank","a":["False (counterexample; start A)"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp16-final/6","n":"6","t":"6. Advanced Hash Party (4 pts)","b":[{"s":[{"p":"Give amortized best-case and worst-case runtimes for one insertion in Θ notation, in N items. Hashing costs O(1); resizing costs linear time; L is bounded by a constant. Give each as “best, worst”."}]},{"id":38,"l":[{"p":"Quadruple bucket count when L > 1."}],"k":"blank","a":["Θ(1), Θ(N)"],"topics":["HASHING"],"topicsBy":"site"},{"id":39,"l":[{"p":"Double bucket count when L > 1/100."}],"k":"blank","a":["Θ(1), Θ(N)"],"topics":["HASHING"],"topicsBy":"site"},{"id":40,"l":[{"p":"Increase bucket count by 10 when L > 1."}],"k":"blank","a":["Θ(N), Θ(N)"],"topics":["HASHING"],"topicsBy":"site"},{"id":41,"l":[{"p":"Double bucket count until no bucket has more than 5 items (may cause multiple doublings)."}],"k":"blank","a":["Θ(1), Θ(∞)"],"topics":["HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp16-final/7","n":"7","t":"7. Asymptotics (5 pts)","b":[{"s":[{"p":"Assume f takes Θ(N), g takes Θ(N²), and h takes O(N²), in all cases. Each returns an array the same length as its input."},{"c":"int[] doStuff1(int[] x) {\n  int N = x.length;\n  int[] effedX = f(x);\n  int[] newArray = new int[N];\n  for (int i = 0; i < N; i += 1) newArray[i] = effedX[i] * 2;\n  return g(newArray);\n}","lang":"java"}]},{"id":42,"l":[{"p":"(a) Runtime of doStuff1"}],"k":"blank","a":["Θ(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"s":[{"c":"int[] fx = f(x);                 // ⟪a⟫\nint[] gfx = g(f(x));            // ⟪b⟫\nint[] hgfx = h(g(f(x)));        // ⟪c⟫\nint[] hfx = h(f(x));            // ⟪d⟫\nint[] ddx = f(f(x));            // ⟪e⟫","lang":"java","f":{"a":"Θ(N)","b":"Θ(N²)","c":"Θ(N²)","d":"O(N²)","e":"Θ(N)"}}]},{"id":43,"l":[{"p":"(b) Runtime of line 1"}],"k":"blank","a":["Θ(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":44,"l":[{"p":"(b) Runtime of line 2"}],"k":"blank","a":["Θ(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":45,"l":[{"p":"(b) Runtime of line 3"}],"k":"blank","a":["Θ(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":46,"l":[{"p":"(b) Runtime of line 4"}],"k":"blank","a":["O(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":47,"l":[{"p":"(b) Runtime of line 5"}],"k":"blank","a":["Θ(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":48,"l":[{"p":"(c) Does f(x) always run faster than g(x) on a given computer? Explain briefly."}],"k":"blank","a":["No; asymptotic bounds do not determine actual time for a particular finite input, and constants can make g faster."],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp16-final/9","n":"9","t":"9. Heaps and JUnit (10 pts)","b":[{"s":[{"p":"Write a JUnit test for minheapify(int[] arr), which performs bottom-up min-heapification. Verify both that the result is a min heap and that it contains exactly the original items. Index 0 is used; children of k are 2k+1 and 2k+2. No duplicates. Complete this test and helpers."},{"c":"@Test public void testHeapify() {\n  int[] arr = {⟪a⟫};\n  int[] original = arr.clone();\n  minheapify(arr);\n  ⟪b⟫\n  ⟪c⟫\n}\nprivate static void testIsAHeap(int[] arr) {\n  for (int i = 0; i < arr.length; i++) {\n    if (⟪d⟫) assertTrue(arr[i] <= arr[2*i+1]);\n    if (⟪e⟫) assertTrue(arr[i] <= arr[2*i+2]);\n  }\n}\nprivate static void testHaveSameItems(int[] original, int[] arr) {\n  Arrays.sort(original); Arrays.sort(arr);\n  ⟪f⟫\n}","lang":"java","f":{"a":"7, 2, 5, 1, 9, 3","b":"testIsAHeap(arr);","c":"testHaveSameItems(original, arr);","d":"2*i+1 < arr.length","e":"2*i+2 < arr.length","f":"assertArrayEquals(original, arr);"}}]},{"id":49,"l":[{"p":"(a) Provide test values"}],"k":"blank","a":["7, 2, 5, 1, 9, 3"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"a"},{"id":50,"l":[{"p":"(b) Check heap property"}],"k":"blank","a":["testIsAHeap(arr);"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"b"},{"id":51,"l":[{"p":"(c) Check item preservation"}],"k":"blank","a":["testHaveSameItems(original, arr);"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"c"},{"id":52,"l":[{"p":"(d) Guard left child"}],"k":"blank","a":["2*i+1 < arr.length"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"d"},{"id":53,"l":[{"p":"(e) Guard right child"}],"k":"blank","a":["2*i+2 < arr.length"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"e"},{"id":54,"l":[{"p":"(f) Assert same sorted contents"}],"k":"blank","a":["assertArrayEquals(original, arr);"],"topics":["HEAPS","TESTING","JAVA"],"topicsBy":"site","part":"f"}],"topics":null},{"id":"61b-sp16-final/10","n":"10","t":"10. Fancy Asymptotics (6 pts)","b":[{"s":[{"p":"BitdiddleSort splits an array into equal halves, sorts half1 with algorithm A, half2 with B, and merges in O(N). Base case length 1. Values lie between 1 and 9."}]},{"id":55,"l":[{"p":"(a) A is a comparison sort and B is counting sort: tightest possible lower bound (Ω notation)"}],"k":"blank","a":["Ω(N log N) (Ω(N) also accepted)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":56,"l":[{"p":"(b) A is counting sort and B is quicksort: tightest upper bound (O notation)"}],"k":"blank","a":["O(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":57,"l":[{"p":"(c) A is quicksort and B is BitdiddleSort: tightest upper bound (O notation)"}],"k":"blank","a":["O(N²)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":58,"l":[{"p":"(d) A and B are both BitdiddleSort: runtime (Θ notation)"}],"k":"blank","a":["Θ(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp16-final/11","n":"11","t":"11. Dynamic Programming (10 pts)","b":[{"s":[{"p":"Neighborly letters differ by exactly one alphabet position; same letters are not neighborly, and a and z are not neighbors. Find the longest alphabetically neighborly subsequence of a nonempty lowercase char array. A subsequence need not be contiguous, and it may increase or decrease. Required expected runtime O(N), assuming constant-time HashMap operations. Use cache values for best subsequence length ending in each letter."},{"c":"public static int llans(char[] input) {\n  HashMap<Character, Integer> cache = new HashMap<>();\n  cache.put(input[0], 1);\n  for (int i = 1; i < input.length; i += 1) {\n    int prev = get(cache, ⟪a⟫, 0);\n    int next = get(cache, ⟪b⟫, 0);\n    cache.put(input[i], ⟪c⟫);\n  }\n  return ⟪d⟫;\n}","lang":"java","f":{"a":"input[i] - 1","b":"input[i] + 1","c":"Math.max(prev, next) + 1","d":"maxValue(cache)"}}]},{"id":59,"l":[{"p":"(a) Look up previous neighboring letter"}],"k":"blank","a":["input[i] - 1"],"topics":["RECURSION","HASHING","JAVA"],"topicsBy":"site","part":"a"},{"id":60,"l":[{"p":"(b) Look up next neighboring letter"}],"k":"blank","a":["input[i] + 1"],"topics":["RECURSION","HASHING","JAVA"],"topicsBy":"site","part":"b"},{"id":61,"l":[{"p":"(c) Update this letter’s best length"}],"k":"blank","a":["Math.max(prev, next) + 1"],"topics":["RECURSION","HASHING","JAVA"],"topicsBy":"site","part":"c"},{"id":62,"l":[{"p":"(d) Return the maximum cached length"}],"k":"blank","a":["maxValue(cache)"],"topics":["RECURSION","HASHING","JAVA"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp16-final/12","n":"12","t":"12. Calling Collect: Tries and Recursive Tree Programming (13 pts)","b":[{"s":[{"p":"A base-10 R-way trie stores positive integers digit by digit, most-significant digit first. Insert keys 1, 100, 10110, 1123, 1134, 2101, 355, 21. The root has dummy digit 0; mark key-ending nodes. Describe the trie by its keys and answer:"}]},{"id":63,"l":[{"p":"(a) List the stored keys represented by the trie"}],"k":"blank","a":["1, 100, 10110, 1123, 1134, 2101, 355, 21"],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"s":[{"p":"collect(z, matches, topDigits) appends topDigits to each key in subtrie z. z10 is the 0 child of the 1 child of root."}]},{"id":64,"l":[{"p":"(b) Results of collect(z10, matches, 1)"}],"k":"blank","a":["100, 10110"],"topics":["TRIES"],"topicsBy":"site","part":"b"},{"s":[{"p":"Complete collect. The call is never made on the root. Don’t prepend a leading zero when topDigits is zero."},{"c":"private void collect(Node x, List<Integer> matches, int topDigits) {\n  if (⟪a⟫) return;\n  if (⟪b⟫) matches.add(⟪c⟫);\n  for (Node child : x.children) {\n    collect(child, matches, ⟪d⟫);\n  }\n}","lang":"java","f":{"a":"x == null","b":"x.exists","c":"topDigits * 10 + x.dig","d":"topDigits * 10 + x.dig"}}]},{"id":65,"l":[{"p":"(c) Null base case"}],"k":"blank","a":["x == null"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"c"},{"id":66,"l":[{"p":"(c) Detect a stored key"}],"k":"blank","a":["x.exists"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"c"},{"id":67,"l":[{"p":"(c) Append this key"}],"k":"blank","a":["topDigits * 10 + x.dig"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"c"},{"id":68,"l":[{"p":"(c) Prefix digits for recursive child"}],"k":"blank","a":["topDigits * 10 + x.dig"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"c"},{"s":[{"p":"Complete findRepeaters: return every stored integer containing two identical consecutive digits. You may use collect."},{"c":"private void findRepeaters(Node x, List<Integer> matches, int topDigits) {\n  if (x == null) return;\n  for (Node child : x.children) {\n    if (⟪e⟫) {\n      collect(child, matches, ⟪f⟫);\n    } else {\n      findRepeaters(child, matches, ⟪g⟫);\n    }\n  }\n}","lang":"java","f":{"e":"x.dig == child.dig","f":"topDigits * 10 + x.dig","g":"topDigits * 10 + x.dig"}}]},{"id":69,"l":[{"p":"(d) Detect repeated adjacent digits"}],"k":"blank","a":["x.dig == child.dig"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"d"},{"id":70,"l":[{"p":"(d) Collect from repeated digit’s child"}],"k":"blank","a":["topDigits * 10 + x.dig"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"d"},{"id":71,"l":[{"p":"(d) Recurse with prefix"}],"k":"blank","a":["topDigits * 10 + x.dig"],"topics":["TRIES","RECURSION","JAVA"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp16-final/13","n":"13","t":"13. (Fond?) Farewell to 61B (10 pts)","b":[{"s":[{"p":"Build a FIFO MagicStringQueue using one MagicBag and constant additional memory. MagicBag.add(key) stores/replaces an equal key; remove(key) removes and returns an equal stored item, or null. enqueue is called at most one million times. Do not use a linked list or array as the queue. Describe the required fields, helper class, and operations."}]},{"id":72,"l":[{"p":"(a) Queue instance variables"}],"k":"blank","a":["MagicBag<Helper> bag; int addNumber, removeNumber"],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"a"},{"id":73,"l":[{"p":"(b) Helper instance variables"}],"k":"blank","a":["String value; int position"],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"b"},{"id":74,"l":[{"p":"(b) What should Helper.equals compare?"}],"k":"blank","a":["position only"],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"b"},{"id":75,"l":[{"p":"(b) What must Helper.hashCode satisfy?"}],"k":"blank","a":["Equal helpers (same position) must have equal hash codes."],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"b"},{"id":76,"l":[{"p":"(c) enqueue operation"}],"k":"blank","a":["Add new Helper(value, addNumber) to bag, then increment addNumber."],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"c"},{"id":77,"l":[{"p":"(c) dequeue operation"}],"k":"blank","a":["Remove helper at removeNumber using a dummy Helper, increment removeNumber, and return its value."],"topics":["DEQUES","HASHING"],"topicsBy":"site","part":"c"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp16-mt1","t":"Spring 2016 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1ooKS9xu6ojQ926axtwdsHM5vbBUh3ylh/view","sol":"https://drive.google.com/file/d/1JSJDTtwwj5VaV6u35XQ55ZjPMlKsZdXi/view","topics":"sp16-mt1"},"p":[{"id":"61b-sp16-mt1/1","n":"1","t":"1. IntList Essentials (3.5 pts)","b":[{"s":[{"c":"class IntList { int val; IntList tail; IntList(int v, IntList t) { val=v; tail=t; } }\nstatic void next1(IntList list) { list=list.tail; }\nstatic IntList next2(IntList list) { list=list.tail; return list; }\nstatic void next3(IntList list) { IntList temp=list; temp=temp.tail; }\nIntList L=new IntList(3,new IntList(2,new IntList(1,null)));\nnext1(L); System.out.println(L.val); // A\nnext2(L); System.out.println(L.val); // B\nnext3(L); System.out.println(L.val); // C","lang":"java"}]},{"id":1,"l":[{"p":"(a) Print A"}],"k":"blank","a":["3"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a) Print B"}],"k":"blank","a":["3"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":3,"l":[{"p":"(a) Print C"}],"k":"blank","a":["3"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"The method must insert x before the current first value while keeping the original IntList object, so an alias to it sees the new head too."},{"c":"public IntList strangeInsertFront(int x) {\n    ⟪a⟫;\n    ⟪b⟫;\n    return this;\n}","lang":"java","f":{"a":"this.tail = new IntList(this.val, this.tail)","b":"this.val = x"}}]},{"id":4,"l":[{"p":"(b) Preserve the old first value"}],"k":"blank","a":["this.tail = new IntList(this.val, this.tail)","tail = new IntList(val, tail)"],"topics":["LINKED_LISTS"],"topicsBy":"site","part":"b"},{"id":5,"l":[{"p":"(b) Set the new first value"}],"k":"blank","a":["this.val = x","val = x"],"topics":["LINKED_LISTS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp16-mt1/2","n":"2","t":"2. SList Debugging and Testing (2.5 pts)","b":[{"s":[{"p":"The implementation shares its sentinel across every SList because the field is static. Write a JUnit test that fails on this implementation but passes when each list has its own sentinel."},{"c":"@Test\npublic void test() {\n    ⟪a⟫\n    ⟪b⟫\n    ⟪c⟫\n    ⟪d⟫\n    ⟪e⟫\n}","lang":"java","f":{"a":"SList s1 = new SList();","b":"SList s2 = new SList();","c":"s1.insertFront(1);","d":"s2.insertFront(2);","e":"assertEquals(1, s1.getFront());"}}]},{"id":6,"l":[{"p":"(a) Make the first list"}],"k":"blank","a":["SList s1 = new SList();","SList s1=new SList();"],"topics":["TESTING","JAVA"],"topicsBy":"site","part":"a"},{"id":7,"l":[{"p":"(a) Make the second list"}],"k":"blank","a":["SList s2 = new SList();","SList s2=new SList();"],"topics":["TESTING","JAVA"],"topicsBy":"site","part":"a"},{"id":8,"l":[{"p":"(a) Insert into the first list"}],"k":"blank","a":["s1.insertFront(1)","s1.insertFront(1);"],"topics":["TESTING","JAVA"],"topicsBy":"site","part":"a"},{"id":9,"l":[{"p":"(a) Insert into the second list"}],"k":"blank","a":["s2.insertFront(2)","s2.insertFront(2);"],"topics":["TESTING","JAVA"],"topicsBy":"site","part":"a"},{"id":10,"l":[{"p":"(a) Assert the first list retained its value"}],"k":"blank","a":["assertEquals(1, s1.getFront())","assertEquals(1, s1.getFront());"],"topics":["TESTING","JAVA"],"topicsBy":"site","part":"a"}],"topics":null},{"id":"61b-sp16-mt1/3","n":"3","t":"3. ArrayHorse.com (5.5 pts)","b":[{"s":[{"p":"For the odd positive N, genCoolGrid fills a symmetric diamond with 8s. Other cells remain the int-array default, 0."},{"c":"// Show genCoolGrid(5), with rows from top to bottom.\n⟪a⟫\n⟪b⟫\n⟪c⟫\n⟪d⟫\n⟪e⟫","lang":"java","f":{"a":"0 0 8 0 0","b":"0 8 8 8 0","c":"8 8 8 8 8","d":"0 8 8 8 0","e":"0 0 8 0 0"}}]},{"id":11,"l":[{"p":"(a) Row 0"}],"k":"blank","a":["0 0 8 0 0"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":12,"l":[{"p":"(a) Row 1"}],"k":"blank","a":["0 8 8 8 0"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":13,"l":[{"p":"(a) Row 2"}],"k":"blank","a":["8 8 8 8 8"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":14,"l":[{"p":"(a) Row 3"}],"k":"blank","a":["0 8 8 8 0"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":15,"l":[{"p":"(a) Row 4"}],"k":"blank","a":["0 0 8 0 0"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"Map f over one column in place. The method returns the same matrix reference."},{"c":"public static int[][] mapColumn(IUF f, int[][] m, int c) {\n    ⟪a⟫\n    ⟪b⟫\n    ⟪c⟫\n    return m;\n}","lang":"java","f":{"a":"for (int i = 0; i < m.length; i += 1) {","b":"    m[i][c] = f.apply(m[i][c]);","c":"}"}}]},{"id":16,"l":[{"p":"(b) Iterate through the rows"}],"k":"blank","a":["for (int i = 0; i < m.length; i += 1) {","for(int i=0;i<m.length;i+=1){"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"b"},{"id":17,"l":[{"p":"(b) Transform this row’s selected column"}],"k":"blank","a":["m[i][c] = f.apply(m[i][c]);"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"b"},{"id":18,"l":[{"p":"(b) Close the loop"}],"k":"blank","a":["}"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"b"},{"id":19,"l":[{"p":"(c) Make a 5×5 cool grid and square its middle column"}],"k":"blank","a":["mapColumn(new Squarer(), genCoolGrid(5), 2)"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp16-mt1/4","n":"4","t":"4. All Natural (2.5 pts)","b":[{"s":[{"p":"Remove negative items from the SList without allocating nodes, preserving the order of the remaining items. The sentinel is not part of the list. Fill the right-hand solution."},{"c":"public void allNatural() {\n    IntNode p = ⟪a⟫;\n    while (⟪b⟫) {\n        if (⟪c⟫) {\n            ⟪d⟫\n        } else {\n            ⟪e⟫\n        }\n    }\n}","lang":"java","f":{"a":"sentinel","b":"p != null && p.next != null","c":"p.next.item < 0","d":"p.next = p.next.next;","e":"p = p.next;"}}]},{"id":20,"l":[{"p":"(a) Start at the sentinel"}],"k":"blank","a":["sentinel"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":21,"l":[{"p":"(a) Continue while a next node exists"}],"k":"blank","a":["p != null && p.next != null","p.next != null && p != null"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":22,"l":[{"p":"(a) Identify a negative next item"}],"k":"blank","a":["p.next.item < 0"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":23,"l":[{"p":"(a) Unlink that item"}],"k":"blank","a":["p.next = p.next.next;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":24,"l":[{"p":"(a) Advance to the next node"}],"k":"blank","a":["p = p.next;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"}],"topics":null},{"id":"61b-sp16-mt1/5","n":"5","t":"5. EggEgg (5.5 pts)","b":[{"s":[{"p":"Initial list: egg points to 1 → 9 → 2 → 6 → 6 → 4. Apply statements A through E in the given order: A removes two nodes after egg; B inserts a node with head one less than egg.tail.head before the tail; C sets backup = egg; D advances egg two links; E sets backup.tail = egg. Report the reachable lists after all five operations."},{"c":"After A–E:\negg → ⟪a⟫ → ⟪b⟫ → 4\nbackup → ⟪c⟫ → ⟪d⟫ → ⟪e⟫ → 4","lang":"java","f":{"a":"6","b":"6","c":"1","d":"6","e":"6"}}]},{"id":25,"l":[{"p":"(a) egg’s first value"}],"k":"blank","a":["6"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":26,"l":[{"p":"(a) egg’s next value"}],"k":"blank","a":["6"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":27,"l":[{"p":"(a) backup’s first value"}],"k":"blank","a":["1"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":28,"l":[{"p":"(a) backup’s second value"}],"k":"blank","a":["6"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":29,"l":[{"p":"(a) backup’s third value"}],"k":"blank","a":["6"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"Reorder all five operations so some reachable IntList has exactly 1 → 2 → 3 → 4."}]},{"id":30,"l":[{"p":"(b) Choose a valid operation order"}],"k":"mc","o":["CDEAB","CDAEB","ABCDE","BACDE"],"a":0,"also":[1],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp16-mt1/6","n":"6","t":"6. Array Processing (8 pts)","b":[{"s":[{"p":"Treat message as circular. The banned word is shorter than the nonempty message, and k is a valid start index."},{"c":"private static boolean matches(char[] message, char[] banned, int k) {\n    for (int i = ⟪a⟫; i < ⟪b⟫; i += 1) {\n        int messageIndex = ⟪c⟫;\n        if (⟪d⟫) {\n            ⟪e⟫\n        }\n    }\n    ⟪f⟫\n}","lang":"java","f":{"a":"0","b":"banned.length","c":"(k + i) % message.length","d":"message[messageIndex] != banned[i]","e":"return false;","f":"return true;"}}]},{"id":31,"l":[{"p":"(a) Initialize the loop"}],"k":"blank","a":["0"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":32,"l":[{"p":"(a) Loop over the banned word"}],"k":"blank","a":["banned.length"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":33,"l":[{"p":"(a) Wrap the message index around"}],"k":"blank","a":["(k + i) % message.length"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":34,"l":[{"p":"(a) Detect a character mismatch"}],"k":"blank","a":["message[messageIndex] != banned[i]"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":35,"l":[{"p":"(a) Return on mismatch"}],"k":"blank","a":["return false;"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":36,"l":[{"p":"(a) Return after every character matched"}],"k":"blank","a":["return true;"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"Search every possible circular starting index; return -1 when no start matches."},{"c":"public static int matchStart(char[] message, char[] banned) {\n    for (int k = 0; k < message.length; k += 1) {\n        if (matches(message, banned, k)) {\n            ⟪a⟫\n        }\n    }\n    ⟪b⟫\n}","lang":"java","f":{"a":"return k;","b":"return -1;"}}]},{"id":37,"l":[{"p":"(b) Return the matching start index"}],"k":"blank","a":["return k;"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"b"},{"id":38,"l":[{"p":"(b) Return when no match exists"}],"k":"blank","a":["return -1;"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"b"},{"s":[{"p":"Remove the one circular occurrence while restoring the original message order. The official solution rotates the copy into the correct position using an offset d."},{"c":"public static char[] filter(char[] message, char[] banned) {\n    int match = ⟪a⟫;\n    if (match < 0) return ⟪b⟫;\n    int numToCopy = ⟪c⟫;\n    char[] result = new char[⟪d⟫];\n    int messageIndex = ⟪e⟫;\n    for (int i = 0; i < ⟪f⟫; i += 1) {\n        int d = ⟪g⟫;\n        result[(d + i) % numToCopy] = message[(messageIndex + i) % message.length];\n    }\n    return ⟪h⟫;\n}","lang":"java","f":{"a":"matchStart(message, banned)","b":"message","c":"message.length - banned.length","d":"numToCopy","e":"(match + banned.length) % message.length","f":"numToCopy","g":"Math.max(messageIndex - banned.length, 0)","h":"result"}}]},{"id":39,"l":[{"p":"(c) Find the match"}],"k":"blank","a":["matchStart(message, banned)"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":40,"l":[{"p":"(c) Preserve the original if absent"}],"k":"blank","a":["message"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":41,"l":[{"p":"(c) Find the number of remaining chars"}],"k":"blank","a":["message.length - banned.length"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":42,"l":[{"p":"(c) Allocate the result"}],"k":"blank","a":["numToCopy"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":43,"l":[{"p":"(c) Start copying after the match"}],"k":"blank","a":["(match + banned.length) % message.length"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":44,"l":[{"p":"(c) Copy each remaining character"}],"k":"blank","a":["numToCopy"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":45,"l":[{"p":"(c) Compute the placement offset"}],"k":"blank","a":["Math.max(messageIndex - banned.length, 0)"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"},{"id":46,"l":[{"p":"(c) Return the filtered array"}],"k":"blank","a":["result"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp16-mt1/8","n":"8","t":"8. Interfaces (6 pts)","b":[{"s":[{"p":"(a) Add a default method to Deque that reverses its items. This recursive version uses only the existing Deque methods and leaves the same items in reverse order."},{"c":"default void reverse() {\n    if (⟪a⟫) {\n        Item first = ⟪b⟫;\n        ⟪c⟫;\n        ⟪d⟫;\n    }\n}","lang":"java","f":{"a":"size() > 1","b":"removeFirst()","c":"reverse()","d":"addLast(first)"}}]},{"id":58,"l":[{"p":"(a) Stop when at most one item remains"}],"k":"blank","a":["size() > 1"],"topics":["DEQUES","RECURSION"],"topicsBy":"site","part":"a"},{"id":59,"l":[{"p":"(a) Remove the front item"}],"k":"blank","a":["removeFirst()"],"topics":["DEQUES","RECURSION"],"topicsBy":"site","part":"a"},{"id":60,"l":[{"p":"(a) Reverse the rest"}],"k":"blank","a":["reverse()"],"topics":["DEQUES","RECURSION"],"topicsBy":"site","part":"a"},{"id":61,"l":[{"p":"(a) Restore the item at the back"}],"k":"blank","a":["addLast(first)"],"topics":["DEQUES","RECURSION"],"topicsBy":"site","part":"a"},{"s":[{"p":"Assume ArrayDeque and LinkedListDeque correctly implement Deque. A is the Deque default append(Deque); B and C are ArrayDeque.append(ArrayDeque) and the override append(Deque); D and E are ArrayDeque.prepend(Deque) and prepend(ArrayDeque). Choose which method runs or whether the expression fails for each receiver and argument type."},{"c":"Deque<Integer> d = new ArrayDeque<>();\nArrayDeque<Integer> ad = new ArrayDeque<>();\n// A: Deque.append(Deque)\n// B: ArrayDeque.append(ArrayDeque)\n// C: ArrayDeque.append(Deque)\n// D: ArrayDeque.prepend(Deque)\n// E: ArrayDeque.prepend(ArrayDeque)","lang":"java"}]},{"id":47,"l":[{"p":"d.prepend(d)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":0,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":48,"l":[{"p":"d.prepend(ad)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":0,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":49,"l":[{"p":"ad.prepend(d)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":5,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":50,"l":[{"p":"ad.prepend(ad)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":6,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":51,"l":[{"p":"ad.append(d)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":4,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":52,"l":[{"p":"ad.append(ad)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":3,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":53,"l":[{"p":"d.append(d)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":2,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"},{"id":54,"l":[{"p":"d.append(ad)"}],"k":"mc","o":["Compile-error","Runtime-error","A","B","C","D","E"],"a":2,"topics":["INHERITANCE","JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp16-mt1/9","n":"9","t":"9. Dynamic Method Selection and Inheritance (6 pts)","b":[{"s":[{"p":"Complete the blanks so DMSList.max() works. Every inserted number is positive; the base case node returns zero."},{"c":"public DMSList() {\n    sentinel = new IntNode(-1000, ⟪a⟫);\n}\npublic class ⟪b⟫ extends IntNode {\n    ⟪c⟫\n        super(0, null);\n    }\n    @Override\n    public int max() { return 0; }\n}","lang":"java","f":{"a":"new LastIntNode()","b":"LastIntNode","c":"public LastIntNode() {"}}]},{"id":55,"l":[{"p":"(a) Install the terminal node"}],"k":"blank","a":["new LastIntNode()"],"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"a"},{"id":56,"l":[{"p":"(a) Name the terminal node subtype"}],"k":"blank","a":["LastIntNode"],"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"a"},{"id":57,"l":[{"p":"(a) Declare its constructor"}],"k":"blank","a":["public LastIntNode() {"],"topics":["INHERITANCE","JAVA"],"topicsBy":"site","part":"a"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp16-mt2","t":"Spring 2016 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1GuTG5O-2SSudWgm47rIi4orkmmpU4Apa/view","sol":"https://drive.google.com/file/d/1KXLkjx1e8QPiu-waBJFwmcT5IToMHQK5/view","topics":"sp16-mt2"},"p":[{"id":"61b-sp16-mt2/1","n":"1","t":"1. BST and Hash Table Essentials (9 pts)","b":[{"s":[{"p":"(a) A map stores rental cost per square foot. Starting from an empty BSTMap (not self-balancing, ordered alphabetically with the alphabet _ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789), we call put(\"SAN JOSE\", 2.9), then:"},{"c":"put(\"LA\", 2.0)\nput(\"NYC\", 2.1)\nput(\"SD\", 6.3)\nput(\"BOSTON\", 2.3)\nput(\"UNIT 3\", 18.0)\nput(\"SF\", 2.7)\nput(\"SD\", 1.9)","lang":"java"}]},{"id":1,"l":[{"p":"(a) List the keys of the resulting BSTMap in preorder, separated by commas."}],"k":"blank","a":["SAN JOSE, LA, BOSTON, NYC, SD, UNIT 3, SF"],"topics":["BSTS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a) What value is stored with SD at the end?"}],"k":"blank","a":["1.9"],"topics":["BSTS"],"topicsBy":"site","x":"The tree is SAN JOSE(LA(BOSTON, NYC), SD(-, UNIT 3(SF, -))); the second put on SD replaces its value.","part":"a"},{"s":[{"p":"(b) Repeat with a hash map: a string’s hashCode is the number of its first letter (B → 2, L → 12, N → 14, S → 19, U → 21), there are 5 buckets, no resizing, and chaining as in class. Write each bucket’s keys in chain order, separated by commas; write [] if empty."}]},{"id":3,"l":[{"p":"(b) Bucket 0"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":4,"l":[{"p":"(b) Bucket 1"}],"k":"blank","a":["UNIT 3"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":5,"l":[{"p":"(b) Bucket 2"}],"k":"blank","a":["LA, BOSTON"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":6,"l":[{"p":"(b) Bucket 3"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":7,"l":[{"p":"(b) Bucket 4"}],"k":"blank","a":["SAN JOSE, NYC, SD, SF"],"topics":["HASHING"],"topicsBy":"site","x":"19, 14 and 19 mod 5 are 4; 12 and 2 are 2; 21 is 1. The second SD put just updates the value.","part":"b"},{"s":[{"p":"(c) A TreeSet uses this BST, written value(left, right). We call remove(29), using Hibbard deletion (at most two references should change)."},{"c":"20( 15(8, -), 29( 25(23(22, 24), -), 33(-, 35(34, 36)) ) )","lang":"txt"}]},{"id":8,"l":[{"p":"(c) Which tree can result?"}],"k":"mc","o":["20( 15(8, -), 33( 25(23(22, 24), -), 35(34, 36) ) )","20( 15(8, -), 25( 23(22, 24), 33(-, 35(34, 36)) ) )","20( 15(8, -), 34( 25(23(22, 24), -), 33(-, 35(-, 36)) ) )","20( 15(8, -), 25(23(22, 24), 35(34, 36)) )"],"a":0,"topics":["BSTS"],"topicsBy":"site","also":[1],"x":"29 is replaced by its successor 33 (whose right subtree moves up) or its predecessor 25 (whose left subtree moves up). Both are correct.","part":"c"},{"id":9,"l":[{"p":"(d) A HashMap’s key type has a hashCode that always returns 2000000000, and the value’s hashCode always returns −5. equals is properly implemented. Will containsKey and get always return the expected result (ignoring runtime)?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"Every key lands in one bucket, but the map still finds keys by checking equals within that bucket. Values’ hash codes are never used.","part":"d"},{"s":[{"c":"public class Glelk {\n    private int x;\n    private int y;\n\n    /** Normally an equals method should check that o is actually a Glelk.\n        We omit that check here for brevity. */\n    public boolean equals(Object o) {\n        Glelk other = (Glelk) o;\n        return (this.x == other.x) && (this.y == other.y);\n    }\n    public int hashCode() {\n        return super.hashCode() / 2;\n    }\n}","lang":"java"}]},{"id":10,"l":[{"p":"(e) Will all operations on a HashSet<Glelk> behave as we expect?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"super.hashCode() is Object’s, based on the memory address, so two equal Glelks can hash to different buckets and seem to “disappear”.","part":"e"}],"topics":null},{"id":"61b-sp16-mt2/2","n":"2","t":"2. WeightedQuickUnionUF (4 pts)","b":[{"s":[{"p":"(a) On the exam you drew WeightedQuickUnionUF trees of worst-case height for N = 4, 6 and 8 (one way: union two worst-case trees of size N/2)."}]},{"id":11,"l":[{"p":"(a) What is the worst-case height for N = 8?"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":12,"l":[{"p":"(b) Best-case height of a WeightedQuickUnionUF tree with N items"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":0,"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":13,"l":[{"p":"(b) Worst-case height"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"Height grows by one only when two trees of equal size join, which doubles the size.","part":"b"}],"topics":null},{"id":"61b-sp16-mt2/3","n":"3","t":"3. Exceptions (4 pts)","b":[{"s":[{"p":"Consider the code below. x / 2 rounds down to the nearest integer."},{"c":"public static void checkIfZero(int x) throws Exception {\n    if (x == 0) {\n        throw new Exception(\"x was zero!\");\n    }\n    System.out.println(x);\n}\n\npublic static int mystery(int x) {\n    int counter = 0;\n    try {\n        while (true) {\n            x = x / 2;\n            checkIfZero(x);\n            counter += 1;\n            System.out.println(\"counter is \" + counter);\n        }\n    } catch (Exception e) {\n        return counter;\n    }\n}\n\npublic static void main(String[] args) {\n    System.out.println(\"mystery of 1 is \" + mystery(1));\n    System.out.println(\"mystery of 6 is \" + mystery(6));\n}","lang":"java"}]},{"id":14,"l":[{"p":"What is the output when main is run? Put each printed line on its own line."}],"k":"blank","a":["mystery of 1 is 0\n3\ncounter is 1\n1\ncounter is 2\nmystery of 6 is 2"],"topics":["JAVA"],"topicsBy":"site","x":"“x was zero!” never prints: Java only prints an exception that isn’t caught."}],"topics":null},{"id":"61b-sp16-mt2/5","n":"5","t":"5. Runtime in Context (6 pts)","b":[{"s":[{"p":"readData reads N cities and their costs of living. isEmpty, readString and readDouble are constant time, Strings have constant length, and city names are unique."},{"c":"public static Map<String, Double> readData(In in) {\n    Map<String, Double> m = new BSTMap<String, Double>();\n    while (!in.isEmpty()) {\n        m.put(in.readString(), in.readDouble());\n    }\n    return m;\n}","lang":"java"}]},{"id":15,"l":[{"p":"(a) BSTMap (no balancing): best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ASYMPTOTICS","BSTS"],"topicsBy":"site","part":"a"},{"id":16,"l":[{"p":"(a) BSTMap: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS","BSTS"],"topicsBy":"site","x":"Best: the tree happens to be balanced. Worst: it’s a chain.","part":"a"},{"id":17,"l":[{"p":"(b) HashMap (String hashCode is Θ(1)): best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":2,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","part":"b"},{"id":18,"l":[{"p":"(b) HashMap: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","x":"If every key collides, each put scans one long chain.","part":"b"},{"id":19,"l":[{"p":"(c) 2-3 TreeMap: best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ASYMPTOTICS","B_TREES"],"topicsBy":"site","part":"c"},{"id":20,"l":[{"p":"(c) 2-3 TreeMap: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ASYMPTOTICS","B_TREES"],"topicsBy":"site","x":"A 2-3 tree stays balanced.","part":"c"}],"topics":null},{"id":"61b-sp16-mt2/6","n":"6","t":"6. Empirical Analysis (3.5 pts)","b":[{"s":[{"p":"A program’s running time R(N) was measured as below. Approximate it as ~aNᵇ using only the largest data points (round the exponent)."},{"c":"N      R(N)\n62     17000\n125    39000\n250    75000\n500    500000\n1000   4000000","lang":"txt"}]},{"id":21,"l":[{"p":"b (the exponent)"}],"k":"blank","a":["3"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":22,"l":[{"p":"a (the constant)"}],"k":"blank","a":["0.004","4/1000","1/250",".004"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"4000000 / 500000 = 8 = 2ᵇ, so b = 3; then a = 4000000 / 1000³ = 0.004."}],"topics":null},{"id":"61b-sp16-mt2/8","n":"8","t":"8. Balanced Trees (8 pts)","b":[{"s":[{"p":"(a) A max heap has the array representation [-, 8, 6, 5, 2, 3, 5, 1, 1, 0]."}]},{"id":23,"l":[{"p":"(a) Give the array after the maximum is deleted (as in class), without the unused first spot, separated by commas."}],"k":"blank","a":["6, 3, 5, 2, 0, 5, 1, 1","6 3 5 2 0 5 1 1"],"topics":["HEAPS"],"topicsBy":"site","x":"The last item 0 replaces 8 at the root and sinks: swap with 6, then with 3.","part":"a"},{"s":[{"p":"(b) Consider this 2-3 tree:"},{"c":"           [4]\n         /     \\\n      [2]       [6 8]\n     /   \\     /  |  \\\n   [1]   [3] [5] [7] [9]","lang":"txt"}]},{"id":24,"l":[{"p":"(b) Which insertion order produces this tree? (Several orders work.)"}],"k":"mc","o":["1, 2, 3, 4, 5, 6, 7, 8, 9","9, 8, 7, 6, 5, 4, 3, 2, 1","4, 2, 6, 8, 1, 3, 5, 7, 9","5, 4, 3, 2, 1, 6, 7, 8, 9"],"a":0,"topics":["B_TREES"],"topicsBy":"site","part":"b"},{"id":25,"l":[{"p":"(c) Tumelo suggests a heap where each item has 4 children. Compared with a normal binary heap, its Θ performance is…"}],"k":"mc","o":["Better","Worse","The same"],"a":2,"topics":["HEAPS"],"topicsBy":"site","x":"Its height is log₄ N = ½ log₂ N, still Θ(log N).","part":"c"}],"topics":null},{"id":"61b-sp16-mt2/9","n":"9","t":"9. That Asymptotics Problem You Knew Was Coming (9 pts)","b":[{"s":[{"p":"Give the runtime of each function in Θ notation."},{"c":"public static void p1(int N) {\n    for (int i = 0; i < N; i += 1) {\n        for (int j = 1; j < N; j = j + 2) {\n            System.out.println(\"hi!\");\n        }\n    }\n}\n\npublic static void p2(int N) {\n    for (int i = 0; i < N; i += 1) {\n        for (int j = 1; j < N; j = j * 2) {\n            System.out.println(\"hi!\");\n        }\n    }\n}\n\npublic static void p3(int N) {\n    if (N <= 1) return;\n    p3(N / 2);\n    p3(N / 2);\n}\n\npublic static void p4(int N) {\n    int m = (int) ((15 + Math.round(3.2 / 2)) *\n        (Math.floor(10 / 5.5) / 2.5) * Math.pow(2, 5));\n    for (int i = 0; i < m; i++) {\n        System.out.println(\"hi\");\n    }\n}\n\npublic static void p5(int N) {\n    for (int i = 1; i <= N * N; i *= 2) {\n        for (int j = 0; j < i; j++) {\n            System.out.println(\"moo\");\n        }\n    }\n}","lang":"java"}]},{"id":26,"l":[{"p":"p1"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":27,"l":[{"p":"p2"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":28,"l":[{"p":"p3"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":2,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"1 + 2 + 4 + … + N calls, each constant work."},{"id":29,"l":[{"p":"p4"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Nothing depends on N."},{"id":30,"l":[{"p":"p5"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"1 + 2 + 4 + … + N² = Θ(N²)."}],"topics":null},{"id":"61b-sp16-mt2/10","n":"10","t":"10. Yum Yum Agar (10 pts)","b":[{"s":[{"c":"public class Agar {\n    public int size; /* assume this is always even and positive */\n    public Agar(int s) { size = s; }\n    public boolean equals(Object o) {\n        Agar other = (Agar) o;\n        return this.size == other.size;\n    }\n    public int hashCode() { /* Not shown, but assume it's consistent with\n        equals, always positive, and does not change unless size changes. */\n    }\n}","lang":"java"},{"p":"Agars are stored in a HashSet with M buckets using insertAgar: if an Agar is inserted into a bucket that already holds an Agar exactly half its size, the new Agar eats it, absorbs its size (adding it to its own), and then tries to insert itself again. It may eat several Agars before it is finally inserted. Agars don’t eat Agars in other buckets. HashSet’s instance variables are private; its public methods include add, contains and remove. If x is already in the set, insertAgar does nothing."},{"p":"(a) Write shouldEatSomething, which returns true if x is going to eat a smaller Agar. HashSet converts hash codes to buckets as in class (hash codes are always positive). Make it as fast as possible."},{"c":"static boolean shouldEatSomething(Agar x, HashSet<Agar> set, int M) {\n    ⟪a⟫;\n    int xBin = ⟪b⟫;\n    int miniBin = ⟪c⟫;\n    return ⟪d⟫;\n}","lang":"java","f":{"a":"Agar mini = new Agar(x.size / 2)","b":"x.hashCode() % M","c":"mini.hashCode() % M","d":"set.contains(mini) && miniBin == xBin"}}]},{"id":31,"l":[{"p":"(a) First line"}],"k":"blank","a":["Agar mini = new Agar(x.size / 2)"],"topics":["HASHING","EQUALS"],"topicsBy":"site","part":"a"},{"id":32,"l":[{"p":"(a) int xBin = ____"}],"k":"blank","a":["x.hashCode() % M","Math.floorMod(x.hashCode(), M)"],"topics":["HASHING","EQUALS"],"topicsBy":"site","part":"a"},{"id":33,"l":[{"p":"(a) int miniBin = ____"}],"k":"blank","a":["mini.hashCode() % M","Math.floorMod(mini.hashCode(), M)"],"topics":["HASHING","EQUALS"],"topicsBy":"site","part":"a"},{"id":34,"l":[{"p":"(a) return ____"}],"k":"blank","a":["set.contains(mini) && miniBin == xBin","miniBin == xBin && set.contains(mini)","set.contains(mini) && xBin == miniBin"],"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"A stand-in Agar of half the size is equal to the one we’re looking for, so contains finds it; it must also be in x’s bucket.","part":"a"},{"s":[{"p":"(b) Now write insertAgar."},{"c":"static void insertAgar(Agar x, HashSet<Agar> set, int M) {\n    if (set.contains(x)) { return; }\n    if (⟪e⟫) {\n        ⟪f⟫;\n        ⟪g⟫;\n        ⟪h⟫;\n        ⟪i⟫;\n    } else {\n        ⟪j⟫;\n    }\n}","lang":"java","f":{"e":"shouldEatSomething(x, set, M)","f":"Agar mini = new Agar(x.size / 2)","g":"set.remove(mini)","h":"x.size += mini.size","i":"insertAgar(x, set, M)","j":"set.add(x)"}}]},{"id":35,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["shouldEatSomething(x, set, M)"],"topics":["HASHING","RECURSION"],"topicsBy":"site","part":"b"},{"id":36,"l":[{"p":"(b) First line inside"}],"k":"blank","a":["Agar mini = new Agar(x.size / 2)"],"topics":["HASHING","RECURSION"],"topicsBy":"site","part":"b"},{"id":37,"l":[{"p":"(b) Second line"}],"k":"blank","a":["set.remove(mini)"],"topics":["HASHING","RECURSION"],"topicsBy":"site","part":"b"},{"id":38,"l":[{"p":"(b) Third line"}],"k":"blank","a":["x.size += mini.size","x.size = x.size + mini.size","x.size += x.size / 2"],"topics":["HASHING","RECURSION"],"topicsBy":"site","part":"b"},{"id":39,"l":[{"p":"(b) Fourth line"}],"k":"blank","a":["insertAgar(x, set, M)"],"topics":["HASHING","RECURSION"],"topicsBy":"site","part":"b"},{"id":40,"l":[{"p":"(b) Otherwise"}],"k":"blank","a":["set.add(x)"],"topics":["HASHING","RECURSION"],"topicsBy":"site","x":"Remove the half-size Agar (an equal stand-in works because equals compares sizes), grow, and try again. Searching the whole set instead is slower and got partial credit.","part":"b"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp17-final","t":"Spring 2017 Final","src":{"exam":"https://drive.google.com/file/d/1bQwnCZ16mv8dhFqfKT6Q95k19zzMS9GN/view","sol":"https://drive.google.com/file/d/1p2pI8h8f9hqFDHDmJvCU_m-EClb2gF8j/view","topics":"sp17-final"},"p":[{"id":"61b-sp17-final/1","n":"1","t":"1. Mystery Spanning Tree 3000 (12 pts)","b":[{"s":[{"p":"Graph edges (weight): AB 6, AC 12, BC 3, BE 4, BF 7, BG 4, CD 9, CE 5, EF 2. List the edges in order; Prim starts at A and ties are alphabetical."}]},{"id":1,"l":[{"p":"Prim edge order (space-separated)"}],"k":"blank","a":["AB BC BE EF BG CD"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":2,"l":[{"p":"Kruskal edge order (space-separated)"}],"k":"blank","a":["EF BC BE BG AB CD"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":3,"l":[{"p":"Is there a vertex whose SPT equals this Prim MST?"}],"k":"mc","o":["Yes: B","Yes: any vertex","No"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":4,"l":[{"p":"Does increasing by 1 the minimum-weight edge crossing any cut necessarily increase the MST total weight?"}],"k":"mc","o":["True","False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":5,"l":[{"p":"Is the shortest A-to-B path always the same when restricted to the MST?"}],"k":"mc","o":["True","False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":6,"l":[{"p":"Is the maximum-weight edge crossing any cut in the maximum spanning tree?"}],"k":"mc","o":["True","False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/2","n":"2","t":"2. Sorting (28 pts)","b":[{"id":10,"l":[{"p":"Inversions in [A, D, B, W, K] sorted alphabetically"}],"k":"blank","a":["2"],"topics":["SORTING"],"topicsBy":"site"},{"id":11,"l":[{"p":"Array after heapify and one in-place heapsort remove-max"}],"k":"blank","a":["[14, 10, 13, 6, 5, 12, 17]"],"topics":["SORTING","HEAPS"],"topicsBy":"site"},{"s":[{"p":"For each scenario choose the best sort: 1 insertion, 2 merge, 3 Hoare quicksort, 4 LSD radix. Give worst-case time."}]},{"id":12,"l":[{"p":"N integers with constant maximum k: best sort number"}],"k":"blank","a":["4"],"topics":["SORTING"],"topicsBy":"site"},{"id":13,"l":[{"p":"N integers with constant maximum k: worst-case time, omit O(...)"}],"k":"blank","a":["N"],"topics":["SORTING"],"topicsBy":"site"},{"id":14,"l":[{"p":"N BigIntegers with max N^3 and comparison cost log N: best sort number"}],"k":"blank","a":["4"],"topics":["SORTING"],"topicsBy":"site"},{"id":15,"l":[{"p":"N BigIntegers with max N^3 and comparison cost log N: worst-case time, omit O(...)"}],"k":"blank","a":["N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":16,"l":[{"p":"N comparable objects in an array, constant comparison: best sort number"}],"k":"blank","a":["2"],"topics":["SORTING"],"topicsBy":"site"},{"id":17,"l":[{"p":"N comparable objects in an array, constant comparison: worst-case time, omit O(...)"}],"k":"blank","a":["N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":18,"l":[{"p":"Doubly linked list of N comparable objects, constant comparison: best sort number"}],"k":"blank","a":["2"],"topics":["SORTING"],"topicsBy":"site"},{"id":19,"l":[{"p":"Doubly linked list of N comparable objects, constant comparison: worst-case time, omit O(...)"}],"k":"blank","a":["N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":20,"l":[{"p":"10 Java Strings of length W: best sort number"}],"k":"blank","a":["1"],"topics":["SORTING"],"topicsBy":"site"},{"id":21,"l":[{"p":"10 Java Strings of length W: worst-case time, omit O(...)"}],"k":"blank","a":["W"],"topics":["SORTING"],"topicsBy":"site"},{"id":22,"l":[{"p":"N comparable objects with Θ(√N) inversions: best sort number"}],"k":"blank","a":["1"],"topics":["SORTING"],"topicsBy":"site"},{"id":23,"l":[{"p":"N comparable objects with Θ(√N) inversions: worst-case time, omit O(...)"}],"k":"blank","a":["N"],"topics":["SORTING"],"topicsBy":"site"},{"id":24,"l":[{"p":"N comparable objects with Θ(N²) inversions: best sort number"}],"k":"blank","a":["2"],"topics":["SORTING"],"topicsBy":"site"},{"id":25,"l":[{"p":"N comparable objects with Θ(N²) inversions: worst-case time, omit O(...)"}],"k":"blank","a":["N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":30,"l":[{"p":"Which array sorting algorithms are monotonically improving in inversion count?"}],"k":"sata","o":["Insertion sort","Selection sort","Heapsort","Quicksort (left pivot, Hoare)","LSD sort","MSD sort"],"a":[0,1,3,5],"topics":["SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/3","n":"3","t":"3. Traversals (14 pts)","b":[{"s":[{"p":"NAryIntTree nodes have int val and Node[] children (null for leaves). Complete recursive postorder and iterative level order."},{"c":"void printTreePostOrder() { ⟪a⟫; }\nvoid printTreePostOrderHelper(Node x) {\n  if (⟪b⟫) {\n    for (int i=0; i < ⟪c⟫; i++) ⟪d⟫;\n  }\n  System.out.println(⟪e⟫);\n}","lang":"java"}]},{"id":40,"l":[{"p":"Call helper on root"}],"k":"blank","a":["printTreePostOrderHelper(root)"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":41,"l":[{"p":"Children exist"}],"k":"blank","a":["x.children != null"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":42,"l":[{"p":"Iterate child count"}],"k":"blank","a":["x.children.length"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":43,"l":[{"p":"Recurse on child"}],"k":"blank","a":["printTreePostOrderHelper(x.children[i])"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":44,"l":[{"p":"Print node value"}],"k":"blank","a":["x.val"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"s":[{"c":"void printTreeLevelOrder() {\n  Queue<Node> fringe = new Queue<>();\n  fringe.⟪f⟫;\n  while (⟪g⟫) {\n    Node x = ⟪h⟫;\n    System.out.println(x.val);\n    if (x.children != null) {\n      for (int i=0; i < x.children.length; i++) ⟪i⟫;\n    }\n  }\n}","lang":"java"}]},{"id":45,"l":[{"p":"Enqueue root"}],"k":"blank","a":["enqueue(root)"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":46,"l":[{"p":"Queue nonempty"}],"k":"blank","a":["fringe.size() > 0"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":47,"l":[{"p":"Dequeue next node"}],"k":"blank","a":["fringe.dequeue()"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":48,"l":[{"p":"Enqueue each child"}],"k":"blank","a":["fringe.enqueue(x.children[i])"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/4","n":"4","t":"4. Algorithms and Data Structures (12 pts)","b":[{"id":60,"l":[{"p":"Does an adjacency heap improve worst-case asymptotic Dijkstra runtime over an adjacency list?"}],"k":"mc","o":["Better","Equivalent","Worse"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"Gulgate PQ insertion and deletion each cost Θ(N), change-priority Θ(1); Dijkstra initially inserts all V vertices and may process E edges."}]},{"id":61,"l":[{"p":"Dijkstra worst-case runtime in V,E"}],"k":"blank","a":["O(E + V^2)"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"s":[{"p":"Xelha Quick Union: constructor Θ(N), union Θ(N log N), connected Θ(log N). Kruskal uses a heap priority queue and E≫V."}]},{"id":62,"l":[{"p":"Kruskal worst-case runtime in V,E"}],"k":"blank","a":["O(V^2 log V)"],"topics":["GRAPH_REPRESENTATIONS","DISJOINT_SETS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/5","n":"5","t":"5. Potpourri (16 pts)","b":[{"s":[{"p":"A ternary heap can use a compact array. Give formulas for root index zero."}]},{"id":70,"l":[{"p":"parent(k)"}],"k":"blank","a":["(k - 1) / 3"],"topics":["HEAPS"],"topicsBy":"site"},{"id":71,"l":[{"p":"left(k)"}],"k":"blank","a":["3*k + 1"],"topics":["HEAPS"],"topicsBy":"site"},{"id":72,"l":[{"p":"middle(k)"}],"k":"blank","a":["3*k + 2"],"topics":["HEAPS"],"topicsBy":"site"},{"id":73,"l":[{"p":"right(k)"}],"k":"blank","a":["3*k + 3"],"topics":["HEAPS"],"topicsBy":"site"},{"id":74,"l":[{"p":"If equals is overridden without hashCode, can HashSet.contains return an incorrect result?"}],"k":"mc","o":["True","False"],"a":0,"topics":["HASHING"],"topicsBy":"site"},{"id":75,"l":[{"p":"Does omitting hashCode make HashSet.contains much more likely to take linear time?"}],"k":"mc","o":["True","False"],"a":1,"topics":["HASHING"],"topicsBy":"site"},{"s":[{"p":"Give a suitable interface enabling generic trie keys, with one method that exposes the indexed digit/character at position i."}]},{"id":76,"l":[{"p":"Interface name and method signature"}],"k":"blank","a":["interface HasDigits { int digit(int i); }"],"topics":["TRIES"],"topicsBy":"site"},{"id":77,"l":[{"p":"Main consideration for DogPicture implementing that interface"}],"k":"blank","a":["Whether anyone will want prefix operations with DogPictures"],"topics":["TRIES"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/6","n":"6","t":"6. Stocks (12 pts)","b":[{"s":[{"p":"A stock’s price is mutated after the stock is inserted in a heap-based MaxPQ. Select all direct issues."}]},{"id":80,"l":[{"p":"Issues present"}],"k":"sata","o":["Returns k cheapest stocks","May return duplicate stock entries","Mutating a heap item can break heap order and yield wrong results","List return type with ArrayList value is a compile error","Map cannot refer to objects stored in the heap"],"a":[2],"topics":["HEAPS","HASHING"],"topicsBy":"site"},{"id":81,"l":[{"p":"Worst-case runtime with nice hash spread, in S,T,k"}],"k":"blank","a":["S + T + k log S"],"topics":["HEAPS","HASHING"],"topicsBy":"site"},{"id":82,"l":[{"p":"Space complexity in S"}],"k":"blank","a":["S"],"topics":["HEAPS","HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/7","n":"7","t":"7. Arithmetic Tree (23 pts)","b":[{"s":[{"p":"Complete postorder evaluation of arithmetic expression nodes. Nodes expose children and processNode(Stack<Integer>)."},{"c":"static int evaluateTree(Node tree) {\n  Stack<Integer> stk = new Stack<>();\n  ⟪a⟫\n  ⟪b⟫\n}\nstatic void evaluateTreeHelper(Node tree, Stack<Integer> stk) {\n  for (⟪c⟫) ⟪d⟫\n  ⟪e⟫\n}\nvoid processNode(Stack<Integer> stk) {\n  int res = stk.pop();\n  for (int i=1; i < numArgs(); i++) res = apply(res, ⟪f⟫);\n  stk.push(res);\n}\nvoid processNumber(Stack<Integer> stk) { stk.push(⟪g⟫); }","lang":"java"}]},{"id":90,"l":[{"p":"Evaluate tree helper"}],"k":"blank","a":["evaluateTreeHelper(tree, stk);"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":91,"l":[{"p":"Return result"}],"k":"blank","a":["return stk.pop();"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":92,"l":[{"p":"Loop over children"}],"k":"blank","a":["Node c : tree.children"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":93,"l":[{"p":"Recurse"}],"k":"blank","a":["evaluateTreeHelper(c, stk);"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":94,"l":[{"p":"Process after children"}],"k":"blank","a":["tree.processNode(stk);"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":95,"l":[{"p":"Pop next argument"}],"k":"blank","a":["stk.pop()"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":96,"l":[{"p":"Push number value"}],"k":"blank","a":["value"],"topics":["TREE_TRAVERSALS","ADTS"],"topicsBy":"site"},{"id":97,"l":[{"p":"Multiplication apply body"}],"k":"blank","a":["return arg1 * arg2;"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":98,"l":[{"p":"Addition apply body"}],"k":"blank","a":["return arg1 + arg2;"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/9","n":"9","t":"9. Asymptotics (16 pts)","b":[{"id":110,"l":[{"p":"f1 best runtime (two recursive calls on N/2 plus Θ(N²) work)"}],"k":"blank","a":["N^2"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":111,"l":[{"p":"f1 worst runtime"}],"k":"blank","a":["N^2"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":112,"l":[{"p":"f2 best runtime"}],"k":"blank","a":["1"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":113,"l":[{"p":"f2 worst runtime"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":114,"l":[{"p":"f3 best runtime"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":115,"l":[{"p":"f3 worst runtime"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":116,"l":[{"p":"f4 best runtime"}],"k":"blank","a":["1"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":117,"l":[{"p":"f4 worst runtime"}],"k":"blank","a":["2^N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"f2 loops across the array; a null string causes one replacement and recursive continuation. f3 visits each node once. f4 recursively processes the left subtree twice after aliasing right=left."}]}],"topics":null},{"id":"61b-sp17-final/10","n":"10","t":"10. Return of the XelhaTree (16 pts)","b":[{"s":[{"c":"boolean isAHeap(IntTree xt) {\n  if (xt == null) return true;\n  if (xt.item > getItem(xt.left) || xt.item > getItem(xt.right)) return false;\n  return ⟪a⟫;\n}\nvoid getTreeValues(IntTree xt, List<Integer> out) {\n  if (xt == null) return;\n  ⟪b⟫\n  ⟪c⟫\n  ⟪d⟫\n}\nboolean validXelhaTree(IntTree xt, List<Integer> vals) {\n  List<Integer> treeValues = new ArrayList<>();\n  getTreeValues(xt, treeValues);\n  return ⟪e⟫;\n}","lang":"java"}]},{"id":130,"l":[{"p":"Recursive heap checks"}],"k":"blank","a":["isAHeap(xt.left) && isAHeap(xt.right)"],"topics":["TREE_TRAVERSALS","BSTS"],"topicsBy":"site"},{"id":131,"l":[{"p":"Inorder visit left"}],"k":"blank","a":["getTreeValues(xt.left, out);"],"topics":["TREE_TRAVERSALS","BSTS"],"topicsBy":"site"},{"id":132,"l":[{"p":"Append item"}],"k":"blank","a":["out.add(xt.item);"],"topics":["TREE_TRAVERSALS","BSTS"],"topicsBy":"site"},{"id":133,"l":[{"p":"Inorder visit right"}],"k":"blank","a":["getTreeValues(xt.right, out);"],"topics":["TREE_TRAVERSALS","BSTS"],"topicsBy":"site"},{"id":134,"l":[{"p":"Check heap and inorder sequence"}],"k":"blank","a":["isAHeap(xt) && treeValues.equals(vals)"],"topics":["TREE_TRAVERSALS","BSTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/11","n":"11","t":"11. MaxPQ (12 pts)","b":[{"s":[{"p":"Implement a max priority queue by wrapping MinPQ with a reverse comparator. Reference-sheet MinPQ offers insert, delMin and a comparator constructor."},{"c":"class MaxPQ<Item extends Comparable<Item>> {\n  ⟪a⟫\n  MaxPQ() { pq = new MinPQ<Item>(new ReverseComparator()); }\n  class ReverseComparator implements Comparator<Item> {\n    public int compare(Item i1, Item i2) { return ⟪c⟫; }\n  }\n  Item delMax() { return ⟪d⟫; }\n  void insert(Item x) { ⟪e⟫; }\n}","lang":"java"}]},{"id":140,"l":[{"p":"Field declaration"}],"k":"blank","a":["private MinPQ<Item> pq;"],"topics":["HEAPS"],"topicsBy":"site"},{"id":141,"l":[{"p":"Reverse order comparator"}],"k":"blank","a":["i2.compareTo(i1)"],"topics":["HEAPS"],"topicsBy":"site"},{"id":142,"l":[{"p":"Delete max"}],"k":"blank","a":["pq.delMin()"],"topics":["HEAPS"],"topicsBy":"site"},{"id":143,"l":[{"p":"Insert item"}],"k":"blank","a":["pq.insert(x)"],"topics":["HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/12","n":"12","t":"12. Danger and Optimization (12 pts)","b":[{"id":150,"l":[{"p":"Appropriate integer sorting choices for hostile inputs"}],"k":"sata","o":["Merge sort","Insertion sort","Shuffled Hoare quicksort","LSD radix sort","Recursive MSD sort"],"a":[0,2,3],"topics":["SORTING"],"topicsBy":"site"},{"id":151,"l":[{"p":"Appropriate set choices for hostile Java String inputs"}],"k":"sata","o":["2-3 tree set","LLRB set","Hash set","Trie set (array links)","TST set"],"a":[0,1],"topics":["BSTS","HASHING","TRIES"],"topicsBy":"site"},{"id":152,"l":[{"p":"Appropriate traversal for user-submitted graphs: recursive DFS"}],"k":"mc","o":["Appropriate","Inappropriate"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":153,"l":[{"p":"Appropriate traversal for user-submitted graphs: BFS"}],"k":"mc","o":["Appropriate","Inappropriate"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-final/13","n":"13","t":"13. Reductions (26.5 pts)","b":[{"id":160,"l":[{"p":"Maximum spanning tree using unmodified Kruskal black box"}],"k":"blank","a":["Negate every edge weight, then run Kruskal"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":161,"l":[{"p":"Shortest path where path cost is sum of weights plus edge count, using Dijkstra black box"}],"k":"blank","a":["Add 1 to every edge weight, then run Dijkstra"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":162,"l":[{"p":"Does adding Q to every edge preserve shortest paths when exactly one edge has weight −Q?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":163,"l":[{"p":"A zelch-based sort needs Ω(N log log N) zelch operations"}],"k":"mc","o":["True","False"],"a":0,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":164,"l":[{"p":"Sorting in Zulg has Θ(N log log N) worst-case time"}],"k":"mc","o":["True","False"],"a":1,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":165,"l":[{"p":"Optimal Zulg sorting is O(N log log N)"}],"k":"mc","o":["True","False"],"a":1,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":166,"l":[{"p":"Every Zulg sorting algorithm is O(N log log N)"}],"k":"mc","o":["True","False"],"a":1,"topics":["SORTING","ASYMPTOTICS"],"topicsBy":"site"},{"id":167,"l":[{"p":"Some MinimumPQ implementation has add Θ(log log N)"}],"k":"mc","o":["True","False"],"a":0,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":168,"l":[{"p":"Some implementation has removeMin Θ(log log N)"}],"k":"mc","o":["True","False"],"a":0,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":169,"l":[{"p":"One implementation has both add and removeMin Θ(log log N)"}],"k":"mc","o":["True","False"],"a":1,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":170,"l":[{"p":"Some implementation has add Θ(1)"}],"k":"mc","o":["True","False"],"a":0,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":171,"l":[{"p":"Some implementation has removeMin Θ(1)"}],"k":"mc","o":["True","False"],"a":0,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":172,"l":[{"p":"One implementation has both add and removeMin Θ(1)"}],"k":"mc","o":["True","False"],"a":1,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":173,"l":[{"p":"A LongestPath solver exists in O(N^k) time"}],"k":"mc","o":["True","False","Depends on P=NP"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":174,"l":[{"p":"A proposed LongestPath solution can be checked in O(N^k) time"}],"k":"mc","o":["True","False","Depends on P=NP"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":175,"l":[{"p":"The byte length of the shortest Java program solving LongestPath can be calculated"}],"k":"mc","o":["True","False","Depends on P=NP"],"a":1,"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp17-mt1","t":"Spring 2017 Midterm 1","src":{"exam":"https://drive.google.com/file/d/12KqULT9XIb3KHQqOdGQprsKELYTrAXN5/view","sol":"https://drive.google.com/file/d/15Vnd9z34Wlp-D9boc4ZezgpyH_ul65qZ/view","topics":"sp17-mt1"},"p":[{"id":"61b-sp17-mt1/1","n":"1","t":"1. Pass By Value (4.5 pts)","b":[{"s":[{"c":"static void swap(int x, int y) { int temp=y; y=x; x=temp; System.out.println(x); }\nstatic void swap(int[] x, int[] y) { int[] temp=y; y=x; x=temp; System.out.println(x[0]); }\nint x1=42, y1=12;\nswap(x1,y1); // A\nSystem.out.println(x1); // B\nSystem.out.println(y1); // C\nint[] x2={1,2,3}, y2={4,5,6};\nswap(x2,y2); // D\nSystem.out.println(x2[0]); // E\nSystem.out.println(y2[0]); // F\nx2=new int[]{1,2,3}; y2=new int[]{4,5,6};\nswap(x2[0],y2[0]); // G\nSystem.out.println(x2[0]); // H\nSystem.out.println(y2[0]); // I","lang":"java"}]},{"id":1,"l":[{"p":"Print A"}],"k":"blank","a":["12"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":2,"l":[{"p":"Print B"}],"k":"blank","a":["42"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":3,"l":[{"p":"Print C"}],"k":"blank","a":["12"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":4,"l":[{"p":"Print D"}],"k":"blank","a":["4"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":5,"l":[{"p":"Print E"}],"k":"blank","a":["1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":6,"l":[{"p":"Print F"}],"k":"blank","a":["4"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":7,"l":[{"p":"Print G"}],"k":"blank","a":["4"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":8,"l":[{"p":"Print H"}],"k":"blank","a":["1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":9,"l":[{"p":"Print I"}],"k":"blank","a":["4"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/2","n":"2","t":"2. The Return of Pass By Value (7 pts)","b":[{"s":[{"p":"IntList5000 has fields rest, primitive, reference, and static slogan. Its constructor assigns them from its arguments."},{"c":"static void disenturbulate(IntList5000 p) {\n    p.primitive=5000; p.reference=new Integer(1000);\n    p=new IntList5000(null,5,10,\"relax\");\n}\nvoid indoctrinate(int b) { b=0; this.rest.primitive=b; }\nvoid integrate(Integer v) { this.reference=v; v=new Integer(10); }\nIntList5000 x=new IntList5000(null,100,new Integer(7),\"live\");\nIntList5000 y=new IntList5000(x,9,x.reference,\"eat\");\nSystem.out.println(y.primitive); // A\nSystem.out.println(y.reference); // B\ndisenturbulate(y);\nSystem.out.println(y.primitive); // C\nSystem.out.println(y.reference); // D\ny.indoctrinate(100);\nSystem.out.println(x.primitive); // E\nx.integrate(new Integer(200));\nSystem.out.println(x.reference); // F\nSystem.out.println(IntList5000.slogan); // G","lang":"java"}]},{"id":10,"l":[{"p":"Print A"}],"k":"blank","a":["9"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":11,"l":[{"p":"Print B"}],"k":"blank","a":["7"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":12,"l":[{"p":"Print C"}],"k":"blank","a":["5000"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":13,"l":[{"p":"Print D"}],"k":"blank","a":["1000"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":14,"l":[{"p":"Print E"}],"k":"blank","a":["0"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":15,"l":[{"p":"Print F"}],"k":"blank","a":["200"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":16,"l":[{"p":"Print G"}],"k":"blank","a":["relax"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/3","n":"3","t":"3. Potpourri (6 pts)","b":[{"s":[{"p":"Assume Cat and Dog are subclasses of Animal. All three classes have default constructors. Consider each assignment independently."},{"c":"Cat c = new Animal();","lang":"java"}]},{"id":20,"l":[{"p":"Result for Cat c = new Animal();"}],"k":"mc","o":["Compilation error","Runtime error","Runs fine"],"a":0,"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"s":[{"c":"Animal a = new Cat();","lang":"java"}]},{"id":21,"l":[{"p":"Result for Animal a = new Cat();"}],"k":"mc","o":["Compilation error","Runtime error","Runs fine"],"a":2,"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"s":[{"c":"Dog d = new Cat();","lang":"java"}]},{"id":22,"l":[{"p":"Result for Dog d = new Cat();"}],"k":"mc","o":["Compilation error","Runtime error","Runs fine"],"a":0,"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"s":[{"c":"Animal a = (Cat) new Cat();","lang":"java"}]},{"id":23,"l":[{"p":"Result for Animal a = (Cat) new Cat();"}],"k":"mc","o":["Compilation error","Runtime error","Runs fine"],"a":2,"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"s":[{"c":"Dog d = (Dog) new Animal();","lang":"java"}]},{"id":24,"l":[{"p":"Result for Dog d = (Dog) new Animal();"}],"k":"mc","o":["Compilation error","Runtime error","Runs fine"],"a":1,"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"s":[{"p":"Select each item that makes javac abort compilation."}]},{"id":25,"l":[{"p":"Compile-time errors"}],"k":"sata","o":["Missing semicolon at end of statement","Division by an int variable whose value may be zero","Attempting to instantiate a generic array as new T[10], where T is a type parameter","Accessing x[i] when x has length 3 and i is 10","Missing return type for a static method"],"a":[0,2,4],"topics":["JAVA"],"topicsBy":"site"},{"s":[{"p":"Omid sets a breakpoint on the call to f, reaches it, then clicks “Step Over” exactly once. Write the output, including what printed before the breakpoint."},{"c":"public static void f() {\n  System.out.println(2);\n  System.out.println(3);\n}\npublic static void main(String[] args) {\n  System.out.println(1);\n  f(); // BREAKPOINT\n  System.out.println(4);\n}","lang":"java"}]},{"id":26,"l":[{"p":"Output line 1"}],"k":"blank","a":["1"],"topics":["JAVA"],"topicsBy":"site"},{"id":27,"l":[{"p":"Output line 2"}],"k":"blank","a":["2"],"topics":["JAVA"],"topicsBy":"site"},{"id":28,"l":[{"p":"Output line 3"}],"k":"blank","a":["3"],"topics":["JAVA"],"topicsBy":"site"},{"id":29,"l":[{"p":"Does the final println(4) run after that single Step Over?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/4","n":"4","t":"4. Flirbocon (12 pts)","b":[{"s":[{"p":"Assume Falcon extends Bird, and the following declarations are in scope:"},{"c":"Bird bird = new Falcon();\nFalcon falcon = (Falcon) bird;","lang":"java"},{"p":"All methods are instance methods. F1: Bird::gulgate(Bird); F2: Bird::gulgate(Falcon); F3: Falcon::gulgate(Bird); F4: Falcon::gulgate(Falcon)."}]},{"id":30,"l":[{"p":"For bird.gulgate(bird), which individual features alone let the call compile?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[0],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":31,"l":[{"p":"For bird.gulgate(bird), which set makes Bird::gulgate(Bird) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[0],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":32,"l":[{"p":"For bird.gulgate(bird), which set makes Falcon::gulgate(Bird) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[0,2],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":33,"l":[{"p":"For falcon.gulgate(falcon), which individual features alone let the call compile?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[0,1,2,3],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":34,"l":[{"p":"For falcon.gulgate(falcon), which set makes Bird::gulgate(Bird) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[0],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":35,"l":[{"p":"For falcon.gulgate(falcon), which set makes Bird::gulgate(Falcon) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[1],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":36,"l":[{"p":"For falcon.gulgate(falcon), which set makes Falcon::gulgate(Bird) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[2],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":37,"l":[{"p":"For falcon.gulgate(falcon), which set makes Falcon::gulgate(Falcon) execute?"}],"k":"sata","o":["F1","F2","F3","F4","Impossible"],"a":[3],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/5","n":"5","t":"5. Hoffery (8 pts)","b":[{"s":[{"p":"UnaryFunction<T> has T apply(T x). A Spy wraps a UnaryFunction, returns its result, remembers arguments in order, and prints the history without destroying it. Assume ArrayDeque supports addLast and printDeque."},{"c":"public class Spy<T> ⟪a⟫ {\n  ArrayDeque<T> history;\n  UnaryFunction<T> function;\n  public Spy(UnaryFunction<T> function) {\n    this.history = ⟪b⟫;\n    this.function = function;\n  }\n  @Override\n  public T apply(T x) {\n    ⟪c⟫\n    ⟪d⟫\n  }\n  public void printArgumentHistory() {\n    ⟪e⟫\n  }\n}","lang":"java"}]},{"id":40,"l":[{"p":"Interface declaration"}],"k":"blank","a":["implements UnaryFunction<T>"],"topics":["JAVA"],"topicsBy":"site"},{"id":41,"l":[{"p":"Construct history"}],"k":"blank","a":["new ArrayDeque<>()"],"topics":["JAVA"],"topicsBy":"site"},{"id":42,"l":[{"p":"Record argument"}],"k":"blank","a":["history.addLast(x);"],"topics":["JAVA"],"topicsBy":"site"},{"id":43,"l":[{"p":"Return wrapped result"}],"k":"blank","a":["return function.apply(x);"],"topics":["JAVA"],"topicsBy":"site"},{"id":44,"l":[{"p":"Print argument history"}],"k":"blank","a":["history.printDeque();"],"topics":["JAVA"],"topicsBy":"site"},{"s":[{"p":"After applying the spy to 5, 2, and 3, each printArgumentHistory call prints “5 2 3 ”."}]}],"topics":null},{"id":"61b-sp17-mt1/6","n":"6","t":"6. Skippify (12 pts)","b":[{"s":[{"p":"Complete IntList.skippify. Starting with n = 1, keep the current node, skip n nodes after it, then advance to the next kept node and increment n. Stop when there are no more nodes to skip."},{"c":"public void skippify() {\n  IntList p = this;\n  int n = 1;\n  while (p != null) {\n    IntList next = ⟪a⟫;\n    for (int i = 0; ⟪b⟫; i += 1) {\n      if (⟪c⟫) { break; }\n      next = ⟪d⟫;\n    }\n    ⟪e⟫\n    ⟪f⟫\n    ⟪g⟫\n  }\n}","lang":"java"}]},{"id":50,"l":[{"p":"Initialize next"}],"k":"blank","a":["p.rest"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":51,"l":[{"p":"Loop n times"}],"k":"blank","a":["i < n"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":52,"l":[{"p":"Stop at end"}],"k":"blank","a":["next == null"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":53,"l":[{"p":"Advance next"}],"k":"blank","a":["next.rest"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":54,"l":[{"p":"Unlink skipped nodes"}],"k":"blank","a":["p.rest = next;"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":55,"l":[{"p":"Advance p"}],"k":"blank","a":["p = p.rest;"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":56,"l":[{"p":"Increment skip count"}],"k":"blank","a":["n++;"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"s":[{"p":"A = (1,2,3,4,5,6,7,8,9,10) should become (1,3,6,10). B = (9,8,7,6,5,4,3,2,1) should become (9,7,4). Complete this JUnit test."},{"c":"@Test\npublic void testSkippify() {\n  IntList A = IntList.list(1,2,3,4,5,6,7,8,9,10);\n  IntList B = IntList.list(9,8,7,6,5,4,3,2,1);\n  IntList expectedA = ⟪h⟫\n  IntList expectedB = ⟪i⟫\n  ⟪j⟫\n  ⟪k⟫\n  ⟪l⟫\n  ⟪m⟫\n}","lang":"java"}]},{"id":57,"l":[{"p":"Expected A"}],"k":"blank","a":["IntList.list(1,3,6,10);"],"topics":["JAVA","TESTING"],"topicsBy":"site"},{"id":58,"l":[{"p":"Expected B"}],"k":"blank","a":["IntList.list(9,7,4);"],"topics":["JAVA","TESTING"],"topicsBy":"site"},{"id":59,"l":[{"p":"Skippify A"}],"k":"blank","a":["A.skippify();"],"topics":["JAVA","TESTING"],"topicsBy":"site"},{"id":60,"l":[{"p":"Skippify B"}],"k":"blank","a":["B.skippify();"],"topics":["JAVA","TESTING"],"topicsBy":"site"},{"id":61,"l":[{"p":"Assert A"}],"k":"blank","a":["assertEquals(expectedA, A);"],"topics":["JAVA","TESTING"],"topicsBy":"site"},{"id":62,"l":[{"p":"Assert B"}],"k":"blank","a":["assertEquals(expectedB, B);"],"topics":["JAVA","TESTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/8","n":"8","t":"8. Dedup (8 pts)","b":[{"s":[{"p":"Given a sorted linked list, destructively remove duplicates. For example, 1 → 2 → 2 → 2 → 3 becomes 1 → 2 → 3."},{"c":"public static void removeDuplicates(IntList p) {\n  if (⟪a⟫) { return; }\n  IntList current = ⟪b⟫;\n  IntList previous = ⟪c⟫;\n  while (⟪d⟫) {\n    if (current.first == ⟪e⟫) {\n      previous.rest = ⟪f⟫;\n    } else {\n      ⟪g⟫\n    }\n    ⟪h⟫\n  }\n}","lang":"java"}]},{"id":70,"l":[{"p":"Empty list"}],"k":"blank","a":["p == null"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":71,"l":[{"p":"Initialize current"}],"k":"blank","a":["p.rest"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":72,"l":[{"p":"Initialize previous"}],"k":"blank","a":["p"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":73,"l":[{"p":"Loop condition"}],"k":"blank","a":["current != null"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":74,"l":[{"p":"Compare values"}],"k":"blank","a":["previous.first"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":75,"l":[{"p":"Skip duplicate"}],"k":"blank","a":["current.rest"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":76,"l":[{"p":"Advance previous for new value"}],"k":"blank","a":["previous = current;"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"},{"id":77,"l":[{"p":"Advance current"}],"k":"blank","a":["current = current.rest;"],"topics":["JAVA","LINKED_LISTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/9","n":"9","t":"9. Interfaces (8 pts)","b":[{"s":[{"p":"Add a default Deque method remove(Item x) that removes every item equal to x and returns true if anything was removed. Do not use new. Compare with equals, handling null. Only one statement per line."},{"c":"default boolean remove(Item x) {\n  int length = ⟪a⟫;\n  for (int i = 0; i < ⟪b⟫; i++) {\n    Item first = ⟪c⟫;\n    if (⟪d⟫) {\n      ⟪e⟫\n    }\n  }\n  return ⟪f⟫;\n}","lang":"java"}]},{"id":80,"l":[{"p":"Original size"}],"k":"blank","a":["size()"],"topics":["JAVA","DEQUES"],"topicsBy":"site"},{"id":81,"l":[{"p":"Loop bound"}],"k":"blank","a":["length"],"topics":["JAVA","DEQUES"],"topicsBy":"site"},{"id":82,"l":[{"p":"Remove front"}],"k":"blank","a":["removeFirst()"],"topics":["JAVA","DEQUES"],"topicsBy":"site"},{"id":83,"l":[{"p":"Keep condition"}],"k":"blank","a":["!(first == x || (first != null && first.equals(x)))"],"topics":["JAVA","DEQUES"],"topicsBy":"site"},{"id":84,"l":[{"p":"Restore nonmatching item"}],"k":"blank","a":["addLast(first);"],"topics":["JAVA","DEQUES"],"topicsBy":"site"},{"id":85,"l":[{"p":"Return whether anything was removed"}],"k":"blank","a":["length != size()"],"topics":["JAVA","DEQUES"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt1/10","n":"10","t":"10. Grid (14 pts)","b":[{"s":[{"p":"ArrayGrid uses int[][] nums plus logical rows and cols. Its constructor allocates twice the requested capacity. resize(r,c) changes backing dimensions while preserving entries. Complete addRow and rotateColumn."},{"c":"public void addRow(int[] row) {\n  if (⟪a⟫) {\n    resize(⟪b⟫, ⟪c⟫);\n  }\n  System.arraycopy(row, 0, nums[rows], 0, cols);\n  ⟪d⟫\n}","lang":"java"}]},{"id":90,"l":[{"p":"Capacity full?"}],"k":"blank","a":["rows >= nums.length"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":91,"l":[{"p":"New row capacity"}],"k":"blank","a":["nums.length * 2"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":92,"l":[{"p":"Preserve column capacity"}],"k":"blank","a":["nums[0].length"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":93,"l":[{"p":"Increment logical rows"}],"k":"blank","a":["rows++;"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"s":[{"c":"public void rotateColumn(int c, int x) {\n  int[] copy = ⟪e⟫;\n  for (int i = 0; ⟪f⟫; i++) {\n    ⟪g⟫\n  }\n}","lang":"java"}]},{"id":94,"l":[{"p":"Copy original column"}],"k":"blank","a":["getColCopy(c)"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":95,"l":[{"p":"Visit every logical row"}],"k":"blank","a":["i < rows"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":96,"l":[{"p":"Write downward with wraparound"}],"k":"blank","a":["nums[(i + x) % rows][c] = copy[i];"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"s":[{"p":"Start with a 3×3 zero grid, add column [1,2,3], then add row [4,5,6,7]. Rotate column 2 down 1, then column 3 down 3. Complete the final printed grid."},{"c":"Before rotations (line 4):\n0 0 0 1\n0 0 0 2\n0 0 0 3\n4 5 6 7\n\nAfter rotations (line 7):\n⟪h⟫\n⟪i⟫\n⟪j⟫\n⟪k⟫","lang":"txt"}]},{"id":97,"l":[{"p":"Final row 1"}],"k":"blank","a":["0 0 6 2"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":98,"l":[{"p":"Final row 2"}],"k":"blank","a":["0 0 0 3"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":99,"l":[{"p":"Final row 3"}],"k":"blank","a":["0 0 0 7"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"},{"id":100,"l":[{"p":"Final row 4"}],"k":"blank","a":["4 5 0 1"],"topics":["JAVA","ARRAYS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp17-mt2","t":"Spring 2017 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1yWyRp7QTizspTp9dsKz5yxE6bSf9YUIi/view","sol":"https://drive.google.com/file/d/1b99XARlZxg3NMfeSAVt2yzDzwSEcASq3/view","topics":"sp17-mt2"},"p":[{"id":"61b-sp17-mt2/1","n":"1","t":"1. Traversin (11.5 pts)","b":[{"s":[{"p":"(a) For the undirected graph below, give traversals starting from vertex 9, breaking ties in numerical order. The BFS order is the order in which vertices are enqueued."},{"c":"9 — 0    9 — 1    9 — 2    9 — 6    9 — 7\n1 — 6    6 — 5    2 — 5    5 — 7","lang":"txt"}]},{"id":1,"l":[{"p":"(a) DFS preorder"}],"k":"blank","a":["9, 0, 1, 6, 5, 2, 7","9 0 1 6 5 2 7"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a) DFS postorder"}],"k":"blank","a":["0, 2, 7, 5, 6, 1, 9","0 2 7 5 6 1 9"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":3,"l":[{"p":"(a) BFS order"}],"k":"blank","a":["9, 0, 1, 2, 6, 7, 5","9 0 1 2 6 7 5"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) A min heap holds 7 unique items. For each traversal, if we print each node when we visit it, do we get the values in increasing order?"}]},{"id":4,"l":[{"p":"(b) Preorder"}],"k":"mc","o":["Never","Sometimes","Always"],"a":1,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":5,"l":[{"p":"(b) Inorder"}],"k":"mc","o":["Never","Sometimes","Always"],"a":0,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","x":"The root (the minimum) is printed after its left subtree, which isn’t empty with 7 items.","part":"b"},{"id":6,"l":[{"p":"(b) Postorder"}],"k":"mc","o":["Never","Sometimes","Always"],"a":0,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","x":"The root comes last.","part":"b"},{"id":7,"l":[{"p":"(b) Level order"}],"k":"mc","o":["Never","Sometimes","Always"],"a":1,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":8,"l":[{"p":"(c) Is there a tree with 5 unique values whose preorder traversal is the reverse of its inorder traversal?"}],"k":"mc","o":["Yes: any tree where every node has only a left child","Yes: any tree where every node has only a right child","Yes: a complete tree","Impossible"],"a":0,"topics":["TREE_TRAVERSALS"],"topicsBy":"site","x":"With only left children, preorder goes top to bottom and inorder bottom to top.","part":"c"}],"topics":null},{"id":"61b-sp17-mt2/2","n":"2","t":"2. An Operational Understanding (15.2 pts)","b":[{"s":[{"p":"(a) In the tree below, Greek letters are unique numerical values. Select all values that might match each description. For BSTs, left items are smaller. When treating the tree as a graph, assume nothing about the order of adjacency lists."},{"c":"         α\n       /   \\\n      β     π\n     / \\   / \\\n    δ   ε θ   ω","lang":"txt"}]},{"id":9,"l":[{"p":"MinHeap, largest item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[3,4,5,6],"topics":["HEAPS"],"topicsBy":"site"},{"id":10,"l":[{"p":"MinHeap, smallest item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[0],"topics":["HEAPS"],"topicsBy":"site"},{"id":11,"l":[{"p":"BST, largest item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[6],"topics":["BSTS"],"topicsBy":"site"},{"id":12,"l":[{"p":"BST, smallest item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[3],"topics":["BSTS"],"topicsBy":"site"},{"id":13,"l":[{"p":"MinHeap, median item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[1,2,3,4,5,6],"topics":["HEAPS"],"topicsBy":"site","x":"Only the root is ruled out; the median has 3 smaller items, which β’s or π’s side can hold."},{"id":14,"l":[{"p":"BST, median item"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[0],"topics":["BSTS"],"topicsBy":"site"},{"id":15,"l":[{"p":"MinHeap, new root after deleteMin"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[1,2],"topics":["HEAPS"],"topicsBy":"site","x":"The smaller of the root’s children rises to the top."},{"id":16,"l":[{"p":"BST, new root after Hibbard deletion of α"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[4,5],"topics":["BSTS"],"topicsBy":"site","x":"Its predecessor ε or its successor θ."},{"id":17,"l":[{"p":"MinHeap, root after inserting a new item φ"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω","φ"],"a":[0,7],"topics":["HEAPS"],"topicsBy":"site"},{"id":18,"l":[{"p":"BST, root after inserting a new item φ"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω","φ"],"a":[0],"topics":["BSTS"],"topicsBy":"site"},{"id":19,"l":[{"p":"Last item dequeued running BFS from ω"}],"k":"sata","o":["α","β","π","δ","ε","θ","ω"],"a":[3,4],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","x":"δ and ε are the farthest from ω (4 edges), in either order."},{"s":[{"p":"(b) A hash map (as in lecture) maps a year to a famous person born that year. A year’s hash code is the sum of its first and last digits, e.g. hashCode(1569) = 10. There are 4 buckets, each a list, new items go at the end, and there is no resizing. We put, in order: 1569 / Jahangir, 155 / Cao, 1107 / Dandolo, 1737 / Paine, 713 / Stephen, 1048 / Khayyam, 1737 / Hancock."},{"p":"Write each bucket’s entries in order as year name, separated by commas, e.g. 1569 Jahangir, 155 Cao; write [] if empty."}]},{"id":20,"l":[{"p":"(b) Bucket 0"}],"k":"blank","a":["1107 Dandolo, 1737 Hancock","1107, Dandolo, 1737, Hancock"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":21,"l":[{"p":"(b) Bucket 1"}],"k":"blank","a":["1048 Khayyam","1048, Khayyam"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":22,"l":[{"p":"(b) Bucket 2"}],"k":"blank","a":["1569 Jahangir, 155 Cao, 713 Stephen","1569, Jahangir, 155, Cao, 713, Stephen"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":23,"l":[{"p":"(b) Bucket 3"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"topicsBy":"site","x":"Hash codes 10, 6, 8, 8, 10, 9 → buckets 2, 2, 0, 0, 2, 1. The second 1737 replaces Paine with Hancock.","part":"b"}],"topics":null},{"id":"61b-sp17-mt2/3","n":"3","t":"3. Weighted Quick Union (12 pts)","b":[{"s":[{"p":"(a) Could connect(a, b) calls on a weighted quick union (all items starting disconnected) produce each forest? In a tie, the left argument’s root goes below the right argument’s root. Trees are written root(children)."},{"c":"Forest 1:  0   4   5(3(2))   1   6\nForest 2:  1   0(4, 2, 6, 3(5))","lang":"txt"}]},{"id":24,"l":[{"p":"(a) Forest 1"}],"k":"mc","o":["Possible","Impossible"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"A WQU tree of height 2 needs at least 4 items; 5’s tree has 3.","part":"a"},{"id":25,"l":[{"p":"(a) Forest 2"}],"k":"mc","o":["Possible","Impossible"],"a":0,"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"connect(2, 0), connect(4, 0), connect(5, 3), connect(3, 0), connect(6, 0).","part":"a"},{"id":26,"l":[{"p":"(b) We add undo(a, b), which undoes an earlier connect(a, b) (and does nothing if there was none). For which implementations is undo impossible without adding instance variables?"}],"k":"sata","o":["Quick Union","Quick Find","Weighted Quick Union","WQU with Path Compression"],"a":[0,1,2,3],"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"None of them remembers which connect calls made the current structure.","part":"b"},{"s":[{"p":"(c) Suppose we solve disjoint sets with a graph: an adjacency list with no duplicates, connect uses addEdge, and isConnected uses DFS with a marked array that stops early once a connection is found. N is the number of nodes and M the total number of connect and isConnected calls so far."}]},{"id":27,"l":[{"p":"(c) Worst-case runtime of a single connect(a, b)"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(log M)","Θ(N)","Θ(M)","Θ(N + M)","Θ(NM)"],"a":3,"topics":["DISJOINT_SETS","GRAPH_REPRESENTATIONS"],"topicsBy":"site","also":[4,5],"x":"Checking for a duplicate edge scans an adjacency list. Staff accepted Θ(N), Θ(M) and Θ(N + M), since “worst case” was ambiguous.","part":"c"},{"id":28,"l":[{"p":"(c) Worst-case runtime of a single isConnected(a, b)"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(log M)","Θ(N)","Θ(M)","Θ(N + M)","Θ(NM)"],"a":5,"topics":["DISJOINT_SETS","GRAPH_TRAVERSALS"],"topicsBy":"site","also":[3,4],"x":"DFS is Θ(V + E); staff accepted Θ(N), Θ(M) and Θ(N + M).","part":"c"}],"topics":null},{"id":"61b-sp17-mt2/4","n":"4","t":"4. Asymptotics (20 pts)","b":[{"s":[{"p":"(a) Fill in each loop’s update so the function has the desired runtime (no commas; write impossible if it can’t be done)."},{"c":"public static void f1(int N) { // desired runtime: Θ(N)\n    for (int i = 1; i < N; ⟪a⟫) { System.out.println(\"hi\"); }\n}\n\npublic static void f2(int N) { // desired runtime Θ(log N)\n    for (int i = 1; i < N; ⟪b⟫) { System.out.println(\"hi\"); }\n}\n\npublic static void f3(int N) { // desired runtime Θ(1)\n    for (int i = 1; i < N; ⟪c⟫) { System.out.println(\"hi\"); }\n}","lang":"java","f":{"a":"i += 1","b":"i *= 2","c":"i += N"}}]},{"id":29,"l":[{"p":"(a) f1"}],"k":"blank","a":["i += 1","i++","i = i + 1","i += 2"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":30,"l":[{"p":"(a) f2"}],"k":"blank","a":["i *= 2","i = i * 2","i *= 3"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":31,"l":[{"p":"(a) f3"}],"k":"blank","a":["i += N","i = N","i *= N","i = i + N"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) Give the runtime of each function, in Θ or O notation as requested."},{"c":"public static void f4(int N) {\n    if (N == 0) { return; }\n    f4(N / 2);\n    f4(N / 2);\n    f4(N / 2);\n    f4(N / 2);\n    g(N); // runs in Θ(N²) time\n}\n\npublic static void f5(int N, int M) {\n    if (N < 10) { return; }\n    for (int i = 0; i <= N % 10; i++) {\n        f5(N / 10, M / 10);\n        System.out.println(M);\n    }\n}","lang":"java"}]},{"id":32,"l":[{"p":"(b) f4, in Θ notation"}],"k":"mc","o":["Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N⁴)"],"a":1,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"Each level does N² total work (4× the calls, each a quarter as much), for log N levels.","part":"b"},{"id":33,"l":[{"p":"(b) f5, as tight an O bound as possible"}],"k":"mc","o":["O(log N)","O(N)","O(N log N)","O(N^NM!)"],"a":1,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"Each call makes at most 10 calls on N/10, so the call tree has at most about N nodes.","part":"b"},{"s":[{"p":"(d) Timing experiments for assignPupJobs(List<Puppy> puppies, List<Job> jobs), where N is the number of puppies and M the number of jobs:"},{"c":"N      M     R(N, M)\n100    10    0.05 sec\n500    10    0.08 sec\n1000   10    0.13 sec\n100    50    3.1 sec\n500    50    15.5 sec\n1000   50    30.5 sec\n100    100   24.9 sec\n500    100   125.1 sec\n1000   100   251.9 sec","lang":"txt"},{"p":"Assume the runtime has the form ~a·N^b1·M^b2, with a ≈ 251.9 / (1000^b1 × 100^b2). Round to integer exponents."}]},{"id":34,"l":[{"p":"(d) b1"}],"k":"blank","a":["1"],"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"d"},{"id":35,"l":[{"p":"(d) b2"}],"k":"blank","a":["3"],"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Doubling N (500 → 1000) doubles the time; doubling M (50 → 100) multiplies it by about 8.","part":"d"}],"topics":null},{"id":"61b-sp17-mt2/5","n":"5","t":"5. Regex (5.25 pts)","b":[{"s":[{"p":"For each regular expression, select every string it matches (the whole string must match)."}]},{"id":36,"l":[{"p":"ulg"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[0],"topics":["REGEX"],"topicsBy":"site"},{"id":37,"l":[{"p":"(ulgo|grigo)meth"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[1,2],"topics":["REGEX"],"topicsBy":"site"},{"id":38,"l":[{"p":"ulgo|grigometh"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[2,3],"topics":["REGEX"],"topicsBy":"site","x":"| has the lowest precedence: it’s ulgo, or grigometh."},{"id":39,"l":[{"p":"((ulgo)|(grigo))meth"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[1,2],"topics":["REGEX"],"topicsBy":"site"},{"id":40,"l":[{"p":"(ulgo|grigo)*meth"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[1,2,5],"topics":["REGEX"],"topicsBy":"site","x":"* allows zero repetitions, so meth alone matches."},{"id":41,"l":[{"p":"(u|l|g)*ometh"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[1,6],"topics":["REGEX"],"topicsBy":"site"},{"id":42,"l":[{"p":"(ulg)*ometh"}],"k":"sata","o":["ulg","ulgometh","grigometh","ulgo","grigo","meth","ometh"],"a":[1,6],"topics":["REGEX"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp17-mt2/6","n":"6","t":"6. Bipartite Graphs (12.5 pts)","b":[{"s":[{"p":"(a) A graph is bipartite if every vertex can be colored blue or green so that no edge joins two vertices of the same color."},{"c":"Graph 1:  0—1  1—2  0—3  1—4  2—5  3—4  4—5  3—6  5—6\nGraph 2:  0—1  1—2  0—3  1—4  3—4  2—5  2—6  4—5  5—6","lang":"txt"}]},{"id":43,"l":[{"p":"(a) Graph 1"}],"k":"mc","o":["Bipartite","Not bipartite"],"a":0,"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":44,"l":[{"p":"(a) Graph 2"}],"k":"mc","o":["Bipartite","Not bipartite"],"a":1,"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","x":"2, 5 and 6 form a triangle, an odd cycle.","part":"a"},{"s":[{"p":"(b) Using the undirected Graph API (Graph(int V), addEdge(int v, int w), Iterable<Integer> adj(int v), V(), E()), fill in twocolor so that it puts the blue vertices in blue, or throws an exception if no coloring exists."},{"c":"HashSet<Integer> blue = new HashSet<Integer>();\nHashSet<Integer> green = new HashSet<Integer>();\ntwocolor(G, 0, blue, green);\nSystem.out.println(\"Blue vertices are: \" + blue.toString());\n\npublic static void twocolor(Graph G, int v, Set<Integer> a, Set<Integer> b) {\n    ⟪a⟫;\n    for (⟪b⟫) {\n        if (⟪c⟫) {\n            throw new IllegalArgumentException(\"graph is not bipartite\"); }\n        if (⟪d⟫) {\n            ⟪e⟫;\n        }\n    }\n}","lang":"java","f":{"a":"a.add(v)","b":"int u : G.adj(v)","c":"a.contains(u)","d":"!b.contains(u)","e":"twocolor(G, u, b, a)"}}]},{"id":45,"l":[{"p":"(b) First line"}],"k":"blank","a":["a.add(v)"],"topics":["GRAPH_TRAVERSALS","RECURSION"],"topicsBy":"site","part":"b"},{"id":46,"l":[{"p":"(b) The loop header"}],"k":"blank","a":["int u : G.adj(v)","Integer u : G.adj(v)"],"topics":["GRAPH_TRAVERSALS","RECURSION"],"topicsBy":"site","part":"b"},{"id":47,"l":[{"p":"(b) Throw if (____)"}],"k":"blank","a":["a.contains(u)"],"topics":["GRAPH_TRAVERSALS","RECURSION"],"topicsBy":"site","part":"b"},{"id":48,"l":[{"p":"(b) Recurse if (____)"}],"k":"blank","a":["!b.contains(u)"],"topics":["GRAPH_TRAVERSALS","RECURSION"],"topicsBy":"site","part":"b"},{"id":49,"l":[{"p":"(b) The recursive call"}],"k":"blank","a":["twocolor(G, u, b, a)"],"topics":["GRAPH_TRAVERSALS","RECURSION"],"topicsBy":"site","x":"Color v with a’s color; a neighbor already in a means two adjacent vertices share a color. Uncolored neighbors get the other color: swap a and b when recursing.","part":"b"}],"topics":null},{"id":"61b-sp17-mt2/7","n":"7","t":"7. Trees and Hashing (18 pts)","b":[{"s":[{"p":"(a) An LLRBBucketHashSet stores each hash table bucket as a left-leaning red-black tree. It doubles its buckets when the load factor exceeds 2 and never shrinks; hashCode is constant time. Don’t assume the hash codes spread items out. With N items and M buckets, give each single operation’s runtime."}]},{"id":50,"l":[{"p":"(a) put: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":3,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","x":"A put can trigger a resize, which reinserts N items into LLRBs that may all be the same bucket.","part":"a"},{"id":51,"l":[{"p":"(a) containsKey: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":1,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"id":52,"l":[{"p":"(a) remove: worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":1,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","x":"All three operations are Θ(1) in the best case.","part":"a"},{"id":53,"l":[{"p":"(b) An LLRBBucketNoResizeHashSet is the same but never adds buckets. What is the worst case of put, containsKey and remove?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":1,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","part":"b"},{"id":54,"l":[{"p":"(c) Starting from an empty LLRBBucketHashSet, after Q insertions with nicely spread hash codes, what is the amortized time per put?"}],"k":"mc","o":["O(1)","O(log Q)","O(log (Q / M))","O(Q)"],"a":0,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":55,"l":[{"p":"(d) Same question for an LLRBBucketNoResizeHashSet."}],"k":"mc","o":["O(1)","O(log Q)","O(log (Q / M))","O(Q)"],"a":2,"topics":["HASHING","RED_BLACK_TREES"],"topicsBy":"site","x":"Each of the M buckets holds about Q / M items.","part":"d"},{"id":56,"l":[{"p":"(f) To implement LLRBBucketHashSet using the textbook’s RedBlackBST.java, which approach is better?"}],"k":"mc","o":["Extension (extending RedBlackBST)","Delegation (instance variables that include a RedBlackBST)","Either is appropriate"],"a":1,"topics":["HASHING","INHERITANCE"],"topicsBy":"site","x":"A hash set has many trees (one per bucket); it isn’t itself a tree.","part":"f"}],"topics":null},{"id":"61b-sp17-mt2/8","n":"8","t":"8. Xelha (25 pts)","b":[{"s":[{"p":"A XelhaTree for a list of numbers X has the min-heap property (every value ≤ its children), and its in-order traversal visits the values in the list’s order. It need not be complete, and may contain duplicates. For example, for [9, 3, 7, 15, 1, 8, 12] one XelhaTree is 1(3(9, 7(-, 15)), 8(-, 12)). Trees are written value(left, right)."}]},{"id":57,"l":[{"p":"(a) Which are valid XelhaTrees for their sequences?"}],"k":"sata","o":["[9, 3, 7, 15, 1, 8, 12]: 1(3(9, 7(-, 15)), 8(-, 12))","[4, 3, 6, 5, 8, 7, 9]: 3(4, 5(6, 7(8, 9)))","[1, 2, 2, 2]: 1(-, 2(-, 2(-, 2)))"],"a":[0,1,2],"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":58,"l":[{"p":"(b) Which is a valid XelhaTree for [8, 3, 9, 1]?"}],"k":"mc","o":["1(3(8, 9), -)","1(-, 3(8, 9))","3(8, 1(9, -))","1(8, 3(-, 9))"],"a":0,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":59,"l":[{"p":"(c) Which is a valid XelhaTree for [13, 7, 2, 1, 5, 16, 8, 9]?"}],"k":"mc","o":["1(2(7(13, -), -), 5(-, 8(16, 9)))","1(2(7, 13), 5(8(16, -), 9))","1(7(13, 2), 5(-, 8(16, 9)))","2(7(13, -), 1(-, 5(-, 8(16, 9))))"],"a":0,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","x":"The minimum (1) must be the root, with everything before it on the left and after it on the right; repeat within each side.","part":"c"},{"id":60,"l":[{"p":"(d) For full credit, an algorithm for building a XelhaTree had to run faster than Θ(N²) in the worst case. Which works in Θ(N)?"}],"k":"mc","o":["Scan the list once, keeping the path of nodes down the tree’s right side on a stack: pop while the new value is smaller than the top, make the last popped node the new node’s left child, and attach the new node as the right child of what remains on top (or as the root).","Find the minimum, make it the root, and recurse on the parts of the list to its left and right.","Sort the list, then insert each value into a BST in sorted order.","Insert every value into a min-heap, then read the heap’s array in order."],"a":0,"topics":["HEAPS","TREE_TRAVERSALS"],"topicsBy":"site","x":"Each node is pushed and popped at most once, so it’s linear. The recursive-minimum approach is correct but Θ(N²) in the worst case (it got partial credit).","part":"d"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp18-final","t":"Spring 2018 Final","src":{"exam":"https://drive.google.com/file/d/1_hrx4pAevtEVVxtNUoMZ3uZB32D1MOUC/view","sol":"https://drive.google.com/file/d/1lmjGHJy3bAfxKOMtTt53Y4S_3RzjAmh9/view","topics":"sp18-final"},"p":[{"id":"61b-sp18-final/1","n":"1","t":"1. Graph Basics (44 pts)","b":[{"s":[{"p":"Directed graph edges: 61A→61B, 61A→61C; 61B→188, 61B→170, 61B→169; 61C→169; 70→188, 70→170. Starting at 61A, perform DFS/BFS with alphanumeric tie-breaking. Neither traversal restarts after exhausting reachable vertices."}]},{"id":1,"l":[{"p":"DFS preorder, space-separated"}],"k":"blank","a":["61A 61B 169 170 188 61C"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":2,"l":[{"p":"DFS postorder, space-separated"}],"k":"blank","a":["169 170 188 61B 61C 61A"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":3,"l":[{"p":"BFS order, space-separated"}],"k":"blank","a":["61A 61B 61C 169 170 188"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":4,"l":[{"p":"Is this a valid topological order: 70, 61A, 61C, 61B, 188, 170, 169?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"For the weighted undirected graph, label vertices by their symbols: O is the circled top node, I is infinity, Tri is the triangle, Plus is +, Dia is the four-diamond symbol, Hour is the hourglass symbol, Zig is the zigzag, and Clov is the clover. Edges: O–I(1), O–Tri(0), I–Plus(3), I–Dia(8), I–Hour(9), Tri–Hour(−1000), Tri–Clov(2), Plus–Zig(4), Dia–Zig(5), Dia–Hour(7), Zig–Hour(6), Zig–Clov(10), Hour–Clov(11). Prim starts at O. Report edge weights in order."}]},{"id":5,"l":[{"p":"MST edge weights, Prim order"}],"k":"blank","a":["0 -1000 1 2 3 4 5"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":6,"l":[{"p":"MST edge weights, Kruskal order"}],"k":"blank","a":["-1000 0 1 2 3 4 5"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":7,"l":[{"p":"If 1000 is added to every edge weight, do the MST edges change?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"For the next graph, edges are AE=2, AB=1, EB=8, EC=1, CB=5, CD=5, BD=0, and DE=x. The bold candidate tree is AE, AB, EC, CD, BD."}]},{"id":8,"l":[{"p":"Can the marked edges be an MST, and what x values work?"}],"k":"mc","o":["Never","Yes when x ≥ 2","Yes when x ≤ 2","Yes for every x"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":9,"l":[{"p":"Can the marked edges be an SPT rooted at B, and what x values work?"}],"k":"mc","o":["Never","Yes when x ≥ 3","Yes when x ≤ 3","Yes for every x"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/2","n":"2","t":"2. Sorting (33 pts)","b":[{"s":[{"p":"An insertion sort is partway through sorting [@, #, $, %, &, *], at state [&, #, $, @, %, *]. For each statement select true, false, or not enough information."}]},{"id":10,"l":[{"p":"& is the smallest element"}],"k":"mc","o":["True","False","Not enough information"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":11,"l":[{"p":"* is the largest element"}],"k":"mc","o":["True","False","Not enough information"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":12,"l":[{"p":"& < #"}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"id":13,"l":[{"p":"% < @"}],"k":"mc","o":["True","False","Not enough information"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"s":[{"c":"int[] a = {6,1,4,7,3,2,5,8}; // pivot is 6; Tony Hoare partition","lang":"java"}]},{"id":14,"l":[{"p":"Array immediately after first swap"}],"k":"blank","a":["6 1 4 5 3 2 7 8"],"topics":["SORTING"],"topicsBy":"site"},{"id":15,"l":[{"p":"Array after the entire partition"}],"k":"blank","a":["2 1 4 5 3 6 7 8"],"topics":["SORTING"],"topicsBy":"site"},{"id":16,"l":[{"p":"Given x < y and x is right of y, what can happen to inversion count when swapping them?"}],"k":"sata","o":["Decrease","Increase","Stay the same"],"a":[0],"topics":["SORTING"],"topicsBy":"site"},{"id":17,"l":[{"p":"What can happen to inversion count during bottom-up min-heapification?"}],"k":"sata","o":["Decrease","Increase","Stay the same"],"a":[0,2],"topics":["SORTING","HEAPS"],"topicsBy":"site"},{"id":18,"l":[{"p":"Is HashSort constant-time when lookup uses HashMap<int[],int[]> and the map has an entry for every possible input array?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["HASHING","SORTING"],"topicsBy":"site"},{"id":19,"l":[{"p":"Why not?"}],"k":"blank","a":["Computing the input array hash code takes Θ(N) time"],"topics":["HASHING","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/3","n":"3","t":"3. Back to the First Half of the Semester (46 pts)","b":[{"s":[{"p":"Implement append non-destructively: return a new list containing x followed by y."},{"c":"static IntList append(IntList x, IntList y) {\n  if (⟪a⟫) return ⟪b⟫;\n  return ⟪c⟫;\n}","lang":"java"}]},{"id":30,"l":[{"p":"Base case"}],"k":"blank","a":["x == null"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":31,"l":[{"p":"Return for empty x"}],"k":"blank","a":["y"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"id":32,"l":[{"p":"Copy first node and recurse"}],"k":"blank","a":["new IntList(x.first, append(x.rest, y))"],"topics":["LINKED_LISTS"],"topicsBy":"site"},{"s":[{"p":"Complete an iterator for IntList, where nodes have int first and IntList rest."},{"c":"public Iterator<Integer> iterator() { return ⟪d⟫; }\npublic static class IntListIterator implements Iterator<Integer> {\n  private IntList p;\n  public IntListIterator(⟪e⟫) { ⟪f⟫ }\n  public boolean hasNext() { return ⟪g⟫; }\n  public Integer next() {\n    int rval = ⟪h⟫;\n    ⟪i⟫\n    return ⟪j⟫;\n  }\n}","lang":"java"}]},{"id":33,"l":[{"p":"Construct iterator"}],"k":"blank","a":["new IntListIterator(this)"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":34,"l":[{"p":"Constructor argument type"}],"k":"blank","a":["IntList il"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":35,"l":[{"p":"Initialize cursor"}],"k":"blank","a":["p = il"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":36,"l":[{"p":"hasNext condition"}],"k":"blank","a":["p != null"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":37,"l":[{"p":"Read current value"}],"k":"blank","a":["p.first"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":38,"l":[{"p":"Advance cursor"}],"k":"blank","a":["p = p.rest"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"id":39,"l":[{"p":"Return saved value"}],"k":"blank","a":["rval"],"topics":["LINKED_LISTS","ITERATORS"],"topicsBy":"site"},{"s":[{"p":"If IntListIterator is made private: determine compile/runtime outcome for each context."}]},{"id":45,"l":[{"p":"IntList.java"}],"k":"mc","o":["Fails to compile","Compiles"],"a":1,"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":46,"l":[{"p":"One.java enhanced for loop"}],"k":"mc","o":["Fails to compile","Compiles but works incorrectly","Compiles and works correctly"],"a":2,"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":47,"l":[{"p":"Two.java Iterator<Integer> it = L.iterator()"}],"k":"mc","o":["Fails to compile","Compiles but works incorrectly","Compiles and works correctly"],"a":2,"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":48,"l":[{"p":"Three.java explicitly names IntListIterator"}],"k":"mc","o":["Fails to compile","Compiles but works incorrectly","Compiles and works correctly"],"a":0,"topics":["ITERATORS","JAVA"],"topicsBy":"site"},{"id":49,"l":[{"p":"Expected practical runtime of an int[]-backed IntArrayList versus ArrayList<Integer>?"}],"k":"mc","o":["Better","No measurable difference","Worse"],"a":0,"topics":["ARRAYS","JAVA"],"topicsBy":"site"},{"id":50,"l":[{"p":"Runtime reason"}],"k":"blank","a":["Avoids autoboxing and unboxing"],"topics":["ARRAYS","JAVA"],"topicsBy":"site"},{"id":51,"l":[{"p":"Expected space usage of int[]-backed IntArrayList?"}],"k":"mc","o":["Better","No measurable difference","Worse"],"a":0,"topics":["ARRAYS","JAVA"],"topicsBy":"site"},{"id":52,"l":[{"p":"Space reason"}],"k":"blank","a":["Integer objects use more space than primitive ints"],"topics":["ARRAYS","JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/5","n":"5","t":"5. Hash Codes (13 pts)","b":[{"s":[{"p":"SneakySnake.equals compares UUIDString and seed. Class fields: constant String UUIDString, int seed, and Random random initialized from seed in the constructor. Classify each hashCode body as valid, valid but slow, or invalid."},{"c":"return UUIDString;\nreturn UUIDString.hashCode();\nreturn seed;\nreturn random.nextInt();\nRandom hashcodeRand = new Random(10);\nreturn hashcodeRand.nextInt();","lang":"java"}]},{"id":60,"l":[{"p":"return UUIDString;"}],"k":"mc","o":["Valid","Valid but slow","Invalid"],"a":2,"topics":["HASHING","JAVA"],"topicsBy":"site"},{"id":61,"l":[{"p":"return UUIDString.hashCode();"}],"k":"mc","o":["Valid","Valid but slow","Invalid"],"a":1,"topics":["HASHING","JAVA"],"topicsBy":"site"},{"id":62,"l":[{"p":"return seed;"}],"k":"mc","o":["Valid","Valid but slow","Invalid"],"a":0,"topics":["HASHING","JAVA"],"topicsBy":"site"},{"id":63,"l":[{"p":"return random.nextInt();"}],"k":"mc","o":["Valid","Valid but slow","Invalid"],"a":2,"topics":["HASHING","JAVA"],"topicsBy":"site"},{"id":64,"l":[{"p":"new Random(10); return hashcodeRand.nextInt();"}],"k":"mc","o":["Valid","Valid but slow","Invalid"],"a":1,"topics":["HASHING","JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/6","n":"6","t":"6. More Graphs! (37 pts)","b":[{"s":[{"p":"Classify each proposition as Always True, Sometimes True, or Always False."}]},{"id":70,"l":[{"p":"A* finds a correct shortest path, if one exists."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":71,"l":[{"p":"BFS finds a correct shortest path in an unweighted graph."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":72,"l":[{"p":"An MST contains the largest edge in the graph."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":73,"l":[{"p":"The last vertex in a valid topological order has no outgoing edges."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":74,"l":[{"p":"The middle vertex in a topological order of ≥3 vertices has no incoming edge."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":75,"l":[{"p":"With all positive edges except negative edges leaving the start, Dijkstra finds the correct SPT."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":76,"l":[{"p":"Dijkstra variant DAV1 stops when target is enqueued; on nonnegative graphs this gives a correct shortest path."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":77,"l":[{"p":"Dijkstra variant DAV2 stops when target is dequeued; on nonnegative graphs this gives a correct shortest path."}],"k":"mc","o":["Always True","Sometimes True","Always False"],"a":0,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"For nonnegative weighted graphs, use this triangle: vertices A, B, C; all three undirected edges have weight 1."}]},{"id":78,"l":[{"p":"Second-shortest path from A to B"}],"k":"blank","a":["A-C-B"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":79,"l":[{"p":"Second-shortest path from A to C"}],"k":"blank","a":["A-B-C"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":80,"l":[{"p":"Do second-shortest paths necessarily form a tree?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/7","n":"7","t":"7. Can You Do That? (32 pts)","b":[{"id":90,"l":[{"p":"Does calling insertion-sort travel(i) in reverse order still sort?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":91,"l":[{"p":"Counterexample input"}],"k":"blank","a":["3 0 1 2"],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"Pruskal: for each vertex choose its cheapest incident edge; return the set of chosen edges. Connected undirected graph, unique weights."}]},{"id":92,"l":[{"p":"Does Pruskal always return the MST?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"Use this connected graph: A–B has weight 1, B–C has weight 4, and C–D has weight 2."}]},{"id":93,"l":[{"p":"Can a heap priority queue report the true minimum after arbitrary stored keys mutate, if it reheapifies before min and removeMin?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["HEAPS"],"topicsBy":"site"},{"id":94,"l":[{"p":"How can MutationSafeHeapMinPQ ensure correctness?"}],"k":"blank","a":["Reheapify the items at the start of every min() and removeMin() call"],"topics":["HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/8","n":"8","t":"8. Weird Sorts (24 pts)","b":[{"s":[{"p":"PartitionHybridSort partitions around the leftmost item, then runs the selected subsort independently on each subarray. Give worst-case Θ runtime."}]},{"id":100,"l":[{"p":"PartitionHybridSort with InsertionSort"}],"k":"blank","a":["N^2"],"topics":["SORTING"],"topicsBy":"site"},{"id":101,"l":[{"p":"PartitionHybridSort with Mergesort"}],"k":"blank","a":["N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":102,"l":[{"p":"PartitionHybridSort with LSDSort"}],"k":"blank","a":["N"],"topics":["SORTING"],"topicsBy":"site"},{"id":103,"l":[{"p":"PartitionHybridSort with PartitionHybridSort recursively"}],"k":"blank","a":["N^2"],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"LSDMergesort uses stable mergesort to sort on each of W digits. LSDQuicksort instead uses shuffled Hoare quicksort on each digit."}]},{"id":104,"l":[{"p":"LSDMergesort worst-case runtime"}],"k":"blank","a":["W N log N"],"topics":["SORTING"],"topicsBy":"site"},{"id":105,"l":[{"p":"Does LSDMergesort always sort correctly?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"id":106,"l":[{"p":"Why does LSDMergesort work?"}],"k":"blank","a":["Mergesort is stable"],"topics":["SORTING"],"topicsBy":"site"},{"id":107,"l":[{"p":"LSDQuicksort worst-case runtime"}],"k":"blank","a":["W N^2"],"topics":["SORTING"],"topicsBy":"site"},{"id":108,"l":[{"p":"Does LSDQuicksort always sort correctly?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":109,"l":[{"p":"Why can LSDQuicksort fail?"}],"k":"blank","a":["Quicksort is unstable"],"topics":["SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/9","n":"9","t":"9. Dijkstra Runtime (24 pts)","b":[{"s":[{"p":"Give operation runtimes and total Dijkstra runtime. Counts are V add calls, O(E) changePriority calls, O(V) removeMin calls. Keep the total expression in terms of E and V without simplifying."}]},{"id":120,"l":[{"p":"Trinary heap add"}],"k":"blank","a":["log V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":121,"l":[{"p":"Trinary heap changePriority"}],"k":"blank","a":["log V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":122,"l":[{"p":"Trinary heap removeMin"}],"k":"blank","a":["log V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":123,"l":[{"p":"Trinary heap total"}],"k":"blank","a":["E log V + V log V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":124,"l":[{"p":"Unordered array add"}],"k":"blank","a":["V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":125,"l":[{"p":"Unordered array changePriority"}],"k":"blank","a":["1"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":126,"l":[{"p":"Unordered array removeMin"}],"k":"blank","a":["V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":127,"l":[{"p":"Unordered array total"}],"k":"blank","a":["V^2 + E"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":128,"l":[{"p":"Ordered linked list add"}],"k":"blank","a":["V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":129,"l":[{"p":"Ordered linked list changePriority"}],"k":"blank","a":["V"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":130,"l":[{"p":"Ordered linked list removeMin"}],"k":"blank","a":["1"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"},{"id":131,"l":[{"p":"Ordered linked list total"}],"k":"blank","a":["V^2 + EV"],"topics":["GRAPH_REPRESENTATIONS","HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/10","n":"10","t":"10. By the Numbers (40 pts)","b":[{"s":[{"p":"Give exact best and worst numbers of compareTo calls."}]},{"id":140,"l":[{"p":"Solving puppy, cat, dog for N=3: best"}],"k":"blank","a":["2"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":141,"l":[{"p":"Solving puppy, cat, dog for N=3: worst"}],"k":"blank","a":["3"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":142,"l":[{"p":"Insertion sorting 5 numbers: best"}],"k":"blank","a":["4"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":143,"l":[{"p":"Insertion sorting 5 numbers: worst"}],"k":"blank","a":["10"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":144,"l":[{"p":"Inserting 5 numbers into initially empty BST: best"}],"k":"blank","a":["6"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":145,"l":[{"p":"Inserting 5 numbers into initially empty BST: worst"}],"k":"blank","a":["10"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":146,"l":[{"p":"Finding successor of BST root with 7 items: best"}],"k":"blank","a":["0"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":147,"l":[{"p":"Finding successor of BST root with 7 items: worst"}],"k":"blank","a":["0"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":148,"l":[{"p":"Merging sorted arrays sizes 20 and 30: best"}],"k":"blank","a":["20"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":149,"l":[{"p":"Merging sorted arrays sizes 20 and 30: worst"}],"k":"blank","a":["49"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":150,"l":[{"p":"Bottom-up heapify 7 items: best"}],"k":"blank","a":["6"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":151,"l":[{"p":"Bottom-up heapify 7 items: worst"}],"k":"blank","a":["8"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":152,"l":[{"p":"Binary search ordered array of 7 for a key: best"}],"k":"blank","a":["1"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":153,"l":[{"p":"Binary search ordered array of 7 for a key: worst"}],"k":"blank","a":["3"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":154,"l":[{"p":"Counting sort 52 cards by suit: best"}],"k":"blank","a":["0"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":155,"l":[{"p":"Counting sort 52 cards by suit: worst"}],"k":"blank","a":["0"],"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/11","n":"11","t":"11. Sheep Herding (55 pts)","b":[{"s":[{"p":"Must take sheep at position 0, then repeatedly advance between A and B positions inclusive. Maximize total value. Assume B≥A>0."}]},{"id":160,"l":[{"p":"For values {5,2,−3,2,2,10}, A=2, B=3, maximum total"}],"k":"blank","a":["17"],"topics":["RECURSION"],"topicsBy":"site"},{"s":[{"c":"static int maxSheepNaiveHelper(int[] values, int A, int B, int c) {\n  if (⟪a⟫) return ⟪b⟫;\n  int best = ⟪c⟫;\n  for (int s=⟪d⟫; ⟪e⟫; s++) {\n    int val = values[c] + maxSheepNaiveHelper(values,A,B,⟪f⟫);\n    best = Math.max(⟪g⟫, ⟪h⟫);\n  }\n  return best;\n}","lang":"java"}]},{"id":161,"l":[{"p":"Past end"}],"k":"blank","a":["c >= values.length"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":162,"l":[{"p":"Empty suffix"}],"k":"blank","a":["0"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":163,"l":[{"p":"Initialize best"}],"k":"blank","a":["Integer.MIN_VALUE"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":164,"l":[{"p":"Start step"}],"k":"blank","a":["A"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":165,"l":[{"p":"Loop through B"}],"k":"blank","a":["s <= B"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":166,"l":[{"p":"Next index"}],"k":"blank","a":["c + s"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":167,"l":[{"p":"First max argument"}],"k":"blank","a":["best"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"id":168,"l":[{"p":"Second max argument"}],"k":"blank","a":["val"],"topics":["RECURSION","RECURSION"],"topicsBy":"site"},{"s":[{"p":"For values [2,1,−3,6,8,−2,−1,4], define Q(i) as the best achievable total starting at position i. Fill Q from left to right."}]},{"id":169,"l":[{"p":"Q values in index order"}],"k":"blank","a":["11 13 9 8 12 2 -1 4"],"topics":["RECURSION"],"topicsBy":"site"},{"id":170,"l":[{"p":"Dynamic programming runtime in N,A,B"}],"k":"blank","a":["N(B - A)"],"topics":["RECURSION","ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/12","n":"12","t":"12. IntSibTree (51 pts)","b":[{"s":[{"p":"Each sibling-tree node contains item, sibling (next sibling), and child (first child). Items are nonnegative."},{"c":"static int largestSibling(IntSibTree t) {\n  if (t == null) return 0;\n  return ⟪a⟫;\n}\nstatic void postOrder(IntSibTree t, Visitor v) {\n  if (t == null) { ⟪b⟫ }\n  ⟪c⟫\n  ⟪d⟫\n  ⟪e⟫\n}","lang":"java"}]},{"id":180,"l":[{"p":"Largest sibling recursion"}],"k":"blank","a":["Math.max(t.item, largestSibling(t.sibling))"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":181,"l":[{"p":"Null case return"}],"k":"blank","a":["return;"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":182,"l":[{"p":"Visit child subtree"}],"k":"blank","a":["postOrder(t.child, v);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":183,"l":[{"p":"Visit current node"}],"k":"blank","a":["v.visit(t);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"id":184,"l":[{"p":"Visit sibling subtree"}],"k":"blank","a":["postOrder(t.sibling, v);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site"},{"s":[{"p":"Implement MaxPathFinder as a postorder Visitor. Assume largestSibling(list) and secondLargestSibling(list) return the largest and second-largest item among sibling-chain nodes (0 if absent). For a node, the best downward contribution is item plus the largest child contribution; a path through it can combine the top two child contributions. Values are nonnegative."},{"c":"class MaxPathFinder implements Visitor {\n  int bestPathSum;\n  MaxPathFinder() { ⟪f⟫ }\n  public void visit(IntSibTree t) {\n    int largest = largestSibling(t.child);\n    int secondLargest = secondLargestSibling(t.child);\n    int subTreeTotal = ⟪g⟫;\n    int thisBestPathSum = ⟪h⟫;\n    t.item = subTreeTotal;\n    bestPathSum = Math.max(⟪i⟫, ⟪j⟫);\n  }\n  int result() { return ⟪k⟫; }\n}","lang":"java"}]},{"id":185,"l":[{"p":"Initialize best result"}],"k":"blank","a":["bestPathSum = 0"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"},{"id":186,"l":[{"p":"Downward contribution"}],"k":"blank","a":["largest + t.item"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"},{"id":187,"l":[{"p":"Path through node"}],"k":"blank","a":["largest + secondLargest + t.item"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"},{"id":188,"l":[{"p":"Update best result"}],"k":"blank","a":["bestPathSum"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"},{"id":189,"l":[{"p":"Candidate path value"}],"k":"blank","a":["thisBestPathSum"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"},{"id":190,"l":[{"p":"Return best path"}],"k":"blank","a":["bestPathSum"],"topics":["TREE_TRAVERSALS","RECURSION"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-final/13","n":"13","t":"13. Flight Planning (30 pts; scored with Midterm 2)","b":[{"s":[{"p":"Use the unmodified SNRPLTE(G,s,t,W), which tests whether a no-repeated-vertex path from s to t has total weight ≤W. To detect a Hamiltonian path (world tour) in an undirected, unweighted graph G, construct a graph γ."}]},{"id":191,"l":[{"p":"New vertices added to γ"}],"k":"blank","a":["s and t"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":192,"l":[{"p":"Added directed edges"}],"k":"blank","a":["s to every copied vertex, and every copied vertex to t"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":193,"l":[{"p":"Weight assigned to each edge"}],"k":"blank","a":["-1"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":194,"l":[{"p":"SNRPLTE threshold W, for V original vertices"}],"k":"blank","a":["-(V + 1)"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":195,"l":[{"p":"Return value"}],"k":"blank","a":["SNRPLTE(γ, s, t, -(V + 1))"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp18-mt1","t":"Spring 2018 Midterm 1","src":{"exam":"https://drive.google.com/file/d/14yQDPQVcsWAG-QBPxlrX3N-YDRyR2c_C/view","sol":"https://drive.google.com/file/d/1hnRfUh2ImLGqwOSS28hFUxnpZ_cjMaQT/view","topics":"sp18-mt1"},"p":[{"id":"61b-sp18-mt1/1","n":"1","t":"1. Static Dada (19 pts)","b":[{"s":[{"c":"class Dada {\n    Dada[] r; static Dada[] rs; String name;\n    Dada(String n) { name=n; }\n    static void printDadaArray(Dada[] d) {\n        for (Dada x:d) System.out.print(x.name+\" \");\n        System.out.println();\n    }\n}\nDada a=new Dada(\"alice\"), b=new Dada(\"bob\");\nDada c=new Dada(\"carol\"), d=new Dada(\"dan\");\nDada[][] twod={{a,b},{c,d}};\na.r=twod[1]; printDadaArray(a.r); // A\nDada.rs=a.r; b.r=Dada.rs; b.r=new Dada[]{d,c};\nDada.rs[1]=new Dada(\"eve\");\nprintDadaArray(Dada.rs); // B\nprintDadaArray(b.r); // C\nprintDadaArray(twod[0]); // D\nprintDadaArray(twod[1]); // E","lang":"java"}]},{"id":1,"l":[{"p":"(a) Print A"}],"k":"blank","a":["carol dan"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a) Print B"}],"k":"blank","a":["carol eve"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"a"},{"id":3,"l":[{"p":"(a) Print C"}],"k":"blank","a":["dan carol"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"a"},{"id":4,"l":[{"p":"(a) Print D"}],"k":"blank","a":["alice bob"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"a"},{"id":5,"l":[{"p":"(a) Print E"}],"k":"blank","a":["carol eve"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"a"},{"s":[{"p":"For part (b), Dada.rs starts as [fritz, gritz]. fillOne(d) only reassigns its parameter; fillMany(d) calls System.arraycopy(rs, 0, d, 0, d.length). c.r initially refers to [alice, bob]."},{"c":"static void fillMany(Dada[] d) { System.arraycopy(Dada.rs,0,d,0,d.length); }\nstatic void fillOne(Dada d) { d=Dada.rs[0]; }\nDada.rs=new Dada[]{new Dada(\"fritz\"),new Dada(\"gritz\")};\nc.r=twod[0];\nprintDadaArray(c.r); // F\nfillOne(c.r[0]); printDadaArray(c.r); // G\nfillMany(c.r); printDadaArray(c.r); // H","lang":"java"}]},{"id":6,"l":[{"p":"(b) Print F"}],"k":"blank","a":["alice bob"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"},{"id":7,"l":[{"p":"(b) Print G"}],"k":"blank","a":["alice bob"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"},{"id":8,"l":[{"p":"(b) Print H"}],"k":"blank","a":["fritz gritz"],"topics":["JAVA","ARRAYS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp18-mt1/2","n":"2","t":"2. What It Do (12 pts)","b":[{"s":[{"c":"static int f(int x) {\n    if (x == 1) return 1;\n    return 2 * f(x / 2);\n}","lang":"java"}]},{"id":9,"l":[{"p":"(a) What does f do for x ≥ 1?"}],"k":"mc","o":["Returns x","Returns the largest power of 2 no greater than x","Returns the smallest power of 2 no less than x","Returns the number of bits in x"],"a":1,"topics":["RECURSION","JAVA"],"topicsBy":"site","part":"a"},{"id":10,"l":[{"p":"(a) What happens for x < 1?"}],"k":"mc","o":["It returns 0","It returns 1","It recurses without reaching its base case","It throws a compile error"],"a":2,"topics":["RECURSION","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"c":"static void g(IntList x) {\n    if (x == null) return;\n    g(x.rest);\n    x.rest = x;\n}\nIntList L = IntList.of(3, 4, 5);\ng(L);","lang":"java"}]},{"id":11,"l":[{"p":"(b) What does the list reachable from L become?"}],"k":"mc","o":["3 → 4 → 5 → null","3 → 3 → …","3 → 4 → 3 → …","The call never returns"],"a":1,"topics":["LINKED_LISTS","RECURSION"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp18-mt1/3","n":"3","t":"3. KeyGate (16.25 pts)","b":[{"s":[{"c":"class Key {} class SkeletonKey extends Key {} class Fingerprint {}\nclass StandardBox { void unlock(Key k) { /* UK */ } }\nclass BioBox extends StandardBox {\n    void unlock(SkeletonKey sk) { /* USK */ }\n    void unlock(Fingerprint f) { /* UF */ }\n}\nKey k = new Key(); SkeletonKey sk = new SkeletonKey(); Fingerprint f = new Fingerprint();\nStandardBox sb = new StandardBox(), sbbb = new BioBox();\nBioBox bb = new BioBox();","lang":"java"},{"p":"For each call, choose the method body that runs, or the error. Earlier erroneous lines are treated as commented out."}]},{"id":12,"l":[{"p":"sb.unlock(k)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":13,"l":[{"p":"sbbb.unlock(k)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":14,"l":[{"p":"bb.unlock(k)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":15,"l":[{"p":"sb.unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":16,"l":[{"p":"sbbb.unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":17,"l":[{"p":"bb.unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":3,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":18,"l":[{"p":"sb.unlock(f)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":0,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":19,"l":[{"p":"sbbb.unlock(f)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":0,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":20,"l":[{"p":"bb.unlock(f)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":4,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":21,"l":[{"p":"((StandardBox) bb).unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":22,"l":[{"p":"((StandardBox) sbbb).unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":2,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":23,"l":[{"p":"((BioBox) sb).unlock(sk)"}],"k":"mc","o":["Compile error","Runtime error","UK","USK","UF"],"a":1,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"},{"id":24,"l":[{"p":"Does bb = (BioBox) sbbb succeed?"}],"k":"mc","o":["Yes","Compile error","Runtime error"],"a":0,"topics":["DMS","INHERITANCE","JAVA"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp18-mt1/4","n":"4","t":"4. Sans (39 pts)","b":[{"s":[{"p":"sans copies an int array without y. ilsans does the same non-destructively for IntList. dilsans removes y from an IntList destructively without new."},{"c":"static int[] sans(int[] x, int y) {\n    int[] first = new int[x.length]; int count = 0;\n    for (int i = 0; i < x.length; i++) {\n        if (⟪a⟫) { first[count] = x[i]; count++; }\n    }\n    int[] result = new int[count];\n    System.arraycopy(first, 0, result, 0, count);\n    return result;\n}","lang":"java","f":{"a":"x[i] != y"}}]},{"id":25,"l":[{"p":"(a) Copy condition"}],"k":"blank","a":["x[i] != y"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"c":"static IntList ilsans(IntList x, int y) {\n    if (x == null) return null;\n    if (⟪a⟫) return ilsans(x.rest, y);\n    return ⟪b⟫;\n}","lang":"java","f":{"a":"x.first == y","b":"new IntList(x.first, ilsans(x.rest, y))"}}]},{"id":26,"l":[{"p":"(b) Skip condition"}],"k":"blank","a":["x.first == y"],"topics":["LINKED_LISTS","RECURSION"],"topicsBy":"site","part":"b"},{"id":27,"l":[{"p":"(b) Keep node without changing x"}],"k":"blank","a":["new IntList(x.first, ilsans(x.rest, y))"],"topics":["LINKED_LISTS","RECURSION"],"topicsBy":"site","part":"b"},{"s":[{"c":"static IntList dilsans(IntList x, int y) {\n    if (x == null) return null;\n    ⟪a⟫;\n    if (x.first == y) return ⟪b⟫;\n    return x;\n}","lang":"java","f":{"a":"x.rest = dilsans(x.rest, y)","b":"x.rest"}}]},{"id":28,"l":[{"p":"(c) Filter the rest"}],"k":"blank","a":["x.rest = dilsans(x.rest, y)"],"topics":["LINKED_LISTS","RECURSION"],"topicsBy":"site","part":"c"},{"id":29,"l":[{"p":"(c) Return when x is removed"}],"k":"blank","a":["x.rest"],"topics":["LINKED_LISTS","RECURSION"],"topicsBy":"site","part":"c"},{"id":30,"l":[{"p":"(d) Which JUnit assertion checks sans(new int[]{1,2,2,3}, 2)?"}],"k":"mc","o":["assertEquals(new int[]{1,3}, actual)","assertArrayEquals(new int[]{1,3}, actual)","assertTrue(actual == new int[]{1,3})","assertEquals(2, actual)"],"a":1,"topics":["TESTING","ARRAYS"],"topicsBy":"site","part":"d"},{"id":31,"l":[{"p":"(d) Which pair of assertions checks ilsans(IntList.of(1,2,3), 2) and non-destruction?"}],"k":"mc","o":["assertEquals(IntList.of(1,3), actual); assertEquals(IntList.of(1,2,3), x)","assertSame(x, actual)","assertEquals(IntList.of(1,3), x)","assertNull(actual)"],"a":0,"topics":["TESTING","LINKED_LISTS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp18-mt1/5","n":"5","t":"5. A Needle in ArrayStack (32 pts)","b":[{"s":[{"p":"ArrayStack doubles its array when full and halves it when less than one-quarter full, never below length 8."},{"c":"void push(Item x) {\n    if (usage_ratio() == 1) resize(size * 2);\n    ⟪a⟫;\n    ⟪b⟫;\n}\nItem pop() {\n    if (size == 0) return null;\n    if (usage_ratio() < 0.25 && items.length > 8) resize(items.length / 2);\n    ⟪c⟫;\n    Item result = items[size];\n    ⟪d⟫;\n    return result;\n}","lang":"java","f":{"a":"items[size] = x","b":"size += 1","c":"size -= 1","d":"items[size] = null"}}]},{"id":32,"l":[{"p":"(a) Store pushed item"}],"k":"blank","a":["items[size] = x"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":33,"l":[{"p":"(a) Increase size"}],"k":"blank","a":["size += 1","size++"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":34,"l":[{"p":"(a) Decrease size before reading the popped item"}],"k":"blank","a":["size -= 1","size--"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"id":35,"l":[{"p":"(a) Clear unnecessary reference"}],"k":"blank","a":["items[size] = null"],"topics":["ARRAYS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"purge(x) removes all items equal to x, preserving the order of all others. A recursive solution uses only stack operations."},{"c":"default void purge(Item x) {\n    if (size() == 0) return;\n    Item top = pop();\n    ⟪a⟫;\n    if (⟪b⟫) push(top);\n}","lang":"java","f":{"a":"purge(x)","b":"!x.equals(top)"}}]},{"id":36,"l":[{"p":"(b) Process the rest"}],"k":"blank","a":["purge(x)"],"topics":["RECURSION","ADTS"],"topicsBy":"site","part":"b"},{"id":37,"l":[{"p":"(b) Keep condition"}],"k":"blank","a":["!x.equals(top)"],"topics":["RECURSION","ADTS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp18-mt1/6","n":"6","t":"6. Combine (20 pts)","b":[{"s":[{"p":"ComFunc.apply(a,b) combines two ints and is commutative. combine must use every array item. Empty arrays produce 0."},{"c":"static int combine(ComFunc f, int[] x) {\n    if (x.length == 0) return 0;\n    if (x.length == 1) return x[0];\n    int t = ⟪a⟫;\n    return combine(f, x, t, 2);\n}\nstatic int combine(ComFunc f, int[] x, int t, int k) {\n    if (⟪b⟫) return t;\n    t = ⟪c⟫;\n    return ⟪d⟫;\n}","lang":"java","f":{"a":"f.apply(x[0], x[1])","b":"k == x.length","c":"f.apply(x[k], t)","d":"combine(f, x, t, k + 1)"}}]},{"id":38,"l":[{"p":"(a) Combine the first two"}],"k":"blank","a":["f.apply(x[0], x[1])"],"topics":["ARRAYS","RECURSION"],"topicsBy":"site","part":"a"},{"id":39,"l":[{"p":"(a) Base case"}],"k":"blank","a":["k == x.length"],"topics":["ARRAYS","RECURSION"],"topicsBy":"site","part":"a"},{"id":40,"l":[{"p":"(a) Add next item to accumulator"}],"k":"blank","a":["f.apply(x[k], t)","f.apply(t, x[k])"],"topics":["ARRAYS","RECURSION"],"topicsBy":"site","part":"a"},{"id":41,"l":[{"p":"(a) Recursive step"}],"k":"blank","a":["combine(f, x, t, k + 1)"],"topics":["ARRAYS","RECURSION"],"topicsBy":"site","part":"a"},{"id":42,"l":[{"p":"(b) Implement sumAll using Combine and Add"}],"k":"blank","a":["return Combine.combine(new Add(), x)"],"topics":["ABSTRACTION","JAVA"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp18-mt1/7","n":"7","t":"7. The Downside of Default (23 pts)","b":[{"s":[{"p":"ListOfInts has size, get, set, and addLast. plusEquals adds corresponding entries if the lists have the same size."},{"c":"default void plusEquals(ListOfInts x) {\n    if (⟪a⟫) return;\n    for (int i = 0; i < size(); i++) {\n        ⟪b⟫;\n    }\n}","lang":"java","f":{"a":"size() != x.size()","b":"set(i, get(i) + x.get(i))"}}]},{"id":43,"l":[{"p":"(a) Length check"}],"k":"blank","a":["size() != x.size()"],"topics":["LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":44,"l":[{"p":"(a) Update element"}],"k":"blank","a":["set(i, get(i) + x.get(i))","this.set(i, this.get(i) + x.get(i))"],"topics":["LISTS","JAVA"],"topicsBy":"site","part":"a"},{"s":[{"p":"DLListOfInts stores a circular sentinel and an IntNode(item,next,prev). Implement plusEquals by walking both lists."},{"c":"void plusEquals(DLListOfInts x) {\n    if (x == null || size() != x.size()) return;\n    IntNode xPtr = x.sentinel.next;\n    for (IntNode p = sentinel.next; p != sentinel; p = p.next) {\n        ⟪a⟫;\n        ⟪b⟫;\n    }\n}","lang":"java","f":{"a":"p.item += xPtr.item","b":"xPtr = xPtr.next"}}]},{"id":45,"l":[{"p":"(b) Add corresponding item"}],"k":"blank","a":["p.item += xPtr.item"],"topics":["LINKED_LISTS","ITERATION"],"topicsBy":"site","part":"b"},{"id":46,"l":[{"p":"(b) Advance other pointer"}],"k":"blank","a":["xPtr = xPtr.next"],"topics":["LINKED_LISTS","ITERATION"],"topicsBy":"site","part":"b"},{"id":47,"l":[{"p":"(c) What is wrong with sumOfLists if result is declared ListOfInts result = lists[0], then result.plusEquals(lists[i]) and the method returns DLListOfInts?"}],"k":"sata","o":["The return type does not match the declared type of result","An empty input array causes an index error","The method changes lists[0]","It always computes the wrong sums for nonempty input"],"a":[0,1,2],"topics":["LISTS","ABSTRACTION"],"topicsBy":"site","part":"c"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp18-mt2","t":"Spring 2018 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1Vo8p4vbOGt7eY5TtalvAEnk4ignpTVvm/view","sol":"https://drive.google.com/file/d/1LIyFXwHYCWXNqIgKTsTyKiOYnB79_ykk/view","topics":"sp18-mt2"},"p":[{"id":"61b-sp18-mt2/1","n":"1","t":"1. Tree time (24 pts)","b":[{"s":[{"p":"Trees are written value(left, right), with - for a missing child. The BST:"},{"c":"7( 5( 1(-, 3(2, -)), - ), 8( -, 12(10(-, 11), -) ) )","lang":"txt"}]},{"id":1,"l":[{"p":"(a) Which tree can result from deleting 7 with Hibbard deletion?"}],"k":"mc","o":["5( 1(-, 3(2, -)), 8(-, 12(10(-, 11), -)) )","8( 5( 1(-, 3(2, -)), - ), 12(10(-, 11), -) )","1( -, 5(3(2, -), 8(-, 12(10(-, 11), -))) )","10( 5( 1(-, 3(2, -)), - ), 8(-, 12(11, -)) )"],"a":0,"topics":["BSTS"],"topicsBy":"site","also":[1],"x":"Either the predecessor (5) or the successor (8) replaces 7; both trees are correct.","part":"a"},{"id":2,"l":[{"p":"(b) Give a rotation on the original tree that would increase its height, written like rotateRight(11)."}],"k":"blank","a":["rotateLeft(7)","rotateRight(7)"],"topics":["BSTS"],"topicsBy":"site","x":"Rotating at the root lifts one side and pushes the other down a level.","part":"b"},{"id":3,"l":[{"p":"(c) In the 2-3 tree that results from inserting 1, 2, 3, 7, 8, 9, 5 in that order, what keys are in the root?"}],"k":"blank","a":["2, 7","2 7","[2 7]"],"topics":["B_TREES"],"topicsBy":"site","part":"c"},{"id":4,"l":[{"p":"(c) …and how many leaves does it have?"}],"k":"blank","a":["3"],"topics":["B_TREES"],"topicsBy":"site","x":"The tree is [2 7] with leaves [1], [3 5] and [8 9].","part":"c"},{"id":5,"l":[{"p":"(d) Which is the LLRB that results from inserting 1, 2, 3, 7, 8, 9, 5 in that order? (A * marks a node whose link to its parent is red.)"}],"k":"mc","o":["7( *2(1, 5(*3, -)), 9(*8, -) )","5( *2(1, 3), 8(*7, 9) )","7( 2(1, *5(3, -)), *9(8, -) )","2( 1, *7(5(*3, -), 9(*8, -)) )"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","x":"It mirrors the 2-3 tree from (c): [2 7] becomes 7 with red left child 2, [3 5] becomes 5 with red left child 3, [8 9] becomes 9 with red left child 8.","part":"d"},{"id":6,"l":[{"p":"(e) What is the minimum height of a valid BST containing the keys 1, 2, 3, 7, 8, 9, 5? (Height = links from the root to the deepest leaf.)"}],"k":"blank","a":["2"],"topics":["BSTS"],"topicsBy":"site","x":"For example 5(2(1, 3), 8(7, 9)).","part":"e"},{"id":7,"l":[{"p":"(f) Under what conditions is a complete BST containing N items unique (the only complete BST with exactly those items)? BSTs never contain duplicates."}],"k":"mc","o":["Always, for any N","Only when N is one less than a power of 2","Only when N is a power of 2","Never, for N > 2"],"a":0,"topics":["BSTS"],"topicsBy":"site","x":"A complete tree’s shape is fixed by N, and a BST’s in-order traversal must be sorted, so the values have only one possible placement.","part":"f"}],"topics":null},{"id":"61b-sp18-mt2/2","n":"2","t":"2. Hash Tables (28 pts)","b":[{"s":[{"p":"XList is a list of integers whose hash code is the sum of its digits; two XLists are equal only with the same length and values in the same order. FourBucketHashMap uses external chaining, adds new items to the end of each bucket, always has four buckets and never resizes."},{"c":"FourBucketHashMap<XList, String> fbhm = new FourBucketHashMap<>();\nfbhm.put(XList.of(1, 2, 3), \"cat\");\nfbhm.put(XList.of(1, 4), \"riding\");\nfbhm.put(XList.of(5), \"a\");\nfbhm.put(XList.of(3, 4), \"bull\");\nfbhm.put(XList.of(1, 4), \"below\");","lang":"java"},{"p":"(a) What does each bucket hold? Write each entry as list = value, in chain order, separated by commas, e.g. [1, 4] = below, [5] = a; write [] for an empty bucket."}]},{"id":8,"l":[{"p":"(a) Bucket 0"}],"k":"blank","a":["[]","empty"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":9,"l":[{"p":"(a) Bucket 1"}],"k":"blank","a":["[1, 4] = below, [5] = a","[1, 4] = \"below\", [5] = \"a\"","[1,4]=below, [5]=a"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":10,"l":[{"p":"(a) Bucket 2"}],"k":"blank","a":["[1, 2, 3] = cat","[1, 2, 3] = \"cat\"","[1,2,3]=cat"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":11,"l":[{"p":"(a) Bucket 3"}],"k":"blank","a":["[3, 4] = bull","[3, 4] = \"bull\"","[3,4]=bull"],"topics":["HASHING"],"topicsBy":"site","x":"Sums: 6 → bucket 2, 5 → 1, 5 → 1, 7 → 3. The last put finds [1, 4] and replaces its value.","part":"a"},{"s":[{"c":"// (b)\nFourBucketHashMap<XList, String> fbhm = new FourBucketHashMap<>();\nXList firstList = XList.of(1, 2, 3);\nfbhm.put(firstList, \"cat\");\nfbhm.get(XList.of(1, 2, 3));     // (i)\nfirstList.addLast(0);            // list is now [1, 2, 3, 0]\nfbhm.get(firstList);             // (ii)\nfbhm.get(XList.of(1, 2, 3));     // (iii)","lang":"java"}]},{"id":12,"l":[{"p":"(b) (i) returns"}],"k":"blank","a":["cat","\"cat\""],"topics":["HASHING","EQUALS"],"topicsBy":"site","part":"b"},{"id":13,"l":[{"p":"(b) (ii) returns"}],"k":"blank","a":["cat","\"cat\""],"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"Adding 0 doesn’t change the sum, so the key is still found in bucket 2.","part":"b"},{"id":14,"l":[{"p":"(b) (iii) returns"}],"k":"blank","a":["null"],"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"[1, 2, 3] lands in bucket 2, but the stored key is now [1, 2, 3, 0], which isn’t equal.","part":"b"},{"s":[{"c":"// (c)\nFourBucketHashMap<XList, String> fbhm = new FourBucketHashMap<>();\nXList firstList = XList.of(1, 2, 3);\nfbhm.put(firstList, \"cat\");\nfirstList.addLast(1);               // list is now [1, 2, 3, 1]\nfbhm.get(firstList);                // (i)\nfbhm.get(XList.of(1, 2, 3));        // (ii)\nfbhm.get(XList.of(1, 2, 3, 1));     // (iii)\nfbhm.get(XList.of(3, 4));           // (iv)\nfbhm.put(firstList, \"dog\");\nfbhm.get(firstList);                // (v)\nfbhm.get(XList.of(1, 2, 3));        // (vi)\nfbhm.get(XList.of(1, 2, 3, 1));     // (vii)","lang":"java"},{"p":"Write what each get returns (null if not found), separated by commas."}]},{"id":15,"l":[{"p":"(c) (i) through (iv)"}],"k":"blank","a":["null, null, null, null","null null null null"],"topics":["HASHING","EQUALS"],"topicsBy":"site","part":"c"},{"id":16,"l":[{"p":"(c) (v) through (vii)"}],"k":"blank","a":["dog, null, dog","dog null dog","\"dog\", null, \"dog\""],"topics":["HASHING","EQUALS"],"topicsBy":"site","x":"The mutated key now sums to 7 (bucket 3) but is stored in bucket 2, so it can’t be found; [1, 2, 3] reaches bucket 2 but isn’t equal. put then adds a second entry in bucket 3, which (v) and (vii) find.","part":"c"},{"s":[{"p":"(d) FourBucketHashMap’s best- and worst-case get and put runtimes, as a function of N items (assume nothing about the keys)."}]},{"id":17,"l":[{"p":"(d) get: best / worst"}],"k":"mc","o":["Θ(1) / Θ(1)","Θ(1) / Θ(log N)","Θ(1) / Θ(N)","Θ(N) / Θ(N)"],"a":2,"topics":["HASHING"],"topicsBy":"site","part":"d"},{"id":18,"l":[{"p":"(d) put: best / worst"}],"k":"mc","o":["Θ(1) / Θ(1)","Θ(1) / Θ(log N)","Θ(1) / Θ(N)","Θ(N) / Θ(N)"],"a":2,"topics":["HASHING"],"topicsBy":"site","x":"Four buckets never grow, so a bucket can hold Θ(N) items; but the key might be first in its bucket.","part":"d"},{"id":19,"l":[{"p":"(e) If it instead triples its buckets when the load factor exceeds 0.7 (a resize takes linear time), what are get’s and put’s best / worst runtimes?"}],"k":"mc","o":["Θ(1) / Θ(1) for both","Θ(1) / Θ(N) for both","get Θ(1) / Θ(1), put Θ(1) / Θ(N)","Θ(1) / Θ(log N) for both"],"a":1,"topics":["HASHING"],"topicsBy":"site","x":"With nothing assumed about the keys, all of them can still collide; and a put that triggers a resize costs Θ(N).","part":"e"}],"topics":null},{"id":"61b-sp18-mt2/3","n":"3","t":"3. Weighted Quick Union (32 pts)","b":[{"s":[{"p":"A “fully connected” DisjointSets object is one where connected returns true for any arguments. A tree’s height is the number of links from the root to the deepest leaf. Heighted Quick Union is like Weighted Quick Union but uses height instead of weight to choose the new root."}]},{"id":20,"l":[{"p":"(a) Fully connected with 6 items: Weighted Quick Union’s best-case height"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":21,"l":[{"p":"(a) …Weighted Quick Union’s worst-case height"}],"k":"blank","a":["2"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":22,"l":[{"p":"(a) …Heighted Quick Union’s best-case height"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":23,"l":[{"p":"(a) …Heighted Quick Union’s worst-case height"}],"k":"blank","a":["2"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":24,"l":[{"p":"(b) Give an exact formula for the minimum number of objects in a Weighted Quick Union tree of height H."}],"k":"blank","a":["2^H","2**H","2ᴴ","pow(2, H)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":25,"l":[{"p":"(c) Which Quick Union tree is possible for Heighted Quick Union but impossible for Weighted Quick Union? (Written value(children).)"}],"k":"mc","o":["1( 2, 3(4, 5, 6) )","1( 2, 3, 4, 5, 6 )","1( 2(3, 4), 5(6) )","None exists"],"a":0,"topics":["DISJOINT_SETS"],"topicsBy":"site","x":"3’s tree (4 items, height 1) went under 1’s tree (2 items, height 1): fine when heights tie, but WQU always puts the lighter tree below.","part":"c"},{"s":[{"p":"(d) Create a set for SimpleOomage objects using a WeightedQuickUnionUF. Its hashCode() is perfect: unique and always between 0 and 140,607 inclusive. WeightedQuickUnionUF’s methods are union() and connected()."},{"c":"public class SimpleOomageSet {\n    private WeightedQuickUnionUF wq = new WeightedQuickUnionUF(⟪a⟫);\n    public void add(T item) {\n        ⟪b⟫;\n    }\n    public boolean contains(T item) {\n        ⟪c⟫;\n    }\n}","lang":"java","f":{"a":"140609","b":"wq.union(item.hashCode(), 140608)","c":"return wq.connected(item.hashCode(), 140608)"}}]},{"id":26,"l":[{"p":"(d) The WeightedQuickUnionUF’s size"}],"k":"blank","a":["140609"],"topics":["DISJOINT_SETS","HASHING"],"topicsBy":"site","part":"d"},{"id":27,"l":[{"p":"(d) The body of add"}],"k":"blank","a":["wq.union(item.hashCode(), 140608)","union(item.hashCode(), 140608)","wq.union(140608, item.hashCode())"],"topics":["DISJOINT_SETS","HASHING"],"topicsBy":"site","part":"d"},{"id":28,"l":[{"p":"(d) The body of contains"}],"k":"blank","a":["return wq.connected(item.hashCode(), 140608)","return connected(item.hashCode(), 140608)","return wq.connected(140608, item.hashCode())"],"topics":["DISJOINT_SETS","HASHING"],"topicsBy":"site","x":"Use one extra item (140,608) as a marker: adding an Oomage connects its hash code to the marker, and contains checks that connection.","part":"d"}],"topics":null},{"id":"61b-sp18-mt2/5","n":"5","t":"5. Multiset (20 pts)","b":[{"s":[{"p":"A Multiset is a set where items can occur multiple times; e.g. after add(5), add(5), add(10), add(15), add(5), multiplicity(5) returns 3. (a) A “Trinary Search Tree” implements Multiset: the left branch holds smaller items, the middle branch equal items, and the right branch larger items. Implement add."},{"c":"public interface Multiset<T> {\n    public void add(T item);            // adds item.\n    public boolean contains(T item);    // true if item occurs at least once.\n    public int multiplicity(T item);    // number of times item occurs.\n}\n\npublic class TriSTMultiset<T extends Comparable<T>> implements Multiset<T> {\n    private class Node {\n        private T item;\n        private Node left, middle, right;\n        public Node(T i) { item = i; }\n    }\n    Node root = null;\n    public void add(T item) {\n        ⟪a⟫;\n    }\n    private Node add(T item, Node p) {\n        if (p == null) { ⟪b⟫; }\n        int cmp = item.compareTo(p.item);\n        if (cmp < 0) {\n            ⟪c⟫;\n        } else if (cmp > 0) {\n            ⟪d⟫;\n        } else {\n            ⟪e⟫;\n        }\n        return p;\n    } ...\n}","lang":"java","f":{"a":"root = add(item, root)","b":"return new Node(item)","c":"p.left = add(item, p.left)","d":"p.right = add(item, p.right)","e":"p.middle = add(item, p.middle)"}}]},{"id":29,"l":[{"p":"(a) The body of the public add"}],"k":"blank","a":["root = add(item, root)"],"topics":["BSTS","ADTS"],"topicsBy":"site","part":"a"},{"id":30,"l":[{"p":"(a) if (p == null) { ____ }"}],"k":"blank","a":["return new Node(item)"],"topics":["BSTS","ADTS"],"topicsBy":"site","part":"a"},{"id":31,"l":[{"p":"(a) cmp < 0"}],"k":"blank","a":["p.left = add(item, p.left)"],"topics":["BSTS","ADTS"],"topicsBy":"site","part":"a"},{"id":32,"l":[{"p":"(a) cmp > 0"}],"k":"blank","a":["p.right = add(item, p.right)"],"topics":["BSTS","ADTS"],"topicsBy":"site","part":"a"},{"id":33,"l":[{"p":"(a) Otherwise"}],"k":"blank","a":["p.middle = add(item, p.middle)"],"topics":["BSTS","ADTS"],"topicsBy":"site","part":"a"},{"id":34,"l":[{"p":"(b) Let X have multiplicity M, and N be the number of nodes. Give the best Ω bound on the best-case runtime of any possible implementation of multiplicity(X) for a TriSTMultiset."}],"k":"mc","o":["Ω(1)","Ω(log N)","Ω(M)","Ω(N)"],"a":2,"topics":["BSTS","ADTS","ASYMPTOTICS"],"topicsBy":"site","x":"Each copy of X is its own node in the middle chain, and all M must be counted.","part":"b"},{"id":35,"l":[{"p":"(c) Rather than building Multiset from scratch, which is better?"}],"k":"mc","o":["Delegation to a java.util.TreeMap<T, Integer> (item → count)","Extending java.util.TreeSet<T>","Extending java.util.ArrayList<T>","Delegation to a java.util.HashSet<T>"],"a":0,"topics":["ADTS"],"topicsBy":"site","x":"A map from each item to its count gives add, contains and multiplicity directly. Other reasonable answers were accepted on the exam.","part":"c"}],"topics":null},{"id":"61b-sp18-mt2/6","n":"6","t":"6. Min Heaps (14 pts)","b":[{"s":[{"p":"In the min heap below, each letter represents a unique value."},{"c":"              H\n           /     \\\n          D       L\n        /   \\    / \\\n       B     F  K   M\n      / \\   / \\\n     A   C E   G","lang":"txt"},{"p":"(a) (The staff key for this part reads the letters as if the values were inserted in increasing order.)"}]},{"id":36,"l":[{"p":"(a) Smallest value"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[7],"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":37,"l":[{"p":"(a) Median value"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[8],"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":38,"l":[{"p":"(a) Largest value"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[6],"topics":["HEAPS"],"topicsBy":"site","x":"Inserting in increasing order fills the heap in level order: H < D < L < B < F < K < M < A < C < E < G.","part":"a"},{"id":39,"l":[{"p":"(b) If values were inserted in decreasing order, which letters could be the smallest value?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[7],"topics":["HEAPS"],"topicsBy":"site","x":"In any min heap the root is the smallest.","part":"b"},{"s":[{"p":"(c) If values were inserted in an unknown order:"}]},{"id":40,"l":[{"p":"(c) Which letters could be the median value?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[0,1,2,4,5,6,8,9,10],"topics":["HEAPS"],"topicsBy":"site","part":"c"},{"id":41,"l":[{"p":"(c) Which letters could be the largest value?"}],"k":"sata","o":["A","B","C","D","E","F","G","H","K","L","M"],"a":[0,2,4,6,8,10],"topics":["HEAPS"],"topicsBy":"site","x":"The largest value must be a leaf.","part":"c"}],"topics":null},{"id":"61b-sp18-mt2/7","n":"7","t":"7. Iteration (46 pts)","b":[{"s":[{"p":"(a) Fill in toList, which takes an Iterable<T> and returns a List<T>, throwing an IllegalArgumentException if any item is null. Use for-each notation; don’t call next or hasNext explicitly."},{"c":"public class IterableUtils {\n    public static <T> List<T> toList(Iterable<T> iterable) {\n        ⟪a⟫;\n        for (⟪b⟫) {\n            if (⟪c⟫) {\n                ⟪d⟫;\n            }\n            ⟪e⟫;\n        }\n        ⟪f⟫;\n    }\n}","lang":"java","f":{"a":"List<T> r = new ArrayList<T>()","b":"T t : iterable","c":"t == null","d":"throw new IllegalArgumentException()","e":"r.add(t)","f":"return r"}}]},{"id":42,"l":[{"p":"(a) First line"}],"k":"blank","a":["List<T> r = new ArrayList<T>()","List<T> r = new ArrayList<>()"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"id":43,"l":[{"p":"(a) The loop header"}],"k":"blank","a":["T t : iterable"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"id":44,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["t == null"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"id":45,"l":[{"p":"(a) Inside the if"}],"k":"blank","a":["throw new IllegalArgumentException()"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"id":46,"l":[{"p":"(a) After the if"}],"k":"blank","a":["r.add(t)"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"id":47,"l":[{"p":"(a) After the loop"}],"k":"blank","a":["return r"],"topics":["ITERATORS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) ReverseOddDigitIterator implements Iterable<Integer> and iterates through an integer’s odd digits in reverse order: new ReverseOddDigitIterator(12345770) yields 7, 7, 5, 3, 1. Write a JUnit test using toList (List.of(3, 4, 5) makes a list of 3, 4 and 5)."},{"c":"@Test\npublic void testRODI() {\n    ReverseOddDigitIterator odi = new ReverseOddDigitIterator(12345770);\n    ⟪g⟫;\n    ⟪h⟫;\n    ⟪i⟫;\n}","lang":"java","f":{"g":"List<Integer> expected = List.of(7, 7, 5, 3, 1)","h":"List<Integer> actual = IterableUtils.toList(odi)","i":"assertEquals(expected, actual)"}}]},{"id":48,"l":[{"p":"(b) First line"}],"k":"blank","a":["List<Integer> expected = List.of(7, 7, 5, 3, 1)"],"topics":["TESTING","ITERATORS"],"topicsBy":"site","part":"b"},{"id":49,"l":[{"p":"(b) Second line"}],"k":"blank","a":["List<Integer> actual = IterableUtils.toList(odi)"],"topics":["TESTING","ITERATORS"],"topicsBy":"site","part":"b"},{"id":50,"l":[{"p":"(b) Third line"}],"k":"blank","a":["assertEquals(expected, actual)"],"topics":["TESTING","ITERATORS"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Implement ReverseOddDigitIterator."},{"c":"public class ReverseOddDigitIterator implements Iterable<Integer>, Iterator<Integer> {\n    private int value;\n    public ReverseOddDigitIterator(int v) {\n        value = v;\n    }\n    public boolean hasNext() {\n        if (value == 0) {\n            return ⟪j⟫;\n        }\n        if (⟪k⟫) {\n            return ⟪l⟫;\n        } else {\n            value = ⟪m⟫;\n            return ⟪n⟫;\n        }\n    }\n    public Integer next() {\n        int d = ⟪o⟫;\n        value = ⟪p⟫;\n        return d;\n    }\n    public Iterator<Integer> iterator() {\n        return ⟪q⟫;\n    }\n}","lang":"java","f":{"j":"false","k":"value % 2 == 1","l":"true","m":"value / 10","n":"hasNext()","o":"value % 10","p":"value / 10","q":"this"}}]},{"id":51,"l":[{"p":"(c) return ____ (value is 0)"}],"k":"blank","a":["false"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":52,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["value % 2 == 1","value % 2 != 0"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":53,"l":[{"p":"(c) return ____ (odd last digit)"}],"k":"blank","a":["true"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":54,"l":[{"p":"(c) value = ____ (even last digit)"}],"k":"blank","a":["value / 10"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":55,"l":[{"p":"(c) return ____"}],"k":"blank","a":["hasNext()"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":56,"l":[{"p":"(c) int d = ____"}],"k":"blank","a":["value % 10"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":57,"l":[{"p":"(c) value = ____ (in next)"}],"k":"blank","a":["value / 10"],"topics":["ITERATORS"],"topicsBy":"site","part":"c"},{"id":58,"l":[{"p":"(c) iterator() returns"}],"k":"blank","a":["this"],"topics":["ITERATORS"],"topicsBy":"site","x":"hasNext drops even last digits until an odd one (or 0) is left; next returns the last digit and drops it.","part":"c"},{"s":[{"p":"(d) For each removal, which file (if any) fails to compile as a direct result (not because one of its dependencies failed)?"}]},{"id":59,"l":[{"p":"(d) Remove “implements Iterable<Integer>”"}],"k":"mc","o":["IterableUtils","TestRODI","ReverseOddDigitIterator","None"],"a":1,"topics":["ITERATORS","INHERITANCE"],"topicsBy":"site","x":"TestRODI passes odi to toList, which takes an Iterable.","part":"d"},{"id":60,"l":[{"p":"(d) Remove “implements Iterator<Integer>”"}],"k":"mc","o":["IterableUtils","TestRODI","ReverseOddDigitIterator","None"],"a":2,"topics":["ITERATORS","INHERITANCE"],"topicsBy":"site","x":"iterator() returns this, which is then no longer an Iterator.","part":"d"},{"id":61,"l":[{"p":"(d) Remove the hasNext method"}],"k":"mc","o":["IterableUtils","TestRODI","ReverseOddDigitIterator","None"],"a":2,"topics":["ITERATORS","INHERITANCE"],"topicsBy":"site","x":"The class no longer implements every Iterator method.","part":"d"},{"id":62,"l":[{"p":"(d) Remove the iterator method"}],"k":"mc","o":["IterableUtils","TestRODI","ReverseOddDigitIterator","None"],"a":2,"topics":["ITERATORS","INHERITANCE"],"topicsBy":"site","x":"The class no longer implements Iterable’s method.","part":"d"}],"topics":null},{"id":"61b-sp18-mt2/8","n":"8","t":"8. Asymptotics (45 pts)","b":[{"s":[{"p":"(a) Give the runtime of each function in Θ notation."},{"c":"public static void g1(int N) {\n    for (int i = 0; i < N*N*N; i += 1) {\n        for (int j = 0; j < N*N*N; j += 1) {\n            System.out.print(\"fyhe\");\n        }\n    }\n}\n\npublic static void g2(int N) {\n    for (int i = 0; i < N; i += 1) {\n        int numJ = Math.pow(2, i + 1) - 1; // <-- constant time!\n        for (int j = 0; j < numJ; j += 1) {\n            System.out.print(\"fhet\");\n        }\n    }\n}\n\npublic static void g3(int N) {\n    for (int i = 2; i < N; i *= i) {}\n    for (int i = 2; i < N; i++) {}\n}","lang":"java"}]},{"id":63,"l":[{"p":"(a) g1"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":6,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":64,"l":[{"p":"(a) g2"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":7,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"1 + 3 + 7 + … + (2ᴺ − 1) = Θ(2ᴺ).","part":"a"},{"id":65,"l":[{"p":"(a) g3"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) An algorithm’s runtime is Θ(N² log N) in all cases. Is each statement definitely true, definitely false, or is there not enough information?"}]},{"id":66,"l":[{"p":"(b) O(N² log N)"}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":67,"l":[{"p":"(b) Ω(N² log N)"}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":68,"l":[{"p":"(b) O(N³)"}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":69,"l":[{"p":"(b) Θ(N² log₄ N)"}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"Logs of different bases differ by a constant factor.","part":"b"},{"s":[{"p":"(c) An algorithm’s runtime is O(N³) in all cases."}]},{"id":70,"l":[{"p":"(c) There exist some inputs for which the runtime is Θ(N²)."}],"k":"mc","o":["True","False","Not enough information"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":71,"l":[{"p":"(c) There exist some inputs for which the runtime is Θ(N³)."}],"k":"mc","o":["True","False","Not enough information"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":72,"l":[{"p":"(c) There exist some inputs for which the runtime is Θ(N⁴)."}],"k":"mc","o":["True","False","Not enough information"],"a":1,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":73,"l":[{"p":"(c) The worst-case runtime is O(N³)."}],"k":"mc","o":["True","False","Not enough information"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":74,"l":[{"p":"(c) The worst-case runtime has order of growth N³."}],"k":"mc","o":["True","False","Not enough information"],"a":2,"topics":["ASYMPTOTICS"],"topicsBy":"site","x":"O is only an upper bound; the true order of growth could be smaller.","part":"c"},{"s":[{"p":"(d) Give the best- and worst-case runtimes. k(N) runs in constant time and returns a boolean."},{"c":"public static void g4(int N) {\n    if (N == 0) { return; }\n    g4(N - 1);\n    if (k(N)) { g4(N - 1); }\n}\n\npublic static void g5(int N) {\n    if (N == 0) { return; }\n    g5(N / 2);\n    if (k(N)) { g5(N / 2); }\n}","lang":"java"}]},{"id":75,"l":[{"p":"(d) g4 best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","part":"d"},{"id":76,"l":[{"p":"(d) g4 worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":7,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","part":"d"},{"id":77,"l":[{"p":"(d) g5 best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":1,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","part":"d"},{"id":78,"l":[{"p":"(d) g5 worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS","RECURSION"],"topicsBy":"site","x":"Two calls on N/2 at every level: 1 + 2 + 4 + … + N calls.","part":"d"},{"s":[{"p":"(e) Give the runtime of uniques in terms of N, the length of x. HashSet61B is a hash table from class (external chaining, resizes when the load factor gets too large), and resize() doesn’t traverse the chains."},{"c":"public Set<Planet> uniques(ArrayList<Planet> x) {\n    HashSet61B<Planet> items = new HashSet61B<>();\n    for (int i = 0; i < x.size(); i += 1) {\n        items.add(x.get(i));\n    }\n    return items;\n}","lang":"java"}]},{"id":79,"l":[{"p":"(e) Best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","part":"e"},{"id":80,"l":[{"p":"(e) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":4,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","x":"If every Planet collides, each add scans one long chain.","part":"e"},{"s":[{"p":"(f) The same code, but x is a list of N Strings, each of length N."}]},{"id":81,"l":[{"p":"(f) Best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","x":"This is the staff answer.","part":"f"},{"id":82,"l":[{"p":"(f) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N³)","Θ(N⁶)","Θ(2ᴺ)"],"a":5,"topics":["ASYMPTOTICS","HASHING"],"topicsBy":"site","x":"Θ(N²) comparisons, each of up to N characters.","part":"f"}],"topics":null},{"id":"61b-sp18-mt2/9","n":"9","t":"9. Flights (30 pts)","b":[{"s":[{"p":"An ArrayList<Flight> holds every commercial flight ever taken. Each Flight stores a start time, an end time and a number of passengers, all as ints (minutes since January 1, 1914). Give an algorithm that finds the largest number of people ever in flight at once, in N log N time for N flights, not depending on the number of minutes since 1914. (The exam asked you to list the data structures and describe the algorithm.)"}]},{"id":83,"l":[{"p":"Which approach works?"}],"k":"mc","o":["Put the flights in one min-PQ by start time and one by end time. Repeatedly remove the smaller top: a start adds its passengers to a running tally (record the best tally seen), an end subtracts them.","Count the passengers in the air at every minute since 1914 and return the largest count.","Sort the flights by number of passengers and return the largest single flight’s passengers.","Put every flight in a HashMap from start time to passengers and add up the values at the busiest start time."],"a":0,"topics":["HEAPS","SORTING"],"topicsBy":"site","x":"Processing the 2N start and end events in time order needs only N log N. Sorting the list by start time and keeping an end-time PQ also works."}],"topics":null}],"by":["Hug"]},{"id":"61b-sp19-final","t":"Spring 2019 Final","src":{"exam":"https://drive.google.com/file/d/1ADV5iN2OSxP8fHfaGvqlyT39QqncEdij/view","sol":"https://drive.google.com/file/d/1Wu9X7czbBIAywTLoCcqx07-JF92iCeTi/view","topics":"sp19-final"},"p":[{"id":"61b-sp19-final/1","n":"1","t":"1. Sorting Cornucopia (98 pts)","b":[{"s":[{"p":"Sort [9,1,1,3,5,5,6,8]."}]},{"id":1,"l":[{"p":"(a)(i) Bottom-up max-heap array"}],"k":"blank","a":["9,8,6,3,5,5,1,1"],"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(a)(ii) Array after one in-place remove-largest (including sorted suffix)"}],"k":"blank","a":["8,5,6,3,1,5,1,9"],"topics":["HEAPS","SORTING"],"topicsBy":"site","part":"a"},{"id":3,"l":[{"p":"(b) Two sorted arrays merged in final mergesort step"}],"k":"blank","a":["1,1,3,9 | 5,5,6,8"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":4,"l":[{"p":"(c) Does inserting into TreeSet and iterating preserve the full sorted array?"}],"k":"mc","o":["No, duplicate values disappear from a set","Yes, TreeSet preserves duplicates","No, iteration is preorder","Yes, insertion sort is required"],"a":0,"topics":["BSTS","SORTING"],"topicsBy":"site","part":"c"},{"id":5,"l":[{"p":"(d) Fastest sort for this specific array"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING"],"topicsBy":"site","part":"d"},{"s":[{"p":"Why?"}]},{"id":6,"l":[{"p":"(d) Reason"}],"k":"blank","a":["Small array and linear number of inversions"],"topics":["SORTING"],"topicsBy":"site","part":"d"},{"s":[{"p":"(e) For each possible partition result, classify as: Hoare; another partition scheme only; or impossible."}]},{"id":7,"l":[{"p":"[4,5,1,3,7,2,6]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":8,"l":[{"p":"[1,2,3,4,5,6,7]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":9,"l":[{"p":"[1,7,5,3,4,2,6]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":10,"l":[{"p":"[1,3,4,2,5,7,6]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":11,"l":[{"p":"[1,3,4,2,5,6,7]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":2,"topics":["SORTING"],"topicsBy":"site"},{"id":12,"l":[{"p":"[2,1,3,4,5,7,6]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":1,"topics":["SORTING"],"topicsBy":"site"},{"id":13,"l":[{"p":"[3,2,1,4,7,5,6]"}],"k":"mc","o":["Hoare partition","Other partition only","Impossible"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"(f) Merge [1,7,8,9] and [2,3,4,5]. Mark each statement true or false."}]},{"id":14,"l":[{"p":"Result is sorted"}],"k":"blank","a":["true"],"topics":["SORTING"],"topicsBy":"site"},{"id":15,"l":[{"p":"1 is compared to another item exactly once"}],"k":"blank","a":["true"],"topics":["SORTING"],"topicsBy":"site"},{"id":16,"l":[{"p":"2 is compared to 3"}],"k":"blank","a":["false"],"topics":["SORTING"],"topicsBy":"site"},{"id":17,"l":[{"p":"Exactly 7 comparisons"}],"k":"blank","a":["false"],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"(g) Merge sorted [1,7,8,9] with [A,B,C,D], where A–D are arbitrary integers. Use true, false, or cannot be determined (CBD)."}]},{"id":18,"l":[{"p":"1 compared exactly once"}],"k":"blank","a":["CBD"],"topics":["SORTING"],"topicsBy":"site"},{"id":19,"l":[{"p":"A compared to B"}],"k":"blank","a":["false"],"topics":["SORTING"],"topicsBy":"site"},{"id":20,"l":[{"p":"Exactly 7 comparisons"}],"k":"blank","a":["CBD"],"topics":["SORTING"],"topicsBy":"site"},{"id":21,"l":[{"p":"1 is in correct order relative to A"}],"k":"blank","a":["true"],"topics":["SORTING"],"topicsBy":"site"},{"id":22,"l":[{"p":"C is in correct order relative to 1"}],"k":"blank","a":["CBD"],"topics":["SORTING"],"topicsBy":"site"},{"id":23,"l":[{"p":"8 is in correct order relative to A"}],"k":"blank","a":["false"],"topics":["SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp19-final/2","n":"2","t":"2. Radix Sorting (43 pts)","b":[{"s":[{"p":"Input: [123,723,175,394,763]."}]},{"id":24,"l":[{"p":"(a) Counting sort by rightmost digit"}],"k":"blank","a":["123,723,763,394,175"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":25,"l":[{"p":"(b) After two LSD counting-sort passes (ones, then tens)"}],"k":"blank","a":["123,723,763,175,394"],"topics":["SORTING"],"topicsBy":"site","part":"b"},{"id":26,"l":[{"p":"(c) Stable insertion sort using only leftmost digit"}],"k":"blank","a":["123,175,394,723,763"],"topics":["SORTING"],"topicsBy":"site","part":"c"},{"id":27,"l":[{"p":"(d) LSD radix with heapsort subroutine: why can it fail?"}],"k":"blank","a":["Heapsort is not stable"],"topics":["SORTING"],"topicsBy":"site","part":"d"},{"id":28,"l":[{"p":"(d) MSD radix with heapsort subroutine: does it always work?"}],"k":"blank","a":["yes"],"topics":["SORTING"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp19-final/3","n":"3","t":"3. MSTs, SPTs (62 pts)","b":[{"s":[{"p":"Undirected graph edge weights from the diagram: center O–upper-left 40, O–upper-right 20, O–lower-left 30, O–lower-right 55; upper-left–upper-right 65; upper-left–left 10; left–lower-left 85; lower-left–lower-right 70; upper-right–right 100; lower-right–right 90."}]},{"id":29,"l":[{"p":"(a) Prim MST edge weights in order from O"}],"k":"blank","a":["20,30,40,10,55,90"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":30,"l":[{"p":"(b) Is this SPT also the MST? If no, give an SPT edge not in MST"}],"k":"blank","a":["no; 100"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"b"},{"id":31,"l":[{"p":"(c) Do G and G−1000 have the same MST edge set?"}],"k":"blank","a":["yes"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"c"},{"id":32,"l":[{"p":"(d) Smallest edge touching a vertex in a nonnegative weighted undirected graph is always in MST: T/F"}],"k":"blank","a":["true"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"d"},{"id":33,"l":[{"p":"(e) Smallest edge leaving a vertex in a nonnegative weighted directed graph is always in its SPT: T/F"}],"k":"blank","a":["true"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"e"}],"topics":null},{"id":"61b-sp19-final/4","n":"4","t":"4. Binary Search Tree Removal Redux (51 pts)","b":[{"s":[{"c":"TreeNode min(TreeNode x) {\n  if (x == null) return null;\n  if (x.left == null) return x;\n  return min(x.left);\n}\nvoid hibbardDelete(TreeNode x) {\n  TreeNode successor = min(x.right);\n  x.right = deleteMin(x.right);\n  x.item = successor.item;\n}","lang":"java"}]},{"id":34,"l":[{"p":"(a) Condition for minimum node"}],"k":"blank","a":["x.left == null"],"topics":["BSTS"],"topicsBy":"site","part":"a"},{"id":35,"l":[{"p":"(a) Return minimum node"}],"k":"blank","a":["return x"],"topics":["BSTS"],"topicsBy":"site","part":"a"},{"id":36,"l":[{"p":"(a) Recursive call"}],"k":"blank","a":["return min(x.left)"],"topics":["BSTS"],"topicsBy":"site","part":"a"},{"id":37,"l":[{"p":"(b) Successor expression"}],"k":"blank","a":["min(x.right)"],"topics":["BSTS"],"topicsBy":"site","part":"b"},{"id":38,"l":[{"p":"(b) Remove successor from right subtree"}],"k":"blank","a":["x.right = deleteMin(x.right)"],"topics":["BSTS"],"topicsBy":"site","part":"b"},{"id":39,"l":[{"p":"(b) Replace deleted item"}],"k":"blank","a":["x.item = successor.item"],"topics":["BSTS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp19-final/5","n":"5","t":"5. Implementation Details (50 pts)","b":[{"s":[{"p":"For each choice, identify the primary reason the first choice is preferred."}]},{"id":40,"l":[{"p":"Heap array starts at index 1 rather than 0"}],"k":"blank","a":["Simplifies code"],"topics":["ADTS"],"topicsBy":"site"},{"id":41,"l":[{"p":"Dijkstra visits increasing rather than decreasing distance"}],"k":"blank","a":["Guarantees correctness","Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":42,"l":[{"p":"KdTree visits left child first when query lies left (with pruning)"}],"k":"blank","a":["Guarantees correctness","Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":43,"l":[{"p":"Shuffle before Quicksort"}],"k":"blank","a":["Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":44,"l":[{"p":"Rotate after BST insertion"}],"k":"blank","a":["Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":45,"l":[{"p":"Resize hash table after removal"}],"k":"blank","a":["Reduce memory use"],"topics":["ADTS"],"topicsBy":"site"},{"id":46,"l":[{"p":"A* rather than Dijkstra for s-to-t shortest path"}],"k":"blank","a":["Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":47,"l":[{"p":"Heap rather than ordered array for priority queue"}],"k":"blank","a":["Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":48,"l":[{"p":"Doubly linked rather than singly linked deque nodes"}],"k":"blank","a":["Improves runtime"],"topics":["ADTS"],"topicsBy":"site"},{"id":49,"l":[{"p":"Sentinels rather than direct first/last pointers"}],"k":"blank","a":["Simplifies code"],"topics":["ADTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp19-final/7","n":"7","t":"7. DisjointSets (84 pts)","b":[{"s":[{"p":"Implement arbitrary integer QuickUnion using one instance field, plus an iterator over the connected component. Code fragments are individual checkable pieces."},{"c":"HashMap<Integer, Integer> itemToParent;\nQuickUnionSp19F() { itemToParent = new HashMap<>(); }\nvoid add(int p) {\n  if (vertexExists(p)) throw new IllegalArgumentException();\n  itemToParent.put(p, p);\n}\nboolean vertexExists(int p) { return itemToParent.containsKey(p); }\nSet<Integer> vertices() { return itemToParent.keySet(); }\nvoid connect(int p, int q) {\n  if (!vertexExists(p) || !vertexExists(q)) throw new IllegalArgumentException();\n  int pRoot = root(p), qRoot = root(q);\n  itemToParent.put(qRoot, pRoot);\n}\nint root(int p) {\n  if (!vertexExists(p)) throw new IllegalArgumentException();\n  int parent = itemToParent.get(p);\n  if (parent == p) return p;\n  return root(parent);\n}","lang":"java"}]},{"id":50,"l":[{"p":"(a) The one instance variable"}],"k":"blank","a":["HashMap<Integer, Integer> itemToParent"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":51,"l":[{"p":"(a) Constructor initialization"}],"k":"blank","a":["itemToParent = new HashMap<>()"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":52,"l":[{"p":"(a) Add a new root entry"}],"k":"blank","a":["itemToParent.put(p, p)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":53,"l":[{"p":"(a) Check whether item exists"}],"k":"blank","a":["itemToParent.containsKey(p)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":54,"l":[{"p":"(a) Return vertices"}],"k":"blank","a":["itemToParent.keySet()"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":55,"l":[{"p":"(a) Link roots in connect"}],"k":"blank","a":["itemToParent.put(qRoot, pRoot)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":56,"l":[{"p":"(a) Read parent in root"}],"k":"blank","a":["int parent = itemToParent.get(p)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":57,"l":[{"p":"(a) Root base case"}],"k":"blank","a":["if (parent == p) return p"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":58,"l":[{"p":"(a) Recursive root step"}],"k":"blank","a":["return root(parent)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":59,"l":[{"p":"(b) Iterator class implements"}],"k":"blank","a":["Iterable<Integer>"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":60,"l":[{"p":"(b) Store component items in"}],"k":"blank","a":["List<Integer> items"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":61,"l":[{"p":"(b) Allocate component list"}],"k":"blank","a":["items = new ArrayList<Integer>()"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":62,"l":[{"p":"(b) Scan all vertices"}],"k":"blank","a":["for (int q : ds.vertices())"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":63,"l":[{"p":"(b) Select component members"}],"k":"blank","a":["if (ds.isConnected(p, q)) items.add(q)"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":64,"l":[{"p":"(b) Iterator method returns"}],"k":"blank","a":["items.iterator()"],"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp19-final/8","n":"8","t":"8. Asymptotics (68 pts)","b":[{"s":[{"c":"int f1(int N) {\n  if (N <= 1) return N;\n  int sum = f1(N/2);\n  for (int i=0; i<N/2; i+=1) {}\n  sum += f1(N/3);\n  for (int i=0; i<N/2; i+=1) {}\n  sum += f1(N/6); return sum;\n}\nvoid f2(ArrayList<String> A, String s) {\n  int N=A.length(); int sLocation=A.indexOf(s);\n  if (sLocation > -1) { String temp=A.get(0); A.set(0,A.get(sLocation)); A.set(sLocation,temp); }\n}\nint f3(TreeSet<Bloop> A, HashSet<Bloop> B) {\n  int N=A.size()+B.size(), inBoth=0;\n  for (Bloop a : A.keySet()) if (B.containsKey(a)) inBoth++;\n  return inBoth;\n}\nvoid f4(int N) {\n  int M=0; for (int i=1; i<N; i*=2) M++;\n  f4helper(M);\n}\nvoid f4helper(int Q) { if (Q<=0) return; for (int i=0;i<Q;i++) {} f4helper(Q-1); }","lang":"java"}]},{"id":65,"l":[{"p":"f1"}],"k":"blank","a":["Theta(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":66,"l":[{"p":"f2"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":67,"l":[{"p":"f3"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":68,"l":[{"p":"f4"}],"k":"blank","a":["Theta((log N)^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp19-final/9","n":"9","t":"9. Reductions and Sorting (58 pts)","b":[{"s":[{"p":"Graph Path Sort creates an edge of weight 1 from each smaller integer to each larger integer, then runs DAG shortest paths from the minimum and returns the path to the maximum."}]},{"id":69,"l":[{"p":"(i) Overall runtime"}],"k":"blank","a":["Theta(N^2)"],"topics":["SHORTEST_PATHS","ASYMPTOTICS"],"topicsBy":"site","part":"i"},{"id":70,"l":[{"p":"(ii) Output on [5,1,7,9,3]"}],"k":"blank","a":["[1,9]"],"topics":["SHORTEST_PATHS"],"topicsBy":"site"},{"id":71,"l":[{"p":"(iii) Simple fix to make it sort all unique integer arrays"}],"k":"blank","a":["Set every edge weight to -1 so DAGSPT chooses a longest path; the transitive graph’s longest path visits all values in sorted order"],"topics":["SHORTEST_PATHS","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp19-final/10","n":"10","t":"10. A New Way (73 pts)","b":[{"s":[{"p":"Linear probing, table size M=8. Hash code of an integer is its last digit."}]},{"id":72,"l":[{"p":"(a) Table indices 0 through 7 after adding 93,21,5,3,13,25,83"}],"k":"blank","a":["83,21,null,93,3,5,13,25"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":73,"l":[{"p":"(b) Four ordered adds so contains(0) uses 2 equals calls and contains(1) uses 3"}],"k":"blank","a":["10,0,21,1"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":74,"l":[{"p":"(c) Table after deleting 5 from the table in (a), indices 0 through 7"}],"k":"blank","a":["null,21,null,93,3,13,25,83"],"topics":["HASHING"],"topicsBy":"site","part":"c"},{"id":75,"l":[{"p":"(d) Best-case deletion runtime"}],"k":"blank","a":["Theta(1)"],"topics":["HASHING","ASYMPTOTICS"],"topicsBy":"site","part":"d"},{"id":76,"l":[{"p":"(d) Worst-case deletion runtime"}],"k":"blank","a":["Theta(N)"],"topics":["HASHING","ASYMPTOTICS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp19-final/11","n":"11","t":"11. Ψcle (83 pts)","b":[{"s":[{"p":"Directed weighted graph arcs from the figure: B→X(1), C→X(2), X→A(1), B→C(5), C→B(20), C→A(20), Z→B(20), B→Y(3), Z→Y(4), Y→Z(5), Y→A(4), A→B(10). A psi-compliant cycle contains at most one vertex from Ψ."}]},{"id":77,"l":[{"p":"(a) Shortest simple psi-compliant cycle weight for Ψ={A,B,X}"}],"k":"blank","a":["9"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":78,"l":[{"p":"(b) Shortest simple psi-compliant cycle weight for Ψ={X,Y,Z}"}],"k":"blank","a":["12"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"b"},{"s":[{"p":"(c) Select an algorithm meeting O(P V E log V): remove vertices of Ψ to create P+1 graphs (one excludes all Ψ, each other excludes all but one Ψ vertex); in each graph compute the minimum simple-cycle weight by running Dijkstra from every vertex and checking each return edge."}]},{"id":79,"l":[{"p":"Which construction meets the required bound?"}],"k":"mc","o":["Build P+1 subgraphs, each omitting a subset of Ψ as described, then run all-sources Dijkstra and close each path with an edge back to its source","Run one Dijkstra from every vertex on the original graph and ignore Ψ","Enumerate all simple cycles and filter by Ψ","Run Kruskal on each connected component"],"a":0,"topics":["SHORTEST_PATHS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp19-final/12","n":"12","t":"12. Tree Representation 4 (130 pts)","b":[{"s":[{"p":"Representation 4 is breadth-first order, with each node preceded by a boolean that is true exactly for leaves; each node has either zero or two children."}]},{"id":80,"l":[{"p":"(a) Representation for the pictured tree (root 2; children 1 and 6; 6 has children 4 and 7; 4 has children 3 and 5)"}],"k":"blank","a":["F,2,T,1,F,6,F,4,T,7,T,3,T,5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":81,"l":[{"p":"(b) Tree for sequence F,6,T,3,F,4,T,7,T,8 (describe links)"}],"k":"blank","a":["6 has left child 3 and right child 4; 4 has children 7 and 8"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":82,"l":[{"p":"(c) With 9 numbers and 9 flags, minimum and maximum true flags"}],"k":"blank","a":["5,5"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"c"},{"s":[{"c":"void writeTree(Out out) {\n  Queue<Node> q = new Queue<>();\n  q.enqueue(this);\n  while (!q.isEmpty()) {\n    Node p = q.dequeue();\n    boolean leaf = p.left == null && p.right == null;\n    out.println(leaf);\n    out.println(p.item);\n    if (!leaf) { q.enqueue(p.left); q.enqueue(p.right); }\n  }\n}","lang":"java"}]},{"id":83,"l":[{"p":"(d) Queue initialization"}],"k":"blank","a":["Queue<Node> q = new Queue<>();"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"id":84,"l":[{"p":"(d) Seed queue with this root"}],"k":"blank","a":["q.enqueue(this);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"id":85,"l":[{"p":"(d) Leaf predicate"}],"k":"blank","a":["p.left == null && p.right == null"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"id":86,"l":[{"p":"(d) Output leaf flag"}],"k":"blank","a":["out.println(leaf);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"id":87,"l":[{"p":"(d) Output node item"}],"k":"blank","a":["out.println(p.item);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"id":88,"l":[{"p":"(d) Enqueue children when internal"}],"k":"blank","a":["q.enqueue(p.left); q.enqueue(p.right);"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"},{"s":[{"p":"(e) Give an 11-node tree whose breadth-first representation is also parsed correctly by the buggy preorder reader. A right spine of internal nodes, each with a left leaf, ending in an internal node with two leaves works; assign equal item values."}]},{"id":89,"l":[{"p":"(e) Describe one valid tree shape"}],"k":"blank","a":["A right spine of 5 internal nodes; each of the first 4 has a left leaf and a right internal child; the final internal node has two leaves"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"e"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp19-mt1","t":"Spring 2019 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1kTHkeOf-TnvIsllJU5GRF-GjdMhuq_2L/view","sol":"https://drive.google.com/file/d/14EBdd8SO_vt7oEBNJnK5EHB2DGtoBfbt/view","topics":"sp19-mt1"},"p":[{"id":"61b-sp19-mt1/1","n":"1","t":"1. Static Swap (24 pts)","b":[{"s":[{"c":"class StaticSwap {\n    static int staticX=5, staticY=10;\n    static void swap(int x,int y) { int temp=x; x=y; y=temp; }\n    static void staticSwap(int x,int y) {\n        int temp=staticX; staticX=staticY; staticY=temp;\n    }\n    public static void main(String[] args) {\n        int a=5,b=10;\n        swap(a,b); // A\n        swap(staticX,staticY); // B\n        staticSwap(a,b); // C\n        staticSwap(staticX,staticY); // D\n    }\n}","lang":"java"},{"p":"For each call, select every variable whose value changes."}]},{"id":1,"l":[{"p":"(a) Call A"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[4],"topics":["JAVA"],"part":"a"},{"id":2,"l":[{"p":"(a) Call B"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[4],"topics":["JAVA"],"part":"a"},{"id":3,"l":[{"p":"(a) Call C"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[2,3],"topics":["JAVA"],"part":"a"},{"id":4,"l":[{"p":"(a) Call D"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[2,3],"topics":["JAVA"],"part":"a"},{"s":[{"p":"Part (b) changes every int field and parameter to String. The swap and staticSwap bodies otherwise stay the same. Which variables change?"}]},{"id":5,"l":[{"p":"(b) Call A"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[4],"topics":["JAVA"],"part":"b"},{"id":6,"l":[{"p":"(b) Call B"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[4],"topics":["JAVA"],"part":"b"},{"id":7,"l":[{"p":"(b) Call C"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[2,3],"topics":["JAVA"],"part":"b"},{"id":8,"l":[{"p":"(b) Call D"}],"k":"sata","o":["a","b","staticX","staticY","none"],"a":[2,3],"topics":["JAVA"],"part":"b"}],"topics":null},{"id":"61b-sp19-mt1/2","n":"2","t":"2. JUnit and equals (24 pts)","b":[{"s":[{"c":"class Dog {\n    int size; List<String> favoriteFoods;\n    Dog(int s,List<String> f) { size=s; favoriteFoods=f; }\n    public boolean equals(Dog o) {\n        if (this.size != o.size) return false;\n        if (this.favoriteFoods != o.favoriteFoods) return false;\n        return true;\n    }\n}","lang":"java"},{"p":"assertEquals(D1,D2) takes Object arguments and calls expected.equals(actual). Both Dogs have size 5 and separately created [\"banana\", \"tofu\"] lists."}]},{"id":9,"l":[{"p":"Why does the test fail even though the Dogs print alike?"}],"k":"mc","o":["equals(Dog) overloads rather than overrides equals(Object)","The compiler cannot create two Dogs","JUnit cannot compare lists","size must be static"],"a":0,"topics":["JAVA"]},{"id":10,"l":[{"p":"What should the implementation do before casting the Object argument to Dog?"}],"k":"mc","o":["Check it is non-null and a Dog","Call hashCode","Compare the class names as strings","Nothing"],"a":0,"topics":["JAVA"]},{"id":11,"l":[{"p":"How should the favoriteFoods lists be compared?"}],"k":"mc","o":["With ==","With equals","By comparing only their sizes","By toString identity"],"a":1,"topics":["JAVA"]}],"topics":null},{"id":"61b-sp19-mt1/4","n":"4","t":"4. More JUnit (35 pts)","b":[{"s":[{"p":"equalLists checks whether an AList and any List61B contain equal items in the same order. Part (a) asks for a JUnit test using an SLList of length three."},{"c":"SLList<Integer> sll = new SLList<>();\nsll.addLast(1); sll.addLast(2); sll.addLast(3);\nAList<Integer> all = new AList<>();\nall.addLast(1); all.addLast(2); all.addLast(3);\n⟪a⟫;","lang":"java","f":{"a":"assertTrue(all.equalLists(sll))"}}]},{"id":12,"l":[{"p":"(a) Assert the two lists compare equal"}],"k":"blank","a":["assertTrue(all.equalLists(sll))"],"topics":["JAVA","LISTS"],"part":"a"},{"s":[{"c":"public boolean equalLists(List61B<T> otherList) {\n    if (⟪a⟫) return false;\n    if (⟪b⟫) return false;\n    for (int i = 0; i < this.size; i++) {\n        if (⟪c⟫) return false;\n    }\n    return true;\n}","lang":"java","f":{"a":"otherList == null","b":"this.size != otherList.size()","c":"!this.get(i).equals(otherList.get(i))"}}]},{"id":13,"l":[{"p":"(b) Null check"}],"k":"blank","a":["otherList == null"],"topics":["JAVA","LISTS"],"part":"b"},{"id":14,"l":[{"p":"(b) Size check"}],"k":"blank","a":["this.size != otherList.size()","size != otherList.size()"],"topics":["JAVA","LISTS"],"part":"b"},{"id":15,"l":[{"p":"(b) Item mismatch"}],"k":"blank","a":["!this.get(i).equals(otherList.get(i))","!get(i).equals(otherList.get(i))"],"topics":["JAVA","LISTS"],"part":"b"}],"topics":null},{"id":"61b-sp19-mt1/5","n":"5","t":"5. Recursive SLList insertion (40 pts)","b":[{"s":[{"p":"The list has a sentinel. Insert item at index without any loop."},{"c":"public void insert(T item, int index) {\n    if (⟪a⟫) throw new IllegalArgumentException();\n    insert(item, index, sentinel);\n    ⟪b⟫;\n}\nprivate void insert(T item, int index, Node n) {\n    if (index == 0) {\n        ⟪c⟫;\n    } else {\n        ⟪d⟫;\n    }\n}","lang":"java","f":{"a":"index < 0 || index > size()","b":"size += 1","c":"n.next = new Node(item, n.next)","d":"insert(item, index - 1, n.next)"}}]},{"id":16,"l":[{"p":"Invalid index condition"}],"k":"blank","a":["index < 0 || index > size()"],"topics":["LINKED_LISTS"]},{"id":17,"l":[{"p":"Update size"}],"k":"blank","a":["size += 1","size++"],"topics":["LINKED_LISTS"]},{"id":18,"l":[{"p":"Base case insertion"}],"k":"blank","a":["n.next = new Node(item, n.next)"],"topics":["LINKED_LISTS"]},{"id":19,"l":[{"p":"Recursive step"}],"k":"blank","a":["insert(item, index - 1, n.next)"],"topics":["LINKED_LISTS"]}],"topics":null},{"id":"61b-sp19-mt1/6","n":"6","t":"6. IntXList (55 pts)","b":[{"s":[{"p":"IntXList stores an array of IntSLLists, each holding at most four integers. addLast uses the first list with room."},{"c":"public void addLast(int x) {\n    if (⟪a⟫) resize(items.length * 2);\n    ⟪b⟫;\n    ⟪c⟫;\n}","lang":"java","f":{"a":"size == items.length * 4","b":"items[size / 4].addLast(x)","c":"size += 1"}}]},{"id":20,"l":[{"p":"(a) Full capacity condition"}],"k":"blank","a":["size == items.length * 4"],"topics":["LINKED_LISTS"],"part":"a"},{"id":21,"l":[{"p":"(a) Choose the inner list"}],"k":"blank","a":["items[size / 4].addLast(x)"],"topics":["LINKED_LISTS"],"part":"a"},{"id":22,"l":[{"p":"(a) Update size"}],"k":"blank","a":["size += 1","size++"],"topics":["LINKED_LISTS"],"part":"a"},{"s":[{"c":"private void resize(int numSLLists) {\n    IntSLList[] temp = new IntSLList[numSLLists];\n    for (int i = 0; i < items.length; i++) ⟪a⟫;\n    for (int i = items.length; i < numSLLists; i++) ⟪b⟫;\n    ⟪c⟫;\n}","lang":"java","f":{"a":"temp[i] = items[i]","b":"temp[i] = new IntSLList()","c":"items = temp"}}]},{"id":23,"l":[{"p":"(b) Preserve existing inner list"}],"k":"blank","a":["temp[i] = items[i]"],"topics":["LINKED_LISTS"],"part":"b"},{"id":24,"l":[{"p":"(b) Create new inner list"}],"k":"blank","a":["temp[i] = new IntSLList()"],"topics":["LINKED_LISTS"],"part":"b"},{"id":25,"l":[{"p":"(b) Replace outer array"}],"k":"blank","a":["items = temp"],"topics":["LINKED_LISTS"],"part":"b"}],"topics":null},{"id":"61b-sp19-mt1/7","n":"7","t":"7. Yeah One of These Problems (28 pts)","b":[{"s":[{"c":"class Deity {\n    void smite(Object o) { System.out.println(\"DO\"); }\n    void smite(Deity o) { System.out.println(\"DD\"); }\n    void smite(Titan o) { System.out.println(\"DT\"); }\n}\nclass Titan extends Deity {\n    void smite(Object o) { System.out.println(\"TO\"); }\n    void smite(Deity o) { System.out.println(\"TD\"); }\n    void smite(Titan o) { System.out.println(\"TT\"); }\n}\nTitan T = new Titan(); Deity D = new Deity(); Deity Colette = new Titan();","lang":"java"}]},{"id":26,"l":[{"p":"T.smite(Colette)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":4,"topics":["JAVA"]},{"id":27,"l":[{"p":"T.smite((Deity) Colette)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":4,"topics":["JAVA"]},{"id":28,"l":[{"p":"T.smite(D)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":4,"topics":["JAVA"]},{"id":29,"l":[{"p":"T.smite((Object) D)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":3,"topics":["JAVA"]},{"id":30,"l":[{"p":"((Deity) T).smite(D)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":4,"topics":["JAVA"]},{"id":31,"l":[{"p":"T.smite((Titan) D)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":6,"topics":["JAVA"]},{"id":32,"l":[{"p":"((Object) T).smite(D)"}],"k":"mc","o":["DO","DD","DT","TO","TD","TT","Runtime error","Compile error"],"a":7,"topics":["JAVA"]}],"topics":null},{"id":"61b-sp19-mt1/8","n":"8","t":"8. MetaComparison (55 pts)","b":[{"s":[{"p":"Compare corresponding IntList items with givenC, ignoring extra items in the longer list. Return a negative value if more x items compare less than y, a positive value if more compare greater, or zero on a tie."},{"c":"public int compare(IntList x, IntList y) {\n    if (⟪a⟫) return 0;\n    int v = givenC.compare(x.first, y.first);\n    if (v > 0) return ⟪b⟫;\n    else if (v < 0) return ⟪c⟫;\n    else return ⟪d⟫;\n}","lang":"java","f":{"a":"x == null || y == null","b":"compare(x.rest, y.rest) + 1","c":"compare(x.rest, y.rest) - 1","d":"compare(x.rest, y.rest)"}}]},{"id":33,"l":[{"p":"Stop at the end of either list"}],"k":"blank","a":["x == null || y == null","y == null || x == null"],"topics":["COMPARATORS"]},{"id":34,"l":[{"p":"Positive comparison branch"}],"k":"blank","a":["compare(x.rest, y.rest) + 1"],"topics":["COMPARATORS"]},{"id":35,"l":[{"p":"Negative comparison branch"}],"k":"blank","a":["compare(x.rest, y.rest) - 1"],"topics":["COMPARATORS"]},{"id":36,"l":[{"p":"Equal comparison branch"}],"k":"blank","a":["compare(x.rest, y.rest)"],"topics":["COMPARATORS"]}],"topics":null},{"id":"61b-sp19-mt1/9","n":"9","t":"9. Cool Iterators (58 pts)","b":[{"s":[{"c":"class CoolIterator implements Iterator<Integer> {\n    IntList L;\n    CoolIterator(IntList input) { L = input; }\n    boolean hasNext() { return L != null; }\n    IntList getNext(int x, IntList p) {\n        if (p == null) return null;\n        if (x == 0) return p;\n        return getNext(x - 1, p.rest);\n    }\n    Integer next() {\n        int first = L.first;\n        L = getNext(L.first, L);\n        return first;\n    }\n}\nIntList L = IntList.of(1,2,3,4,5,6,7,8,9);\nCoolIterator ci = new CoolIterator(L);\nwhile (ci.hasNext()) System.out.print(ci.next());","lang":"java"}]},{"id":37,"l":[{"p":"(a) Printed output"}],"k":"blank","a":["1248"],"topics":["ITERATORS"],"part":"a"},{"s":[{"p":"BookendIterator wraps another iterator with at least two values. It yields only its first and last values."},{"c":"class BookendIterator<T> implements Iterator<T> {\n    T[] arr = (T[]) new Object[2]; int index = 0;\n    BookendIterator(Iterator<T> input) {\n        arr[0] = ⟪a⟫;\n        while (input.hasNext()) ⟪b⟫;\n    }\n    public boolean hasNext() { return ⟪c⟫; }\n    public T next() {\n        if (!hasNext()) throw new NoSuchElementException();\n        T val = ⟪d⟫;\n        ⟪e⟫;\n        return val;\n    }\n}","lang":"java","f":{"a":"input.next()","b":"arr[1] = input.next()","c":"index < 2","d":"arr[index]","e":"index++"}}]},{"id":38,"l":[{"p":"(b) Store first value"}],"k":"blank","a":["input.next()"],"topics":["ITERATORS"],"part":"b"},{"id":39,"l":[{"p":"(b) Keep replacing last value"}],"k":"blank","a":["arr[1] = input.next()"],"topics":["ITERATORS"],"part":"b"},{"id":40,"l":[{"p":"(b) hasNext"}],"k":"blank","a":["index < 2"],"topics":["ITERATORS"],"part":"b"},{"id":41,"l":[{"p":"(b) Yield value"}],"k":"blank","a":["arr[index]"],"topics":["ITERATORS"],"part":"b"},{"id":42,"l":[{"p":"(b) Advance"}],"k":"blank","a":["index++","index += 1"],"topics":["ITERATORS"],"part":"b"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp19-mt2","t":"Spring 2019 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1yn4HBkf4f70LLS7Lu7J80DbcxXjn7bkJ/view","sol":"https://drive.google.com/file/d/1mj6UodqxVgsR7YtU8bSi50FG_R9aYqzl/view","topics":"sp19-mt2"},"p":[{"id":"61b-sp19-mt2/1","n":"1","t":"1. Tree Removal (33 pts)","b":[{"s":[{"p":"Trees are written value(left, right), with - for a missing child. (a) Here is a BST:"},{"c":"8( 4( 1(-, 3(2, -)), 7(5(-, 6), -) ), 9 )","lang":"txt"}]},{"id":1,"l":[{"p":"(a) Which tree results from deleting 4 with Hibbard deletion, using the successor (not the predecessor)?"}],"k":"mc","o":["8( 5( 1(-, 3(2, -)), 7(6, -) ), 9 )","8( 3( 1(-, 2), 7(5(-, 6), -) ), 9 )","8( 5( 1(-, 3(2, -)), 7(-, 6) ), 9 )","8( 6( 1(-, 3(2, -)), 7(5, -) ), 9 )"],"a":0,"topics":["BSTS"],"x":"4’s successor is 5 (the leftmost node of its right subtree). 5 moves up, and its right child 6 takes its place under 7.","part":"a"},{"s":[{"p":"(b) Fill in deleteMin, which deletes the smallest item in the BST rooted at TreeNode x and returns the root afterwards. x is never null; return null if the tree becomes empty. TreeNode has fields item, left and right."},{"c":"private TreeNode deleteMin(TreeNode x) {\n    if (x.left == null) { return ⟪a⟫; }\n    ⟪b⟫;\n    return ⟪c⟫;\n}","lang":"java","f":{"a":"x.right","b":"x.left = deleteMin(x.left)","c":"x"}}]},{"id":2,"l":[{"p":"(b) return ____ (no left child)"}],"k":"blank","a":["x.right"],"topics":["BSTS"],"part":"b"},{"id":3,"l":[{"p":"(b) The middle line"}],"k":"blank","a":["x.left = deleteMin(x.left)"],"topics":["BSTS"],"part":"b"},{"id":4,"l":[{"p":"(b) return ____"}],"k":"blank","a":["x"],"topics":["BSTS"],"x":"The minimum has no left child; replace it with its right subtree. Otherwise, delete the minimum from the left subtree.","part":"b"}],"topics":null},{"id":"61b-sp19-mt2/2","n":"2","t":"2. Hash Tables (49 pts)","b":[{"s":[{"p":"A correct hash table set as in lecture: buckets in an array, each a linked list; after an add, it resizes to 1.5× the buckets if the load factor is ≥ 1; hash codes are reduced with floorMod(hashCode(), M). For (a)–(c) there are N = 19 items and M = 41 buckets."}]},{"id":5,"l":[{"p":"(a) What is the current load factor? (A fraction is fine.)"}],"k":"blank","a":["19/41","19 / 41","0.463","0.46"],"topics":["HASHING"],"part":"a"},{"id":6,"l":[{"p":"(b) A user calls contains. What is the minimum number of times contains calls equals? (Assume nothing about the distribution.)"}],"k":"blank","a":["0"],"topics":["HASHING"],"part":"b"},{"id":7,"l":[{"p":"(b) …and the maximum?"}],"k":"blank","a":["19"],"topics":["HASHING"],"x":"Empty bucket: 0. All 19 items in the searched bucket: 19.","part":"b"},{"id":8,"l":[{"p":"(c) What is the minimum number of add calls that can cause the next resize?"}],"k":"blank","a":["22"],"topics":["HASHING"],"part":"c"},{"id":9,"l":[{"p":"(c) …and the maximum?"}],"k":"blank","a":["22"],"topics":["HASHING"],"x":"The load factor reaches 1 at 41 items: 22 more adds, however they’re distributed.","part":"c"},{"s":[{"p":"(d) ExamOomage has four int fields r, g, b, a, each in [0, 255], a correct equals, and a hashCode that returns some integer (of unknown quality). A timing experiment adds N random ExamOomages to the hash set:"},{"c":"public static void timingTest(int N) {\n    Stopwatch sw = new Stopwatch();\n    Problem2HashSet<ExamOomage> hsp = new Problem2HashSet<>();\n    for (int i = 0; i < N; i += 1) {\n        hsp.add(ExamOomage.randomPoint()); // returns ExamOomage with random r/g/b/a in [0, 255]\n    }\n    System.out.println(sw.elapsedTime());\n}","lang":"java"},{"c":"N = 1000   : 0.026 seconds\nN = 10000  : 1.00 seconds\nN = 49123  : 26.96 seconds\nN = 100000 : 118.43 seconds","lang":"txt"}]},{"id":10,"l":[{"p":"(d) Which best matches the average time per add?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N²)","Θ(2ᴺ)"],"a":2,"topics":["ASYMPTOTICS","HASHING"],"x":"10× more items takes about 100× longer in total, so each add costs Θ(N).","part":"d"},{"id":11,"l":[{"p":"(e) Give the body of a hashCode() that would produce timings like these."}],"k":"blank","a":["return 1","return 0","return 2","return -1","return 42"],"topics":["ASYMPTOTICS","HASHING"],"x":"Any constant puts every item in one bucket. (Any return of a single constant is right.)","part":"e"}],"topics":null},{"id":"61b-sp19-mt2/3","n":"3","t":"3. KdTree (54 pts)","b":[{"s":[{"p":"The k-d tree below: A(4, 5) splits on x, with left child B(2, 11) and right child E(6, 3), which split on y. B’s down child is C(3, 3) and up child D(1, 12); E’s down child is F(7, 2) and up child G(7, 6). C, D, F and G split on x."}]},{"id":12,"l":[{"p":"(a) What is the result of nearest(new Point(2, 2))?"}],"k":"mc","o":["A (4, 5)","B (2, 11)","C (3, 3)","D (1, 12)","E (6, 3)","F (7, 2)","G (7, 6)"],"a":2,"topics":["K_D_TREES"],"part":"a"},{"id":13,"l":[{"p":"(b) For nearest(new Point(2, 2)), which child of A is the “good child” that should definitely be explored?"}],"k":"mc","o":["B","E"],"a":0,"topics":["K_D_TREES"],"x":"A splits on x, and 2 < 4, so the left side is the good child.","part":"b"},{"id":14,"l":[{"p":"(c) Without exploring A’s children, what is the closest possible point to (2, 2) that could exist in A.right, based only on how A partitions the space? Give it as x, y."}],"k":"blank","a":["4, 2","(4, 2)","4 2"],"topics":["K_D_TREES"],"x":"A.right holds x ≥ 4; the closest such point is straight across: (4, 2).","part":"c"},{"id":15,"l":[{"p":"(d) In what order are the vertices visited to complete the call from (a)? Leave out nodes that are pruned. (The first is A.)"}],"k":"blank","a":["A, B, C","A B C"],"topics":["K_D_TREES"],"x":"After C at distance √2, D’s side (y ≥ 11) and all of A.right (at least distance 2 away) are pruned.","part":"d"},{"id":16,"l":[{"p":"(e) If we added the point (5, 1) to the tree above, where would it go?"}],"k":"mc","o":["C.left","C.right","D.left","D.right","F.left","F.right","G.left","G.right"],"a":4,"topics":["K_D_TREES"],"x":"x 5 ≥ 4: go right to E; y 1 < 3: go down to F; x 5 < 7: F’s left.","part":"e"}],"topics":null},{"id":"61b-sp19-mt2/4","n":"4","t":"4. LLRBs (46 pts)","b":[{"s":[{"p":"The LLRB below (links labeled red are red; the others are black):"},{"c":"           25\n      red /  \\\n        17    43\n       /  \\   / red\n     13   22 39","lang":"txt"}]},{"id":17,"l":[{"p":"(a) If we add 15, what single LLRB operation do we need? Write it like rotateLeft(X), rotateRight(X) or colorFlip(X)."}],"k":"blank","a":["rotateLeft(13)","RotateLeft(13)"],"topics":["RED_BLACK_TREES"],"x":"15 becomes a red right child of 13.","part":"a"},{"id":18,"l":[{"p":"(b) Starting from the original LLRB (without 15), what operations do we need if we add 40? List them in order."}],"k":"blank","a":["rotateLeft(39), rotateRight(43), colorFlip(40), colorFlip(25)","rotateLeft(39)\nrotateRight(43)\ncolorFlip(40)\ncolorFlip(25)","rotateLeft(39) rotateRight(43) colorFlip(40) colorFlip(25)","RotateLeft(39), RotateRight(43), ColorFlip(40), ColorFlip(25)","RotateLeft(39)\nRotateRight(43)\nColorFlip(40)\nColorFlip(25)","RotateLeft(39) RotateRight(43) ColorFlip(40) ColorFlip(25)"],"topics":["RED_BLACK_TREES"],"x":"40 is a red right child of red 39: rotateLeft(39) gives 43–40–39 leaning left twice, so rotateRight(43); 40 then has two red children, so colorFlip(40); that makes 40 red next to red 17, so colorFlip(25).","part":"b"},{"id":19,"l":[{"p":"(c) In the 2-3 tree corresponding to the original LLRB, what keys are in the root? (Separate them with commas.)"}],"k":"blank","a":["17, 25","17 25"],"topics":["RED_BLACK_TREES"],"part":"c"},{"id":20,"l":[{"p":"(c) …and in the rightmost leaf?"}],"k":"blank","a":["39, 43","39 43"],"topics":["RED_BLACK_TREES"],"x":"The 2-3 tree is [17 25] with children [13], [22] and [39 43].","part":"c"}],"topics":null},{"id":"61b-sp19-mt2/6","n":"6","t":"6. WQUzaaaaaaaaaaaaaaaaaaaaapp (24 pts)","b":[{"s":[{"p":"For each figure, could a sequence of at most 4 Weighted Quick Union union calls (without path compression) produce it, starting with everything disconnected? If two trees have the same weight, the first argument’s root goes below the second’s. (The exam asked for the calls when possible.)"},{"c":"Figure 1:  0( 1(2), 3(4) )\nFigure 2:  0( 1, 2, 3(4) )\nFigure 3:  0( 1(2(3)), 4 )","lang":"txt"}]},{"id":21,"l":[{"p":"Figure 1"}],"k":"mc","o":["Possible","Not possible"],"a":1,"topics":["DISJOINT_SETS"],"x":"0 would have to end up as the root above two size-2 trees, but a lone 0 (size 1) always goes under the bigger tree it joins."},{"id":22,"l":[{"p":"Figure 2"}],"k":"mc","o":["Possible","Not possible"],"a":0,"topics":["DISJOINT_SETS"],"x":"For example union(0, 1), union(0, 2), union(3, 4), union(3, 0)."},{"id":23,"l":[{"p":"Figure 3"}],"k":"mc","o":["Possible","Not possible"],"a":1,"topics":["DISJOINT_SETS"],"x":"A WQU of height 3 needs at least 8 items."}],"topics":null},{"id":"61b-sp19-mt2/7","n":"7","t":"7. Shortest Paths (40 pts)","b":[{"s":[{"p":"We run Dijkstra’s algorithm from vertex 0 on this directed graph:"},{"c":"0 → 3   1      0 → 4   4      3 → 7   1\n4 → 2   1      4 → 6   2      6 → 2   3\n6 → 1   20     6 → 5   1      1 → 2   9\n1 → 0   8      2 → 0   5      2 → 5   3\n5 → 7   3","lang":"txt"},{"p":"Right after vertex 2’s edges have been relaxed: distTo is 0, ∞, 5, 1, 4, 8, 6, 2 and edgeTo is -, -, 4, 0, 0, 2, 4, 3 (for vertices 0 to 7)."}]},{"id":24,"l":[{"p":"(a) In what order were the vertices visited? (2 was last.)"}],"k":"blank","a":["0, 3, 7, 4, 2","0 3 7 4 2"],"topics":["SHORTEST_PATHS"],"part":"a"},{"id":25,"l":[{"p":"(b) What vertex will be visited next?"}],"k":"blank","a":["6"],"topics":["SHORTEST_PATHS"],"part":"b"},{"id":26,"l":[{"p":"(c) Give the distTo array (vertices 0 to 7) after the next vertex is visited and its edges relaxed."}],"k":"blank","a":["0, 26, 5, 1, 4, 7, 6, 2","0 26 5 1 4 7 6 2"],"topics":["SHORTEST_PATHS"],"x":"Visiting 6 (distance 6) improves 1 to 6 + 20 = 26 and 5 to 6 + 1 = 7.","part":"c"},{"id":27,"l":[{"p":"(d) If all the edges were undirected, how many edges would be in the minimum spanning tree?"}],"k":"blank","a":["7"],"topics":["SHORTEST_PATHS","MSTS"],"x":"8 vertices, so 7 edges.","part":"d"}],"topics":null},{"id":"61b-sp19-mt2/8","n":"8","t":"8. Les Visiteurs (56 pts)","b":[{"s":[{"p":"The tree 10(9(1, -), 3(2, 5)) is made of TreeNodes. A visitor generalizes “visiting” a node during a traversal:"},{"c":"public class TreeNode {\n    public TreeNode left;\n    public TreeNode right;\n    public int item;\n    ...\n}\n\ninterface Visitor {\n    void visit(TreeNode x);\n}\n\nstatic void preorder(TreeNode n, Visitor v) {\n    if (n == null) { return; }\n    v.visit(n);\n    preorder(n.left, v);\n    preorder(n.right, v);\n}\n\nstatic void inorder(TreeNode n, Visitor v) {\n    if (n == null) { return; }\n    inorder(n.left, v);\n    v.visit(n);\n    inorder(n.right, v);\n}\n\nclass Printer implements Visitor {\n    public void visit(TreeNode x) {\n        System.out.print(x.item + \" \");\n    }\n}\n\nclass Adder implements Visitor {\n    public void visit(TreeNode x) {\n        if (x.left != null) { x.item += x.left.item; }\n        if (x.right != null) { x.item += x.right.item; }\n    }\n}\n\nclass GlorpGlorp implements Visitor {\n    Printer printer = new Printer();\n    public void visit(TreeNode x) {\n        TreeNode.inorder(x, printer);\n    }\n}","lang":"java"}]},{"id":28,"l":[{"p":"(a) What does a preorder traversal with a Printer print?"}],"k":"blank","a":["10 9 1 3 2 5","10, 9, 1, 3, 2, 5"],"topics":["TREE_TRAVERSALS"],"part":"a"},{"id":29,"l":[{"p":"(b) After an inorder traversal with an Adder, what are the tree’s values in preorder (the shape is unchanged)?"}],"k":"blank","a":["23 10 1 10 2 5","23, 10, 1, 10, 2, 5"],"topics":["TREE_TRAVERSALS"],"x":"In order: 1 stays 1; 9 becomes 10; 10 becomes 10 + 10 + 3 = 23 (3 hasn’t been visited yet); 2 stays; 3 becomes 3 + 2 + 5 = 10; 5 stays.","part":"b"},{"id":30,"l":[{"p":"(c) On the original tree, what does TreeNode.preorder(n, new GlorpGlorp()) print?"}],"k":"blank","a":["1 9 10 2 3 5 1 9 1 2 3 5 2 5","1, 9, 10, 2, 3, 5, 1, 9, 1, 2, 3, 5, 2, 5"],"topics":["TREE_TRAVERSALS"],"x":"Each node visited in preorder prints its whole subtree in order: 10’s, then 9’s, then 1’s, 3’s, 2’s and 5’s.","part":"c"},{"s":[{"p":"(d) Treat the original tree as a graph. DFS from 5, visiting the smallest neighbor first."}]},{"id":31,"l":[{"p":"(d) DFS preorder"}],"k":"blank","a":["5 3 2 10 9 1","5, 3, 2, 10, 9, 1"],"topics":["TREE_TRAVERSALS"],"part":"d"},{"id":32,"l":[{"p":"(d) DFS postorder"}],"k":"blank","a":["2 1 9 10 3 5","2, 1, 9, 10, 3, 5"],"topics":["TREE_TRAVERSALS"],"part":"d"}],"topics":null},{"id":"61b-sp19-mt2/9","n":"9","t":"9. Heaping (35 pts)","b":[{"s":[{"p":"(a) Write sink for a heap stored as a tree of TreeNodes. TreeNode.min(a, b) returns the node with the smaller item (ties arbitrary), null if both are null, or the non-null one if only one is null."},{"c":"public static void sink(TreeNode n) {\n    if (n == null) { return; }\n    ⟪a⟫;\n    if (minN == null) {\n        return;\n    }\n    if (⟪b⟫) {\n        ⟪c⟫\n    }\n}","lang":"java","f":{"a":"TreeNode minN = min(n.left, n.right)","b":"n.item > minN.item","c":"int temp = n.item;\nn.item = minN.item;\nminN.item = temp;\nsink(minN);"}}]},{"id":33,"l":[{"p":"(a) First blank"}],"k":"blank","a":["TreeNode minN = min(n.left, n.right)"],"topics":["HEAPS"],"part":"a"},{"id":34,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["n.item > minN.item","minN.item < n.item"],"topics":["HEAPS"],"part":"a"},{"id":35,"l":[{"p":"(a) Inside the if (swap the items, then keep sinking; several lines)"}],"k":"blank","a":["int temp = n.item;\nn.item = minN.item;\nminN.item = temp;\nsink(minN);","int temp = minN.item;\nminN.item = n.item;\nn.item = temp;\nsink(minN);"],"topics":["HEAPS"],"x":"If the smaller child is smaller than n, swap their items and keep sinking from the child.","part":"a"},{"id":36,"l":[{"p":"(b) A SinkVisitor’s visit calls sink(x). For which complete 4-node tree does TreeNode.preorder(n, new SinkVisitor()) not result in a heap?"}],"k":"mc","o":["1(2(0), 3)","0(1(2), 3)","3(2(1), 0)","2(3(1), 0)"],"a":0,"topics":["HEAPS"],"x":"Preorder sinks the root first, while 0 is still hidden below 2; 0 then only rises to the root’s child, under 1.","part":"b"}],"topics":null},{"id":"61b-sp19-mt2/10","n":"10","t":"10. Asymptotics (84 pts)","b":[{"s":[{"p":"(a) Give the runtime of each function in Θ notation."},{"c":"public static void g1(int N) {\n    for (int i = 0; i < N; i += 3) {\n        for (int j = 0; j < i; j += 1) {\n            System.out.print(\"ca3\");\n        }\n    }\n}\n\npublic static void g2(int N) { // ASSUME N IS A POWER OF 2.\n    for (int i = 0; i < N; i = i * 2) {\n        g2(i);\n    }\n    System.out.print(\"power egg\");\n}\n\npublic static void g3(int N) {\n    int j = N / 2;\n    for (int i = 0; i < j; i += 4) {\n        for (j = 0; j < N; j += 1) {\n            System.out.print(\"moo\");\n        }\n    }\n}\n\npublic static void g4(ArrayList<Integer> x) {\n    int N = x.size(); // size takes constant time\n    if (N == 1) { System.out.println(x.get(0)); return; }\n\n    // subListCopy(P, Q) returns a copy of the list from [P, Q),\n    // i.e. exclusive of Q, and takes Θ(Q - P) time.\n    ArrayList<Integer> leftHalf = x.subListCopy(0, N / 2);\n    ArrayList<Integer> rightHalf = x.subListCopy(N / 2, N);\n\n    g4(leftHalf);\n    g4(rightHalf);\n\n    for (int i = 0; i < N; i += 1) {\n        System.out.println(x.get(i)); // get takes constant time\n    }\n}","lang":"java"}]},{"id":37,"l":[{"p":"(a) g1"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"part":"a"},{"id":38,"l":[{"p":"(a) g2"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":2,"topics":["ASYMPTOTICS"],"also":[8],"x":"The staff answer is Θ(N), reading the loop as starting at i = 1: g2(N) then calls g2(1), g2(2), …, g2(N/2), which adds up to Θ(N). As printed, i starts at 0 and 0 * 2 is still 0, so the loop never ends; this site accepts that answer too.","part":"a"},{"id":39,"l":[{"p":"(a) g3"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"x":"The inner loop reuses j and leaves it at N, so the outer loop keeps going while i < N: about N/4 passes of N steps each.","part":"a"},{"id":40,"l":[{"p":"(a) g4"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":3,"topics":["ASYMPTOTICS"],"x":"Linear work per call plus two half-size calls, like mergesort.","part":"a"},{"s":[{"p":"(b) Using the number of values copied as the cost model: an AList starts with 1 slot and doubles whenever an added item doesn’t fit. For example, the 3rd add resizes from 2 to 4 and copies 2 values."}]},{"id":41,"l":[{"p":"(b) i) How many values are copied on each of the first 16 adds? (16 numbers, separated by commas; the first four are 0, 1, 2, 0.)"}],"k":"blank","a":["0, 1, 2, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0","0 1 2 0 4 0 0 0 8 0 0 0 0 0 0 0"],"topics":["ARRAYS"],"part":"b"},{"id":42,"l":[{"p":"(b) ii) Let C_d(N) be the total copies for N adds with doubling (e.g. C_d(4) = 3). C_d(N) is…"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":2,"topics":["ARRAYS","ASYMPTOTICS"],"part":"b"},{"id":43,"l":[{"p":"(b) iii) Now the AList starts with 1 slot and grows by 3 whenever an added item doesn’t fit (e.g. the 5th add resizes from 4 to 7 and copies 4). How many values are copied on each of the first 16 adds? (The first five are 0, 1, 0, 0, 4.)"}],"k":"blank","a":["0, 1, 0, 0, 4, 0, 0, 7, 0, 0, 10, 0, 0, 13, 0, 0","0 1 0 0 4 0 0 7 0 0 10 0 0 13 0 0"],"topics":["ARRAYS"],"part":"b"},{"id":44,"l":[{"p":"(b) iv) Let C_a3(N) be the total copies for N adds when growing by 3 (e.g. C_a3(5) = 5). C_a3(N) is…"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(2ᴺ)","Never terminates (infinite loop)"],"a":4,"topics":["ARRAYS","ASYMPTOTICS"],"x":"This is the same pattern as g1 (that’s why it prints “ca3”): copies of 1, 4, 7, 10, … add up to Θ(N²).","part":"b"}],"topics":null},{"id":"61b-sp19-mt2/11","n":"11","t":"11. Yggdrasil (60 pts)","b":[{"s":[{"p":"(Staff called this a very challenging problem.) Write heapToBBST(k, h), which removes the k smallest values from the min-heap h (made of TreeNodes) and returns them as a perfectly balanced BST, in place (reusing the heap’s TreeNodes), in O(N log N) time and O(log N) extra memory. For example, with a heap holding 4, 6, 7, 8, 9, 10, 11, 12, 13, heapToBBST(7, h) returns 8(6(4, 7), 10(9, 11)) and leaves 12 and 13 in the heap. MinHeap’s instance variables are private; it has removeMin(), which removes and returns the minimum node."},{"c":"public static TreeNode heapToBBST(int k, MinHeap h) {\n    if (k == 0) {\n        return null;\n    }\n    ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n    ⟪d⟫;\n    ⟪e⟫;\n    return middle;\n}","lang":"java","f":{"a":"TreeNode left = heapToBBST(k / 2, h)","b":"TreeNode middle = h.removeMin()","c":"TreeNode right = heapToBBST(k - (k / 2) - 1, h)","d":"middle.left = left","e":"middle.right = right"}}]},{"id":45,"l":[{"p":"First line"}],"k":"blank","a":["TreeNode left = heapToBBST(k / 2, h)","TreeNode left = heapToBBST(k/2, h)"],"topics":["BSTS","HEAPS"]},{"id":46,"l":[{"p":"Second line"}],"k":"blank","a":["TreeNode middle = h.removeMin()"],"topics":["BSTS","HEAPS"]},{"id":47,"l":[{"p":"Third line"}],"k":"blank","a":["TreeNode right = heapToBBST(k - (k / 2) - 1, h)","TreeNode right = heapToBBST(k - k / 2 - 1, h)"],"topics":["BSTS","HEAPS"]},{"id":48,"l":[{"p":"Fourth line"}],"k":"blank","a":["middle.left = left"],"topics":["BSTS","HEAPS"]},{"id":49,"l":[{"p":"Fifth line"}],"k":"blank","a":["middle.right = right"],"topics":["BSTS","HEAPS"],"x":"Build the left subtree from the k/2 smallest values first, then the next value is the root, then the right subtree from the rest. Removing them in this order hands out values in sorted order."}],"topics":null}],"by":["Hug"]},{"id":"61b-sp21-final","t":"Spring 2021 Final","src":{"exam":"https://drive.google.com/file/d/17OByvIiASNi_JSzl-20Gawtxvsjopi0y/view","sol":"https://drive.google.com/file/d/16kmm6B3OvQsIvPsPnCrNgiWeFeOJd8tk/view","topics":"sp21-final"},"p":[{"id":"61b-sp21-final/2","n":"2","t":"2. Heaps (185 pts)","b":[{"id":1,"l":[{"p":"(1a) Worst-case runtime to find the minimum item in a min-heap array?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":0,"topics":["HEAPS"],"topicsBy":"site"},{"id":2,"l":[{"p":"(1b) Worst-case runtime to find the maximum item in a min-heap array?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["HEAPS"],"topicsBy":"site"},{"id":3,"l":[{"p":"(1c) Worst-case runtime to find the second-smallest item in a min-heap array?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":0,"topics":["HEAPS"],"topicsBy":"site"},{"s":[{"p":"The heap contains N strings of length N. Comparing two strings is character by character and may inspect Θ(N) characters. The backing array does not resize."}]},{"id":4,"l":[{"p":"(2a) Best-case time to insert another length-N string"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(2ᴺ)"],"a":0,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":5,"l":[{"p":"(2b) Worst-case time to insert another length-N string"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(2ᴺ)"],"a":3,"topics":["HEAPS","ASYMPTOTICS"],"topicsBy":"site"},{"id":6,"l":[{"p":"(3) Maximum size of a tree that is both a BST and either a min-heap or max-heap; answer inf if unbounded"}],"k":"blank","a":["2"],"topics":["HEAPS","BSTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp21-final/3","n":"3","t":"3. Trees (570 pts)","b":[{"id":7,"l":[{"p":"(1) For a 1-based array representation of a complete trinary tree, what is the rightmost child index of node i?"}],"k":"mc","o":["3i - 1","3i","3i + 1","2i + 1","i² - 1","i² + 1"],"a":2,"topics":["HEAPS"],"topicsBy":"site"},{"s":[{"p":"The WeightedQuickUnion parent array is [1, 2, -3, -1]. Negative values at roots encode the negative tree size."}]},{"id":8,"l":[{"p":"(2a) Why is this not a valid WeightedQuickUnion array?"}],"k":"mc","o":["It has a cycle.","The actual weight of the tree rooted at 2 does not match its listed weight.","The actual weight of the tree rooted at 3 does not match its listed weight.","Its height is impossibly large given the set weights."],"a":2,"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":9,"l":[{"p":"(2b) Interpreted as a 0-based complete binary tree [1,2,-3,-1], why is it not a BST?"}],"k":"mc","o":["It contains negative numbers.","2 should not be the left child of 1.","2 should not be the left child of -3.","The root is not the median value."],"a":1,"topics":["BSTS"],"topicsBy":"site"},{"id":10,"l":[{"p":"(2c) Interpreted as a 0-based complete binary tree [1,2,-3,-1], why is it not a max heap?"}],"k":"mc","o":["It contains negative numbers.","-1 should not be below 2.","-3 should not be below 1.","The root is not the maximum value."],"a":3,"topics":["HEAPS"],"topicsBy":"site"},{"s":[{"p":"For (2d–e), the 0-based array is [1, -2, 3, -4, -1, x, 5]."}]},{"id":11,"l":[{"p":"(2d) Choose integer x making the array a valid BST"}],"k":"blank","a":["2"],"topics":["BSTS"],"topicsBy":"site"},{"id":12,"l":[{"p":"(2e) Choose integer x making the array a valid WeightedQuickUnion parent array"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"s":[{"p":"For (2f–g), the 0-based array is [-1, -1, x, -1]."}]},{"id":13,"l":[{"p":"(2f) Choose integer x making the array a valid max heap"}],"k":"blank","a":["-1"],"topics":["HEAPS"],"topicsBy":"site"},{"id":14,"l":[{"p":"(2g) Choose integer x making the array a valid WeightedQuickUnion parent array"}],"k":"blank","a":["-1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":15,"l":[{"p":"(3a) Can any binary tree of comparable items be transformed into a BST using only rotations?"}],"k":"mc","o":["True","False"],"a":1,"topics":["BSTS"],"topicsBy":"site"},{"id":16,"l":[{"p":"(3b) Number of unique BSTs of height 2 containing 1 through 7"}],"k":"blank","a":["1"],"topics":["BSTS"],"topicsBy":"site"},{"id":17,"l":[{"p":"(3c) Nodes at level 3 in a heap after 8 insertions (root at level 0)"}],"k":"blank","a":["1"],"topics":["HEAPS"],"topicsBy":"site"},{"id":18,"l":[{"p":"(3d) Nodes at level 3 in a heap after 12,329 insertions"}],"k":"blank","a":["8"],"topics":["HEAPS"],"topicsBy":"site"},{"id":19,"l":[{"p":"(3e) Do WeightedQuickUnion and HeightedQuickUnion always create the same tree for the same operations and tie-breaking?"}],"k":"mc","o":["True","False"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":20,"l":[{"p":"(3f) Maximum height of a fully connected WeightedQuickUnion with 8 elements"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp21-final/4","n":"4","t":"4. Finding the Shortest Path (125 pts)","b":[{"s":[{"p":"Directed weighted graph: S→A (10), S→B (1), B→C (3), C→A (2), C→D (8), B→F (15), D→F (2), F→E (8), E→S (3). Break ties alphabetically. Dijkstra’s PQ initially contains every vertex, with infinity priority except S."},{"p":"After visiting C and relaxing its outgoing edges, report each vertex’s priority (inf if infinite, none if already removed)."}]},{"id":21,"l":[{"p":"(a) Priority of S"}],"k":"blank","a":["none"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":22,"l":[{"p":"(a) Priority of A"}],"k":"blank","a":["6"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":23,"l":[{"p":"(a) Priority of B"}],"k":"blank","a":["none"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":24,"l":[{"p":"(a) Priority of C"}],"k":"blank","a":["none"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":25,"l":[{"p":"(a) Priority of D"}],"k":"blank","a":["12"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":26,"l":[{"p":"(a) Priority of E"}],"k":"blank","a":["inf"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":27,"l":[{"p":"(a) Priority of F"}],"k":"blank","a":["16"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"a"},{"id":28,"l":[{"p":"(b) Dijkstra pop order from S, comma separated"}],"k":"blank","a":["S,B,C,A,D,F,E"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"b"}],"topics":null},{"id":"61b-sp21-final/5","n":"5","t":"5. Subsequences (240 pts)","b":[{"s":[{"p":"Sort [652, 135, 101, 383, 495, 651] using insertion sort, selection sort, leftmost-pivot Hoare quicksort without shuffling, or bottom-up max-heapsort. A partial state may occur even midway through an operation. Choose every algorithm that can yield each listed prefix."}]},{"id":29,"l":[{"p":"(1a) State prefix [652, 495, 651, ...]"}],"k":"sata","o":["Insertion sort","Selection sort","Quicksort","Heapsort","None"],"a":[3],"topics":["SORTING"],"topicsBy":"site"},{"id":30,"l":[{"p":"(1b) State prefix [101, 135, 652, ...]"}],"k":"sata","o":["Insertion sort","Selection sort","Quicksort","Heapsort","None"],"a":[0,1],"topics":["SORTING"],"topicsBy":"site"},{"id":31,"l":[{"p":"(1c) State prefix [135, 101, 652, ...]"}],"k":"sata","o":["Insertion sort","Selection sort","Quicksort","Heapsort","None"],"a":[4],"topics":["SORTING"],"topicsBy":"site"},{"s":[{"p":"The full state [383, 135, 101, 495, 651, 652] occurs in both quicksort and heapsort on this input."}]},{"id":32,"l":[{"p":"(2a) Number of completed quicksort partition operations when this state occurs"}],"k":"mc","o":[0,1,2,3,4,5,6,7],"a":3,"topics":["SORTING"],"topicsBy":"site"},{"id":33,"l":[{"p":"(2b) Number of completed heapsort deletion operations when this state occurs"}],"k":"mc","o":[0,1,2,3,4,5,6,7],"a":3,"topics":["SORTING","HEAPS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp21-final/6","n":"6","t":"6. MapDeque (240 pts)","b":[{"s":[{"p":"Implement a Deque backed by Map<Integer,T>, using integer positions as keys. Do not use a List. Initialize first and last so the empty map has size zero, adding at either end updates its position, and removal deletes and returns the appropriate item."},{"c":"public class MapDeque<T> implements Deque<T> {\n  private Map<Integer, T> items;\n  private int first; // ⟪a⟫\n  private int last;  // ⟪b⟫\n  public MapDeque() {\n    items = new HashMap<>();\n    first = ⟪c⟫;\n    last = ⟪d⟫;\n  }\n  public int size() { return ⟪e⟫; }\n  public void addLast(T item) { ⟪f⟫; ⟪g⟫; }\n  public void addFirst(T item) { ⟪h⟫; ⟪i⟫; }\n  public T removeFirst() {\n    if (size() <= 0) throw new NoSuchElementException();\n    ⟪j⟫; T toRet = items.remove(first); return ⟪k⟫;\n  }\n  public T removeLast() {\n    if (size() <= 0) throw new NoSuchElementException();\n    ⟪l⟫; T toRet = items.remove(last); return ⟪m⟫;\n  }\n}","lang":"java","f":{"a":"0","b":"1","c":"0","d":"1","e":"items.size()","f":"items.put(last, item)","g":"last += 1","h":"items.put(first, item)","i":"first -= 1","j":"first += 1","k":"toRet","l":"last -= 1","m":"toRet"}}]},{"id":34,"l":[{"p":"(a) Initial first"}],"k":"blank","a":["0"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"a"},{"id":35,"l":[{"p":"(b) Initial last"}],"k":"blank","a":["1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"b"},{"id":36,"l":[{"p":"(c) Constructor first"}],"k":"blank","a":["0"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"c"},{"id":37,"l":[{"p":"(d) Constructor last"}],"k":"blank","a":["1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"d"},{"id":38,"l":[{"p":"(e) Size"}],"k":"blank","a":["items.size()"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"e"},{"id":39,"l":[{"p":"(f) Store at back"}],"k":"blank","a":["items.put(last, item)"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"f"},{"id":40,"l":[{"p":"(g) Advance back index"}],"k":"blank","a":["last += 1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"g"},{"id":41,"l":[{"p":"(h) Store at front"}],"k":"blank","a":["items.put(first, item)"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"h"},{"id":42,"l":[{"p":"(i) Decrement front index"}],"k":"blank","a":["first -= 1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"i"},{"id":43,"l":[{"p":"(j) Advance front before removal"}],"k":"blank","a":["first += 1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"j"},{"id":44,"l":[{"p":"(k) Return removed front value"}],"k":"blank","a":["toRet"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"k"},{"id":45,"l":[{"p":"(l) Decrement back before removal"}],"k":"blank","a":["last -= 1"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"l"},{"id":46,"l":[{"p":"(m) Return removed back value"}],"k":"blank","a":["toRet"],"topics":["DEQUES","HASHING","JAVA"],"topicsBy":"site","part":"m"}],"topics":null},{"id":"61b-sp21-final/7","n":"7","t":"7. MSTs (180 pts)","b":[{"s":[{"p":"Undirected weighted graph. Spokes SA, SB, SC, SD have weight 1; outer cycle WX, XZ, YZ, WY also has weight 1. Inner edges AB, AC, BD, CD and connectors WA, XB, YC, ZD have weight 2. Ties can be broken arbitrarily."}]},{"id":47,"l":[{"p":"(a) Which edges could be the last edge Kruskal adds to an MST?"}],"k":"sata","o":["SA","SB","SC","SD","AB","AC","BD","CD","WA","XB","YC","ZD","WX","XZ","WY","YZ"],"a":[8,9,10,11],"topics":["MSTS"],"topicsBy":"site","part":"a"},{"id":48,"l":[{"p":"(b) Which edges could be the last edge Prim adds to an MST starting from S?"}],"k":"sata","o":["SA","SB","SC","SD","AB","AC","BD","CD","WA","XB","YC","ZD","WX","XZ","WY","YZ"],"a":[12,13,14,15],"topics":["MSTS"],"topicsBy":"site","part":"b"},{"id":49,"l":[{"p":"(c) Number of valid MSTs"}],"k":"blank","a":["16"],"topics":["MSTS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp21-final/8","n":"8","t":"8. Left-Leaning Red-Black Trees (160 pts)","b":[{"id":50,"l":[{"p":"(a) Starting with node A and inserting M as a red right child, which rotation restores left-leaning form?"}],"k":"mc","o":["rotateLeft(A)","rotateRight(A)","rotateLeft(M)","rotateRight(M)"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"a"},{"s":[{"p":"Then insert B into the resulting tree with M at the root and A as its red left child."}]},{"id":51,"l":[{"p":"(b) Which resulting LLRB shape/coloring is correct?"}],"k":"mc","o":["Root B black with red children A and M (diagram a)","Root B black with black children A and M (diagram b)","M root, red A child with red B grandchild (diagram c)","M root, red B child with red A grandchild (diagram d)","M root, B black with A black (diagram e)","M root black with B red and A red (diagram f)"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"b"},{"id":52,"l":[{"p":"(c) Operation 1"}],"k":"mc","o":["rotateLeft()","rotateRight()","colorFlip()","None"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":53,"l":[{"p":"(c) Node for operation 1"}],"k":"mc","o":["A","B","M","None"],"a":0,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":54,"l":[{"p":"(c) Operation 2"}],"k":"mc","o":["rotateLeft()","rotateRight()","colorFlip()","None"],"a":1,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":55,"l":[{"p":"(c) Node for operation 2"}],"k":"mc","o":["A","B","M","None"],"a":2,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":56,"l":[{"p":"(c) Operation 3"}],"k":"mc","o":["rotateLeft()","rotateRight()","colorFlip()","None"],"a":2,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"},{"id":57,"l":[{"p":"(c) Node for operation 3"}],"k":"mc","o":["A","B","M","None"],"a":1,"topics":["RED_BLACK_TREES"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp21-final/9","n":"9","t":"9. Palindromic Tries (330 pts)","b":[{"s":[{"p":"For the collection [madam, ada, wow, dadad, huh, adamada], a centered subpalindrome is an odd-length palindromic substring that shares the middle character of the containing string."}]},{"id":58,"l":[{"p":"(a) Which strings have “ada” as a centered subpalindrome?"}],"k":"sata","o":["madam","ada","wow","dadad","huh","adamada","None"],"a":[0,1,3],"topics":["TRIES"],"topicsBy":"site","part":"a"},{"s":[{"p":"A PalindromicTrie stores odd-length palindromes. insert(str) takes Θ(L). numCenteredSubPalindromes(subStr) should take Θ(K) for subStr length K and be independent of how many strings match."}]},{"id":59,"l":[{"p":"(b) Add one TrieNode field that supports the query"}],"k":"blank","a":["private int numWordsBelow;"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"b"},{"s":[{"c":"public int numCenteredSubPalindromes(String subStr) {\n  if (!isOddLengthPalindrome(subStr)) throw new IllegalArgumentException();\n  return numCenteredSubPalindromesHelper(root, subStr, ⟪a⟫);\n}\nprivate int numCenteredSubPalindromesHelper(TrieNode node, String subStr, int index) {\n  if (⟪b⟫) return 0;\n  if (⟪c⟫) return ⟪d⟫;\n  TrieNode toCall = node.children.getOrDefault(⟪e⟫, null);\n  return numCenteredSubPalindromesHelper(⟪f⟫, subStr, ⟪g⟫);\n}","lang":"java","f":{"a":"subStr.length() / 2","b":"node == null","c":"index == subStr.length()","d":"node.numWordsBelow","e":"subStr.charAt(index)","f":"toCall","g":"index + 1"}}]},{"id":60,"l":[{"p":"(c) Initial index"}],"k":"blank","a":["subStr.length() / 2"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":61,"l":[{"p":"(c) Missing-node base case"}],"k":"blank","a":["node == null"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":62,"l":[{"p":"(c) End-of-query condition"}],"k":"blank","a":["index == subStr.length()"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":63,"l":[{"p":"(c) Return matching subtree count"}],"k":"blank","a":["node.numWordsBelow"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":64,"l":[{"p":"(c) Trie edge character"}],"k":"blank","a":["subStr.charAt(index)"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":65,"l":[{"p":"(c) Recurse on child"}],"k":"blank","a":["toCall"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"},{"id":66,"l":[{"p":"(c) Advance query index"}],"k":"blank","a":["index + 1"],"topics":["TRIES","JAVA"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp21-final/10","n":"10","t":"10. Graphs (350 pts)","b":[{"s":[{"p":"A recursive graph traversal scans every neighbor edge and uses a TreeSet (balanced red-black tree) for seen and a heap-based MinPQ. Assume comparing vertices is O(1). Express operation counts and operation costs using E, V, and logV."}]},{"id":67,"l":[{"p":"(a,b) contains calls"}],"k":"blank","a":["E"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":68,"l":[{"p":"(a,b) time per contains"}],"k":"blank","a":["logV"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":69,"l":[{"p":"(a,b) pq insert calls"}],"k":"blank","a":["V"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":70,"l":[{"p":"(a,b) time per pq insert"}],"k":"blank","a":["logV"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":71,"l":[{"p":"(a,b) seen add calls"}],"k":"blank","a":["V"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":72,"l":[{"p":"(a,b) time per seen add"}],"k":"blank","a":["logV"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":73,"l":[{"p":"(a,b) overall runtime"}],"k":"blank","a":["ElogV"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site"},{"id":74,"l":[{"p":"(c) Overall runtime if membership tests use MinPQ.contains at O(N)"}],"k":"blank","a":["EV"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp21-final/11","n":"11","t":"11. Asymptotics (190 pts)","b":[{"s":[{"p":"For f1, an array is allocated and filled in one loop from 3 through N. For z1, recursion calls z1(n/2) twice until n≤10. For z2, each call first loops n times and then makes those same two recursive calls. For z3, n≤10 returns; even n calls z3(n/2) twice; odd n calls z3(n+1)."}]},{"id":75,"l":[{"p":"(a) Runtime of f1(N)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse","Never terminates"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":76,"l":[{"p":"(b) Worst-case runtime of z1(N)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse","Never terminates"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"id":77,"l":[{"p":"(c) Worst-case runtime of z2(N)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse","Never terminates"],"a":5,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"c"},{"id":78,"l":[{"p":"(d) Best-case runtime of z3(N)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse","Never terminates"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"d"},{"id":79,"l":[{"p":"(e) Worst-case runtime of z3(N)"}],"k":"mc","o":["Θ(1)","Θ(log log N)","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse","Never terminates"],"a":4,"topics":["ASYMPTOTICS"],"topicsBy":"site","part":"e"}],"topics":null},{"id":"61b-sp21-final/12","n":"12","t":"12. Sorting Lists (620 pts)","b":[{"s":[{"p":"PosIntegerList contains positive integers and compares lexicographically from the left; if one list is a prefix of the other, the longer list is greater."},{"c":"public int compare(PosIntegerList a, PosIntegerList b) {\n  int lim = ⟪a⟫;\n  for (⟪b⟫) {\n    if (⟪c⟫) return ⟪d⟫;\n  }\n  return ⟪e⟫;\n}","lang":"java","f":{"a":"Math.min(a.size(), b.size())","b":"int i = 0; i < lim; i += 1","c":"a.get(i) != b.get(i)","d":"a.get(i) - b.get(i)","e":"a.size() - b.size()"}}]},{"id":80,"l":[{"p":"(a) Shared prefix length"}],"k":"blank","a":["Math.min(a.size(), b.size())"],"topics":["COMPARATORS","SORTING","JAVA"],"topicsBy":"site","part":"a"},{"id":81,"l":[{"p":"(a) Loop header"}],"k":"blank","a":["int i = 0; i < lim; i += 1"],"topics":["COMPARATORS","SORTING","JAVA"],"topicsBy":"site","part":"a"},{"id":82,"l":[{"p":"(a) Detect differing entries"}],"k":"blank","a":["a.get(i) != b.get(i)"],"topics":["COMPARATORS","SORTING","JAVA"],"topicsBy":"site","part":"a"},{"id":83,"l":[{"p":"(a) Compare differing entries"}],"k":"blank","a":["a.get(i) - b.get(i)"],"topics":["COMPARATORS","SORTING","JAVA"],"topicsBy":"site","part":"a"},{"id":84,"l":[{"p":"(a) Prefix tie-break"}],"k":"blank","a":["a.size() - b.size()"],"topics":["COMPARATORS","SORTING","JAVA"],"topicsBy":"site","part":"a"},{"id":85,"l":[{"p":"(b) Worst-case Mergesort time for N lists, each length M, with efficient comparison"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(M)","Θ(N+M)","Θ(NM)","Θ(N log M)","Θ(M log N)","Θ(N log N)","Θ(NM log NM)","Θ(NM log N)","Θ(NM log M)","Θ(N log N + M log M)"],"a":9,"topics":["SORTING","COMPARATORS","ASYMPTOTICS"],"topicsBy":"site","part":"b"},{"s":[{"p":"For LSD radix sort with heapsort as each stable pass, PQNode stores a list, its current digit (use 0 when the list has no digit at index i), and original order as a tie-breaker. Heap sort each digit position from right to left."},{"c":"private static class PQNode implements Comparable<PQNode> {\n  PosIntegerList il;\n  ⟪f⟫\n  ⟪g⟫\n  PQNode(PosIntegerList i, int v, int t) {\n    il = i; ⟪h⟫; ⟪i⟫;\n  }\n  public int compareTo(PQNode o) {\n    if (⟪j⟫) return ⟪k⟫;\n    return ⟪l⟫;\n  }\n}\npublic static List<PosIntegerList> heapSortLists(List<PosIntegerList> ils, int i) {\n  MinPQ<PQNode> pq = new MinPQ<>();\n  int count = 0;\n  for (PosIntegerList currentIl : ils) {\n    PQNode p;\n    if (⟪m⟫) p = ⟪n⟫;\n    else p = ⟪o⟫;\n    count += 1; pq.insert(p);\n  }\n  List<PosIntegerList> returnList = new ArrayList<>();\n  while (pq.size() != 0) returnList.add(pq.delMin().il);\n  return returnList;\n}","lang":"java","f":{"f":"int val;","g":"int tiebreak;","h":"val = v","i":"tiebreak = t","j":"val != o.val","k":"val - o.val","l":"tiebreak - o.tiebreak","m":"i >= currentIl.size()","n":"new PQNode(currentIl, 0, count)","o":"new PQNode(currentIl, currentIl.get(i), count)"}}]},{"id":86,"l":[{"p":"(c) Digit field"}],"k":"blank","a":["int val;"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":87,"l":[{"p":"(c) Stable tie-break field"}],"k":"blank","a":["int tiebreak;"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":88,"l":[{"p":"(c) Initialize digit"}],"k":"blank","a":["val = v"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":89,"l":[{"p":"(c) Initialize tie-break"}],"k":"blank","a":["tiebreak = t"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":90,"l":[{"p":"(c) Compare digits first"}],"k":"blank","a":["val != o.val"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":91,"l":[{"p":"(c) Digit ordering"}],"k":"blank","a":["val - o.val"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":92,"l":[{"p":"(c) Stable order for equal digits"}],"k":"blank","a":["tiebreak - o.tiebreak"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":93,"l":[{"p":"(c) Detect absent digit"}],"k":"blank","a":["i >= currentIl.size()"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":94,"l":[{"p":"(c) Missing digit node"}],"k":"blank","a":["new PQNode(currentIl, 0, count)"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":95,"l":[{"p":"(c) Present digit node"}],"k":"blank","a":["new PQNode(currentIl, currentIl.get(i), count)"],"topics":["SORTING","HEAPS","JAVA"],"topicsBy":"site","part":"c"},{"id":96,"l":[{"p":"(d) Worst-case runtime to LSD-heapsort N lists of length M"}],"k":"mc","o":["Θ(N)","Θ(M)","Θ(N+M)","Θ(NM)","Θ(N log M)","Θ(M log N)","Θ(N log N)","Θ(NM log NM)","Θ(NM log N)","Θ(NM log M)","Θ(N log N + M log M)"],"a":8,"topics":["SORTING","HEAPS","ASYMPTOTICS"],"topicsBy":"site","part":"d"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp21-mt1","t":"Spring 2021 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1S_Fyvyz50DFikHwMcOBcRuFGIZoQMmGK/view","sol":"https://drive.google.com/file/d/1Kal-nMvoEGD-ijt26bjtnDbwrUTfIl_K/view","topics":"sp21-mt1"},"p":[{"id":"61b-sp21-mt1/1","n":"1","t":"1. Cal Central (240 pts)","b":[{"s":[{"p":"(a) contains returns true if and only if the array a contains x (a is never null)."},{"c":"public static boolean contains(int[] a, int x) {\n    for (⟪a⟫) {\n        if (⟪b⟫) {\n            ⟪c⟫;\n        }\n    }\n    ⟪d⟫;\n}","lang":"java","f":{"a":"int i = 0; i < a.length; i += 1","b":"x == a[i]","c":"return true","d":"return false"}}]},{"id":1,"l":[{"p":"(a) Loop header"}],"k":"blank","a":["int i = 0; i < a.length; i += 1","int i = 0; i < a.length; i++"],"topics":["ARRAYS"],"part":"a"},{"id":2,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["x == a[i]","a[i] == x"],"topics":["ARRAYS"],"part":"a"},{"id":3,"l":[{"p":"(a) Inside the if"}],"k":"blank","a":["return true"],"topics":["ARRAYS"],"part":"a"},{"id":4,"l":[{"p":"(a) After the loop"}],"k":"blank","a":["return false"],"topics":["ARRAYS"],"part":"a"},{"s":[{"p":"A CourseCatalog has public int[] courses (initially new int[0]). cc.offerNewCourse(courseid) adds the course if it isn’t already in the catalog. A CalStudent has public int[] courses (length 4) and int numOfCourses. x.addCourse(courseid, cc) adds the course to the first free spot only if it’s in the catalog, the student has fewer than 4 courses, and they don’t already have it."},{"p":"(b) offerNewCourse (you may use Utils.contains):"},{"c":"public void offerNewCourse(int courseid) {\n    if (⟪e⟫) {\n        int[] newArr = new int[⟪f⟫];\n        for (⟪g⟫) {\n            ⟪h⟫;\n        }\n        ⟪i⟫;\n        ⟪j⟫;\n    }\n}","lang":"java","f":{"e":"!Utils.contains(courses, courseid)","f":"courses.length + 1","g":"int i = 0; i < courses.length; i++","h":"newArr[i] = courses[i]","i":"newArr[courses.length] = courseid","j":"courses = newArr"}}]},{"id":5,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["!Utils.contains(courses, courseid)"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"id":6,"l":[{"p":"(b) new int[____]"}],"k":"blank","a":["courses.length + 1"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"id":7,"l":[{"p":"(b) Loop header"}],"k":"blank","a":["int i = 0; i < courses.length; i++","int i = 0; i < courses.length; i += 1"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"id":8,"l":[{"p":"(b) Loop body"}],"k":"blank","a":["newArr[i] = courses[i]"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"id":9,"l":[{"p":"(b) After the loop"}],"k":"blank","a":["newArr[courses.length] = courseid"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"id":10,"l":[{"p":"(b) Last line"}],"k":"blank","a":["courses = newArr","this.courses = newArr"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"b"},{"s":[{"c":"public void addCourse(int courseid, CourseCatalog cc) {\n    if (⟪k⟫) {\n        ⟪l⟫;\n        ⟪m⟫;\n    }\n}","lang":"java","f":{"k":"numOfCourses < 4 && !Utils.contains(courses, courseid) && Utils.contains(cc.courses, courseid)","l":"this.courses[numOfCourses] = courseid","m":"numOfCourses += 1"}}]},{"id":11,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["numOfCourses < 4 && !Utils.contains(courses, courseid) && Utils.contains(cc.courses, courseid)","numOfCourses < 4 && Utils.contains(cc.courses, courseid) && !Utils.contains(courses, courseid)","Utils.contains(cc.courses, courseid) && !Utils.contains(courses, courseid) && numOfCourses < 4"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"c"},{"id":12,"l":[{"p":"(c) First line"}],"k":"blank","a":["this.courses[numOfCourses] = courseid","courses[numOfCourses] = courseid"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"c"},{"id":13,"l":[{"p":"(c) Second line"}],"k":"blank","a":["numOfCourses += 1","numOfCourses++"],"topics":["JAVA","ARRAYS","ABSTRACTION"],"part":"c"},{"id":14,"l":[{"p":"(d) One better data structure than int[] for both classes would be a List. Why?"}],"k":"mc","o":["A List grows as needed, so offerNewCourse wouldn’t have to build a new array, and it tracks its own size, so numOfCourses wouldn’t be needed.","A List can only hold unique items.","A List is always sorted.","A List uses less memory than an array."],"a":0,"topics":["LISTS","ARRAYS"],"x":"A Set, coming later in the course, would be even better.","part":"d"}],"topics":null},{"id":"61b-sp21-mt1/2","n":"2","t":"2. WWJD (120 pts)","b":[{"s":[{"c":"public class Egg {\n    public String owner;\n    public static String staticOwner;\n\n    public Egg(String name) {\n        this.owner = name;\n        staticOwner = name;\n    }\n\n    public void weirdExchange(String borrower, Egg g2) {\n        String lender = this.owner;\n        this.owner = borrower;\n        g2.owner = lender;\n        g2 = new Egg(\"Omar\");\n        System.out.println(\"g2 owner: \" + g2.owner);\n    }\n\n    public static void main(String[] args) {\n        Egg g1 = new Egg(\"Itai\");\n        Egg g2 = new Egg(\"Connor\");\n\n        String p1 = \"Linda\";\n        g1.weirdExchange(p1, g2);                              // line 23\n        System.out.println(\"g1 owner: \" + g1.owner);           // line 24\n        System.out.println(\"g2 owner: \" + g2.owner);           // line 25\n        System.out.println(\"Egg owner: \" + Egg.staticOwner);   // line 26\n    }\n}","lang":"java"}]},{"id":15,"l":[{"p":"What does line 23 print?"}],"k":"mc","o":["g2 owner: Itai","g2 owner: Connor","g2 owner: Linda","g2 owner: Omar","Error"],"a":3,"topics":["JAVA"]},{"id":16,"l":[{"p":"What does line 24 print?"}],"k":"mc","o":["g1 owner: Itai","g1 owner: Connor","g1 owner: Linda","g1 owner: Omar","Error"],"a":2,"topics":["JAVA"]},{"id":17,"l":[{"p":"What does line 25 print?"}],"k":"mc","o":["g2 owner: Itai","g2 owner: Connor","g2 owner: Linda","g2 owner: Omar","Error"],"a":0,"topics":["JAVA"],"x":"weirdExchange set the caller’s g2 object’s owner to \"Itai\" before reassigning its own parameter, which doesn’t affect main’s g2."},{"id":18,"l":[{"p":"What does line 26 print?"}],"k":"mc","o":["Egg owner: Itai","Egg owner: Connor","Egg owner: Linda","Egg owner: Omar","Error"],"a":3,"topics":["JAVA"],"x":"Every constructor sets the static staticOwner; \"Omar\" was the last."}],"topics":null},{"id":"61b-sp21-mt1/3","n":"3","t":"3. WWJDMS (120 pts)","b":[{"s":[{"c":"public interface Instrument {\n    default public String getName() {\n        return \"instrument\";\n    }\n}\n\npublic class Guitar implements Instrument {\n    public String getName() {\n        return \"guitar\";\n    }\n}\n\npublic interface Music {\n    default public void play(Instrument i) {\n        System.out.println(\"music on a \" + i.getName());\n    }\n}\n\npublic class Rock implements Music {\n    public void play(Instrument i) {\n        System.out.println(\"rock on a \" + i.getName());\n    }\n    public void play(Guitar g) {\n        System.out.println(\"RPG\");\n    }\n}\n\npublic class Jota implements Music {\n    public void play(Guitar g) {\n        System.out.println(\"JPG\");\n    }\n}\n\nInstrument i = new Guitar();\nGuitar g = new Guitar();","lang":"java"},{"p":"What does each call print? If the first line errors, ignore it and consider the second."}]},{"id":19,"l":[{"p":"(a) Rock r = new Rock(); r.play(i);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","RPG","Error"],"a":2,"topics":["DMS"],"part":"a"},{"id":20,"l":[{"p":"(a) … r.play(g);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","RPG","Error"],"a":4,"topics":["DMS"],"part":"a"},{"id":21,"l":[{"p":"(b) Music mr = new Rock(); mr.play(i);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","RPG","Error"],"a":2,"topics":["DMS"],"part":"b"},{"id":22,"l":[{"p":"(b) … mr.play(g);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","RPG","Error"],"a":2,"topics":["DMS"],"x":"mr’s static type is Music, which only has play(Instrument); Rock overrides that one.","part":"b"},{"id":23,"l":[{"p":"(c) Jota j = new Jota(); j.play(i);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","JPG","Error"],"a":3,"topics":["DMS"],"part":"c"},{"id":24,"l":[{"p":"(c) … j.play(g);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","JPG","Error"],"a":4,"topics":["DMS"],"part":"c"},{"id":25,"l":[{"p":"(d) Music mj = new Jota(); mj.play(i);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","JPG","Error"],"a":3,"topics":["DMS"],"part":"d"},{"id":26,"l":[{"p":"(d) … mj.play(g);"}],"k":"mc","o":["music on a instrument","rock on a instrument","rock on a guitar","music on a guitar","JPG","Error"],"a":3,"topics":["DMS"],"x":"Through a Music reference only play(Instrument) exists, and Jota doesn’t override it, so the default runs.","part":"d"}],"topics":null},{"id":"61b-sp21-mt1/4","n":"4","t":"4. BLList (310 pts)","b":[{"s":[{"p":"BLList<T> has addLast, get, remove(int i) and size, behaving like any list. (a) Write a JUnit test that addLast and get work, with at least 3 elements."},{"c":"@Test\npublic void testAddLastAndGet() {\n    BLList<Integer> b = new BLList<>();\n    ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n    ⟪d⟫;\n    ⟪e⟫;\n    ⟪f⟫;\n}","lang":"java","f":{"a":"b.addLast(1)","b":"b.addLast(2)","c":"b.addLast(3)","d":"assertEquals(1, b.get(0))","e":"assertEquals(2, b.get(1))","f":"assertEquals(3, b.get(2))"}}]},{"id":27,"l":[{"p":"(a) Line 1"}],"k":"blank","a":["b.addLast(1)"],"topics":["LINKED_LISTS"],"part":"a"},{"id":28,"l":[{"p":"(a) Line 2"}],"k":"blank","a":["b.addLast(2)"],"topics":["LINKED_LISTS"],"part":"a"},{"id":29,"l":[{"p":"(a) Line 3"}],"k":"blank","a":["b.addLast(3)"],"topics":["LINKED_LISTS"],"part":"a"},{"id":30,"l":[{"p":"(a) Line 4"}],"k":"blank","a":["assertEquals(1, b.get(0))"],"topics":["LINKED_LISTS"],"part":"a"},{"id":31,"l":[{"p":"(a) Line 5"}],"k":"blank","a":["assertEquals(2, b.get(1))"],"topics":["LINKED_LISTS"],"part":"a"},{"id":32,"l":[{"p":"(a) Line 6"}],"k":"blank","a":["assertEquals(3, b.get(2))"],"topics":["LINKED_LISTS"],"x":"Any three values work, as long as the asserts match them.","part":"a"},{"s":[{"p":"A BLList (“backward linked list”) is a sentinel node pointing backwards at the last item; each Node has an item and a prev. After addLast(0), addLast(5), addLast(10): sentinel → 10 → 5 → 0 (following prev)."},{"c":"private class Node {\n    private T item;\n    private Node prev;\n    public Node(T i, Node p) { item = i; prev = p; }\n}\nprivate Node sentinel;  // initially new Node(null, null)\nprivate int size;\n\npublic void addLast(T item) {\n    ⟪g⟫;\n    ⟪h⟫;\n}","lang":"java","f":{"g":"sentinel.prev = new Node(item, sentinel.prev)","h":"size += 1"}}]},{"id":33,"l":[{"p":"(b) addLast, line 1"}],"k":"blank","a":["sentinel.prev = new Node(item, sentinel.prev)"],"topics":["LINKED_LISTS"],"part":"b"},{"id":34,"l":[{"p":"(b) addLast, line 2"}],"k":"blank","a":["size += 1","size++"],"topics":["LINKED_LISTS"],"part":"b"},{"s":[{"p":"(c) getNode(int i) finds the ith node recursively (getNode(size) is the sentinel). No loops."},{"c":"private Node getNode(int i) {\n    return ⟪i⟫;\n}\n\nprivate Node getNode(int i, Node p) {\n    if (⟪j⟫) {\n        return p;\n    }\n    return ⟪k⟫;\n}","lang":"java","f":{"i":"getNode(size() - i, sentinel)","j":"i == 0","k":"getNode(i - 1, p.prev)"}}]},{"id":35,"l":[{"p":"(c) getNode(int i) returns"}],"k":"blank","a":["getNode(size() - i, sentinel)","getNode(size - i, sentinel)"],"topics":["LINKED_LISTS"],"part":"c"},{"id":36,"l":[{"p":"(c) if (____) return p"}],"k":"blank","a":["i == 0"],"topics":["LINKED_LISTS"],"part":"c"},{"id":37,"l":[{"p":"(c) return ____"}],"k":"blank","a":["getNode(i - 1, p.prev)"],"topics":["LINKED_LISTS"],"x":"The ith item is size − i hops back from the sentinel.","part":"c"},{"s":[{"p":"(d) The same, iteratively."},{"c":"private Node getNode(int i) {\n    int numNodesToHop = ⟪l⟫;\n    Node p = sentinel;\n    while (⟪m⟫) {\n        ⟪n⟫;\n        ⟪o⟫;\n    }\n    return p;\n}","lang":"java","f":{"l":"size() - i","m":"numNodesToHop > 0","n":"p = p.prev","o":"numNodesToHop -= 1"}}]},{"id":38,"l":[{"p":"(d) numNodesToHop = ____"}],"k":"blank","a":["size() - i","size - i"],"topics":["LINKED_LISTS"],"part":"d"},{"id":39,"l":[{"p":"(d) while (____)"}],"k":"blank","a":["numNodesToHop > 0","numNodesToHop != 0"],"topics":["LINKED_LISTS"],"part":"d"},{"id":40,"l":[{"p":"(d) First line of the loop"}],"k":"blank","a":["p = p.prev"],"topics":["LINKED_LISTS"],"part":"d"},{"id":41,"l":[{"p":"(d) Second line"}],"k":"blank","a":["numNodesToHop -= 1","numNodesToHop--"],"topics":["LINKED_LISTS"],"part":"d"},{"s":[{"p":"(e) remove(int i) removes the ith item, doing nothing for an out-of-bounds index. You may use getNode."},{"c":"public void remove(int i) {\n    if (⟪p⟫) {\n        return;\n    }\n    ⟪q⟫;\n    ⟪r⟫;\n    ⟪s⟫;\n}","lang":"java","f":{"p":"i < 0 || i >= size()","q":"Node parentOfNodeToRemove = getNode(i + 1)","r":"parentOfNodeToRemove.prev = parentOfNodeToRemove.prev.prev","s":"size -= 1"}}]},{"id":42,"l":[{"p":"(e) if (____) return"}],"k":"blank","a":["i < 0 || i >= size()","i < 0 || i >= size"],"topics":["LINKED_LISTS"],"part":"e"},{"id":43,"l":[{"p":"(e) Next line"}],"k":"blank","a":["Node parentOfNodeToRemove = getNode(i + 1)"],"topics":["LINKED_LISTS"],"part":"e"},{"id":44,"l":[{"p":"(e) Next line"}],"k":"blank","a":["parentOfNodeToRemove.prev = parentOfNodeToRemove.prev.prev"],"topics":["LINKED_LISTS"],"part":"e"},{"id":45,"l":[{"p":"(e) Last line"}],"k":"blank","a":["size -= 1","size--"],"topics":["LINKED_LISTS"],"x":"Find the node that points back at the one to remove (item i + 1, or the sentinel) and skip over it.","part":"e"}],"topics":null},{"id":"61b-sp21-mt1/5","n":"5","t":"5. MT1List (220 pts)","b":[{"s":[{"p":"MT1List<T> has addLast, get, remove(int i), size and createList() (a new empty MT1List<T>)."},{"p":"(a) getEvens returns a new list of the even-indexed items without changing the original: [\"ape\", \"banana\", \"cow\", \"dog\"] gives [\"ape\", \"cow\"]."},{"c":"default public MT1List<T> getEvens() {\n    ⟪a⟫;\n    for (⟪b⟫) {\n        ⟪c⟫;\n    }\n    return returnList;\n}","lang":"java","f":{"a":"MT1List<T> returnList = createList()","b":"int i = 0; i < size(); i += 2","c":"returnList.addLast(get(i))"}}]},{"id":46,"l":[{"p":"(a) First line"}],"k":"blank","a":["MT1List<T> returnList = createList()"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"a"},{"id":47,"l":[{"p":"(a) Loop header"}],"k":"blank","a":["int i = 0; i < size(); i += 2","int i = 0; i < size(); i = i + 2"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"a"},{"id":48,"l":[{"p":"(a) Loop body"}],"k":"blank","a":["returnList.addLast(get(i))"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"x":"Or step by 1 and add only when i % 2 == 0.","part":"a"},{"s":[{"p":"(b) remove(int start, int end) removes the items from start to end inclusive and returns them as a list: [\"ape\", \"banana\", \"cow\", \"dog\", \"elephant\"].remove(1, 3) leaves [\"ape\", \"elephant\"] and returns [\"banana\", \"cow\", \"dog\"]."},{"c":"default public MT1List<T> remove(int start, int end) {\n    MT1List<T> returnList = createList();\n    int numToRemove = ⟪d⟫;\n    for (int i = 0; i < numToRemove; i += 1) {\n        ⟪e⟫;\n        ⟪f⟫;\n    }\n    return returnList;\n}","lang":"java","f":{"d":"end - start + 1","e":"returnList.addLast(get(start))","f":"remove(start)"}}]},{"id":49,"l":[{"p":"(b) numToRemove = ____"}],"k":"blank","a":["end - start + 1"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"b"},{"id":50,"l":[{"p":"(b) First line of the loop"}],"k":"blank","a":["returnList.addLast(get(start))"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"b"},{"id":51,"l":[{"p":"(b) Second line"}],"k":"blank","a":["remove(start)"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"x":"Each removal shifts the next item into position start.","part":"b"},{"s":[{"p":"(c) reverse reverses the list in place, without new or createList: [\"ape\", \"banana\", \"cow\", \"dog\", \"elephant\"] becomes [\"elephant\", \"dog\", \"cow\", \"banana\", \"ape\"]."},{"c":"default public void reverse() {\n    int N = size();\n    for (⟪g⟫) {\n        ⟪h⟫;\n        ⟪i⟫;\n        ⟪j⟫;\n    }\n}","lang":"java","f":{"g":"int i = N - 2; i >= 0; i -= 1","h":"T x = get(i)","i":"remove(i)","j":"addLast(x)"}}]},{"id":52,"l":[{"p":"(c) Loop header"}],"k":"blank","a":["int i = N - 2; i >= 0; i -= 1","int i = N - 2; i >= 0; i--"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"c"},{"id":53,"l":[{"p":"(c) Line 1"}],"k":"blank","a":["T x = get(i)"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"c"},{"id":54,"l":[{"p":"(c) Line 2"}],"k":"blank","a":["remove(i)"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"part":"c"},{"id":55,"l":[{"p":"(c) Line 3"}],"k":"blank","a":["addLast(x)"],"topics":["LISTS","ABSTRACTION","INHERITANCE","ITERATION","RECURSION"],"x":"Move items to the end from the second-to-last back to the first.","part":"c"}],"topics":null},{"id":"61b-sp21-mt1/6","n":"6","t":"6. AListBug (110 pts)","b":[{"s":[{"c":"1: public class AListMax100<Item> {\n2:     private Item[] items;\n3:     private static int size;\n4:\n5:     /** Creates an empty list. */\n6:     public AListMax100() {\n7:         items = (Item[]) new Object[100];\n8:         size = 0;\n9:     }\n10:\n11:    /** Inserts X into the back of the list if there is room. */\n12:    public void addLast(Item x) {\n13:        if (size >= 100) {\n14:            return;\n15:        }\n16:        items[size] = x;\n17:        size = size + 1;\n18:    }\n19:\n20:    /** Returns the item from the back of the list or null if empty. */\n21:    public Item getLast() {\n22:        if (size == 0) {\n23:            return null;\n24:        }\n25:        return items[size - 1];\n26:    }\n27:\n28:    /** Returns the number of items in the list. */\n29:    public int size() {\n30:        return size;\n31:    }\n32: }","lang":"java"},{"p":"This list has a serious bug even when it has plenty of room. It isn’t running out of space, and it isn’t an off-by-one error."}]},{"id":56,"l":[{"p":"(a) Which single line number could we change to fix it?"}],"k":"blank","a":["3"],"topics":["JAVA"],"part":"a"},{"id":57,"l":[{"p":"(b) How would we change it?"}],"k":"mc","o":["Remove the static keyword in front of size","Make items static","Change Item[] to Object[]","Initialize size to 1"],"a":0,"topics":["JAVA"],"x":"A static size is shared by every list, so creating a second list resets the first one’s size.","part":"b"},{"s":[{"p":"(c) Write a JUnit test that fails because of the bug."},{"c":"@Test\npublic void test() {\n    AListMax100<Integer> L = new AListMax100<>();\n    L.addLast(5);\n    L.addLast(10);\n    ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n}","lang":"java","f":{"a":"AListMax100<Integer> L2 = new AListMax100<>()","b":"L2.addLast(5)","c":"assertEquals(2, L.size())"}}]},{"id":58,"l":[{"p":"(c) Line 1"}],"k":"blank","a":["AListMax100<Integer> L2 = new AListMax100<>()"],"topics":["JAVA"],"part":"c"},{"id":59,"l":[{"p":"(c) Line 2"}],"k":"blank","a":["L2.addLast(5)"],"topics":["JAVA"],"part":"c"},{"id":60,"l":[{"p":"(c) Line 3"}],"k":"blank","a":["assertEquals(2, L.size())"],"topics":["JAVA"],"x":"Creating L2 resets the shared size to 0, so L.size() is 1, not 2.","part":"c"}],"topics":null},{"id":"61b-sp21-mt1/7","n":"7","t":"7. Tilt (160 pts)","b":[{"s":[{"p":"Re-implement 2048’s tilt for one row, as an IntList: tiltRowLeft transforms it into the result of tilting left. There are no empty tiles, and merges don’t need empty tiles added at the end. Two equal tiles merge into one double tile; a merged tile doesn’t merge again that tilt; with three equal tiles in a row, the leading two merge. For example, 2, 2, 8, 4 becomes 4, 8, 4; 2, 2, 4, 4 becomes 4, 8; and 2, 2, 4, 8 becomes 4, 4, 8."},{"c":"public static void tiltRowLeft(IntList tiles) {\n    IntList p = ⟪a⟫;\n    while (⟪b⟫) {\n        if (⟪c⟫) {\n            ⟪d⟫;\n            ⟪e⟫;\n            if (p.rest == null) { // Using this is optional.\n                break;\n            }\n        }\n        ⟪f⟫;\n    }\n}","lang":"java","f":{"a":"tiles","b":"p.rest != null","c":"p.first == p.rest.first","d":"p.first += p.first","e":"p.rest = p.rest.rest","f":"p = p.rest"}}]},{"id":61,"l":[{"p":"IntList p = ____"}],"k":"blank","a":["tiles"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"]},{"id":62,"l":[{"p":"while (____)"}],"k":"blank","a":["p.rest != null","p != null && p.rest != null"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"],"x":"With p != null && p.rest != null, the optional break isn’t needed."},{"id":63,"l":[{"p":"if (____)"}],"k":"blank","a":["p.first == p.rest.first","p.rest.first == p.first"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"]},{"id":64,"l":[{"p":"Merge, line 1"}],"k":"blank","a":["p.first += p.first","p.first *= 2","p.first = p.first * 2","p.first = 2 * p.first"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"]},{"id":65,"l":[{"p":"Merge, line 2"}],"k":"blank","a":["p.rest = p.rest.rest"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"]},{"id":66,"l":[{"p":"Last line of the loop"}],"k":"blank","a":["p = p.rest"],"topics":["LINKED_LISTS","PROJECT_2048","ITERATION"],"x":"Always move past the current tile, so a merged tile never merges again."}],"topics":null}],"by":["Hug"]},{"id":"61b-sp21-mt2","t":"Spring 2021 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1VlxEIjd19mW8ftxozoPLWYhjBO_yDfia/view","sol":"https://drive.google.com/file/d/1jqFbU5OyV6_7ttEwTxHeKvIi7cjmC13-/view","topics":"sp21-mt2"},"p":[{"id":"61b-sp21-mt2/1","n":"1","t":"1. Graph Traversals (205 pts)","b":[{"s":[{"p":"Consider the undirected graph with these edges:"},{"c":"3 — 7    7 — 1    7 — 5    1 — 5\n6 — 2    2 — 4    5 — 4    4 — 8","lang":"txt"}]},{"id":1,"l":[{"p":"(a) If we perform a BFS traversal starting from vertex 7, what will be the final vertex visited?"}],"k":"mc","o":["1","2","3","4","5","6","7","8"],"a":5,"topics":["GRAPH_TRAVERSALS"],"x":"By distance from 7: 7; 1, 3, 5; 4; 2, 8; 6.","part":"a"},{"id":2,"l":[{"p":"(b) What start vertex (or vertices) will result in a DFS pre-order of 84265173? Ties are broken numerically. If none, select Impossible."}],"k":"sata","o":["1","2","3","4","5","6","7","8","Impossible"],"a":[7],"topics":["GRAPH_TRAVERSALS"],"part":"b"},{"id":3,"l":[{"p":"(c) What start vertex (or vertices) will result in a DFS post-order of 84265173? Ties are broken numerically."}],"k":"sata","o":["1","2","3","4","5","6","7","8","Impossible"],"a":[8],"topics":["GRAPH_TRAVERSALS"],"x":"A post-order ends with the start vertex, so it would have to start at 3. From 3, DFS goes 3 → 7 → 1 → 5 → 4 → 2 → 6 (smallest neighbor first), so 6 would finish first, not 8.","part":"c"},{"id":4,"l":[{"p":"(d) We want a DFS pre-order of 12345678. No vertex gives that now. What is the minimum number of edges to add so that a pre-order traversal could yield this order from some start vertex?"}],"k":"mc","o":["1","2","3","4","5","6","7","8","Impossible"],"a":3,"topics":["GRAPH_TRAVERSALS"],"part":"d"}],"topics":null},{"id":"61b-sp21-mt2/2","n":"2","t":"2. Heaps and Tree Traversals (120 pts)","b":[{"s":[{"p":"An ArrayHeap<Integer> uses the array representation from class (the leftmost item is unused). Its array is [-, −5, 4, −1, 5, 6, 0, 0, 10]."}]},{"id":5,"l":[{"p":"(a) In a pre-order traversal of the heap represented by this array, what is the last value?"}],"k":"mc","o":["-5","-1","3","0","4","5","6","10"],"a":3,"topics":["HEAPS","TREE_TRAVERSALS"],"part":"a"},{"id":6,"l":[{"p":"(b) In an in-order traversal, what is the last value?"}],"k":"mc","o":["-5","-1","3","0","4","5","6","10"],"a":3,"topics":["HEAPS","TREE_TRAVERSALS"],"x":"The tree is −5 → (4 → (5 → (10), 6), −1 → (0, 0)). Both traversals end at the rightmost leaf, the second 0.","part":"b"},{"id":7,"l":[{"p":"(c) If we call removeMin on the heap above (as described in lecture), where will the 10 end up?"}],"k":"mc","o":["10 will not move.","10 will not be present in the heap.","In the root position previously occupied by a -5.","In a position previously occupied by a 4.","In a position previously occupied by a 5.","In a position previously occupied by a 6.","In a position previously occupied by a -1.","In a position previously occupied by a 0."],"a":7,"topics":["HEAPS","TREE_TRAVERSALS"],"x":"10 moves to the root and sinks below −1, then below a 0.","part":"c"}],"topics":null},{"id":"61b-sp21-mt2/3","n":"3","t":"3. Space Git (75 pts)","b":[{"id":8,"l":[{"p":"(a) Sklurp the space horse deleted the proj1 directory in their sp21-s*** repo while starting over from the skeleton code. Which command could they enter next to restore the skeleton code for proj1? (The CWD is the repo.)"}],"k":"mc","o":["git pull skeleton master","git add * then git commit -m \"starting over\"","git pull skeleton origin","git push","git push origin master","git checkout skeleton/master -- proj1"],"a":5,"topics":["GIT"],"part":"a"},{"id":9,"l":[{"p":"(b) Later, git status says the repo is in a “detached HEAD” state. What does this mean?"}],"k":"mc","o":["Their repo isn’t in a clean state. Some changes need to be committed.","They are no longer synced with the skeleton repo.","Some files were deleted after they were added, but before they were committed.","They tried to git push origin master and something went wrong, so HEAD changed its value.","HEAD is pointing to a commit that is not pointed to by a branch.","HEAD is pointing to corrupt files in the staging area."],"a":4,"topics":["GIT"],"part":"b"},{"id":10,"l":[{"p":"(c) What command might possibly get Sklurp out of the “detached HEAD” state? ([some hash] means an actual commit id.)"}],"k":"mc","o":["git checkout master","git add * then git commit -m \"starting over\"","git pull skeleton master","git checkout [some hash] .","git pull origin master"],"a":0,"topics":["GIT"],"part":"c"}],"topics":null},{"id":"61b-sp21-mt2/4","n":"4","t":"4. Hashing (195 pts)","b":[{"s":[{"p":"(a) A hash table represents a set, each bucket is a left-leaning red-black tree, and the items implement Comparable. Which statements are true?"}]},{"id":11,"l":[{"p":"(a) 1) The runtime of contains is O(N)."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS","RED_BLACK_TREES"],"part":"a"},{"id":12,"l":[{"p":"(a) 2) The runtime of contains is O(log N)."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS","RED_BLACK_TREES"],"x":"Even if every item is in one bucket, that LLRB has height O(log N).","part":"a"},{"id":13,"l":[{"p":"(a) 3) The runtime of contains is O(1)."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS","RED_BLACK_TREES"],"part":"a"},{"id":14,"l":[{"p":"(a) 4) One advantage of using an LLRB for the buckets is that it makes it possible to efficiently iterate over all of the keys in the set in ascending order."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS","RED_BLACK_TREES"],"x":"Each bucket is sorted, but the buckets aren’t in order relative to each other.","part":"a"},{"id":15,"l":[{"p":"(a) 5) Assuming items are nicely spread out in the hash table, we expect an LLRB bucket would yield significantly better performance for contains and add than an ArrayList for each bucket."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS","RED_BLACK_TREES"],"x":"Nicely spread buckets are tiny, so the structure inside them barely matters.","part":"a"},{"s":[{"p":"(b) A Set<Picture> uses a hash table with 5 buckets, each a linked list. It holds pictures with these hash codes: bucket 0 holds 5; bucket 1 holds 1; bucket 3 holds 3, 103, 28; bucket 4 holds 9. Bucket numbers use Math.floorMod(hashCode, buckets)."}]},{"id":16,"l":[{"p":"(b) 1) We add a new picture with hash code −6. In which bucket will it end up (no resizing)?"}],"k":"mc","o":["0","1","2","3","4"],"a":4,"topics":["ADTS","HASHING"],"x":"floorMod(−6, 5) = 4.","part":"b"},{"id":17,"l":[{"p":"(b) 2) If we resize the original table by doubling it to 10 buckets, items with which hash codes end up in a different bucket number than before?"}],"k":"sata","o":["5","1","3","103","28","9"],"a":[0,4,5],"topics":["ADTS","HASHING"],"x":"5 → 5 (was 0), 28 → 8 (was 3), 9 → 9 (was 4). 1, 3 and 103 keep their bucket numbers.","part":"b"},{"s":[{"p":"(b) 3) On the original 5-bucket table: Picture x is the one with hash code 9; we run hashTable.add(x); then x.turnPink(), which changes x’s pixels and may change its hash code; then System.out.println(hashTable.contains(x)). A Picture’s equals is true only for identical pixels."}]},{"id":18,"l":[{"p":"(b) 3) For which new hash codes will the last line print true?"}],"k":"sata","o":["x.hashCode() is -1","x.hashCode() is 0","x.hashCode() is 4","x.hashCode() is 14","None of these"],"a":[0,2,3],"topics":["ADTS","HASHING"],"x":"x is still stored in bucket 4 (and is equal to itself), so contains finds it whenever its new hash code maps to bucket 4: −1, 4 and 14 do; 0 doesn’t.","part":"b"}],"topics":null},{"id":"61b-sp21-mt2/5","n":"5","t":"5. By the Numbers (370 pts)","b":[{"s":[{"p":"(a) A hash table starts empty for each part, has 32 buckets, and never resizes. Don’t assume anything about how the items are spread out."}]},{"id":19,"l":[{"p":"(a) 1) If we insert 16 items, what is the minimum number of items in bucket 0?"}],"k":"blank","a":["0"],"topics":["BSTS","HASHING"],"part":"a"},{"id":20,"l":[{"p":"(a) 2) If we insert 16 items, what is the maximum number of items in bucket 0?"}],"k":"blank","a":["16"],"topics":["BSTS","HASHING"],"part":"a"},{"id":21,"l":[{"p":"(a) 3) If we insert 4 strings, and each bucket is a binary search tree (no balancing), how many string comparisons occur in the worst case?"}],"k":"blank","a":["6"],"topics":["BSTS","HASHING"],"x":"All four in one bucket as a spindly BST: 0 + 1 + 2 + 3 = 6 comparisons.","part":"a"},{"s":[{"p":"(b) The height of a tree is the number of edges from the root to the farthest leaf."}]},{"id":22,"l":[{"p":"(b) 1) A 2-3 tree has height 6. What is the minimum height of the corresponding LLRB?"}],"k":"blank","a":["6"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":23,"l":[{"p":"(b) 2) A 2-3 tree has height 6. What is the maximum height of the corresponding LLRB?"}],"k":"blank","a":["13"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"Each 2-3 level can add one red link to a path, and the bottom leaf too: 6 + 7 = 13.","part":"b"},{"id":24,"l":[{"p":"(b) 3) What is the minimum possible height of a 2-3 tree with 8 values?"}],"k":"blank","a":["1"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":25,"l":[{"p":"(b) 4) What is the maximum possible height of a 2-3 tree with 8 values?"}],"k":"blank","a":["2"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"b"},{"id":26,"l":[{"p":"(b) 5) What is the maximum number of values we can insert into the 2-3 tree from (4) without increasing its height?"}],"k":"blank","a":["18"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"The fullest tree of height 2 has 13 nodes of 2 values each: 26 values, and 26 − 8 = 18.","part":"b"}],"topics":null},{"id":"61b-sp21-mt2/6","n":"6","t":"6. Disjoint Sets Iterator (200 pts)","b":[{"s":[{"p":"Implement setIterator for WeightedQuickUnionDS, which iterates over all items in p’s set in increasing order, in O(N log N) time. Items are numbered 0 to N − 1. You may not create helper functions or new classes, or access the instance variables. For example:"},{"c":"WeightedQuickUnionDS df = new WeightedQuickUnionDS(6); // creates WQUDS of size 6\ndf.connect(3, 2);\ndf.connect(1, 5);\ndf.connect(2, 5);\nIterator<Integer> connectedToThree = df.setIterator(3);\nwhile (connectedToThree.hasNext()) {\n    System.out.print(connectedToThree.next() + \" \");\n} // prints 1 2 3 5","lang":"java"},{"c":"public class WeightedQuickUnionDS implements DisjointSets {\n    ... // Instance variables not listed because you are not allowed to access them\n    private int find(int p) { ... }\n    public boolean isConnected(int p, int q) { ... }\n    public void connect(int p, int q) { ... }\n    public int size() { ... } // returns the number of items in the disjoint set\n\n    /** returns an Iterator over the set containing p. */\n    public Iterator<Integer> setIterator(int p) {\n        ⟪a⟫;\n        for (⟪b⟫) {\n            if (⟪c⟫) {\n                ⟪d⟫;\n            }\n        }\n        ⟪e⟫;\n    }\n}","lang":"java","f":{"a":"List<Integer> res = new ArrayList<>()","b":"int i = 0; i < size(); i++","c":"isConnected(i, p)","d":"res.add(i)","e":"return res.iterator()"}}]},{"id":27,"l":[{"p":"(a) First line"}],"k":"blank","a":["List<Integer> res = new ArrayList<>()","ArrayList<Integer> res = new ArrayList<>()"],"topics":["ITERATORS","DISJOINT_SETS"],"part":"a"},{"id":28,"l":[{"p":"(b) The loop header"}],"k":"blank","a":["int i = 0; i < size(); i++","int i = 0; i < size(); i += 1"],"topics":["ITERATORS","DISJOINT_SETS"],"part":"b"},{"id":29,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["isConnected(i, p)","isConnected(p, i)"],"topics":["ITERATORS","DISJOINT_SETS"],"part":"c"},{"id":30,"l":[{"p":"(d) Inside the if"}],"k":"blank","a":["res.add(i)"],"topics":["ITERATORS","DISJOINT_SETS"],"part":"d"},{"id":31,"l":[{"p":"(e) Last line"}],"k":"blank","a":["return res.iterator()"],"topics":["ITERATORS","DISJOINT_SETS"],"x":"Check every item in increasing order and keep those connected to p: N isConnected calls at O(log N) each.","part":"e"}],"topics":null},{"id":"61b-sp21-mt2/7","n":"7","t":"7. Asymptotic Analysis (350 pts)","b":[{"s":[{"p":"Assume h(N) runs in Θ(N) time and returns a boolean."},{"c":"static void alpha(int N) {\n    if (N % 2 == 0) { // this check is done in constant time\n        return;\n    }\n    for (int i = 1; i < N; i *= 2) {\n        if (h(i)) {\n            h(i);\n        }\n    }\n}","lang":"java"}]},{"id":32,"l":[{"p":"(a) alpha best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":0,"topics":["ASYMPTOTICS"],"part":"a"},{"id":33,"l":[{"p":"(b) alpha worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"x":"h(1) + h(2) + h(4) + … < 2N, doubled at most.","part":"b"},{"s":[{"c":"static void beta(int N) {\n    if (h(N)) {\n        return;\n    }\n    for (int i = 1; i < N; i *= 2) {\n        for (int j = N - i; j < N; j++) {\n            int a = 1 + 1;\n        }\n    }\n    if (N % 2 != 0) {\n        return;\n    }\n}","lang":"java"}]},{"id":34,"l":[{"p":"(c) beta best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"part":"c"},{"id":35,"l":[{"p":"(d) beta worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":4,"topics":["ASYMPTOTICS"],"x":"h(N) alone is Θ(N); the loops do 1 + 2 + 4 + … < 2N.","part":"d"},{"s":[{"p":"Assume f(N) returns a random number between 1 and N/2, inclusive, in constant time."},{"c":"static void gamma(int N) {\n    if (N <= 10) {\n        return;\n    }\n    for (int i = f(N); i < N; i += f(N)) {\n        gamma(i);\n    }\n}","lang":"java"}]},{"id":36,"l":[{"p":"(e) gamma best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":3,"topics":["ASYMPTOTICS"],"part":"e"},{"id":37,"l":[{"p":"(f) gamma worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ((log N)²)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)"],"a":12,"topics":["ASYMPTOTICS"],"x":"Best: f returns N/2 each time, so one recursive call on N/2. Worst: f returns 1, so gamma(N) calls gamma(1), …, gamma(N−1): exponential.","part":"f"}],"topics":null},{"id":"61b-sp21-mt2/8","n":"8","t":"8. Recursive Trees (405 pts)","b":[{"s":[{"p":"The split operation recursively splits every node X into two nodes of half the value, XL and XR (Java integer division, e.g. 11 / 2 = 5). XL keeps the left child of X and XR keeps the right child. In place of the node actually split, a new node containing 0 is created, with XL and XR as its children."},{"p":"(a) Trees are written value(left, right), with - for a missing child. Here is a tree; p is the node 20 that is the root’s left child:"},{"c":"3( p=20(4, 4(11, 11)), 20(6, 6) )","lang":"txt"}]},{"id":38,"l":[{"p":"(a) What is the resulting tree after calling split on p?"}],"k":"mc","o":["3( 0( 10(2, 2), 10(2(5, 5), 2(5, 5)) ), 20(6, 6) )","3( 0( 10(2, -), 10(-, 2(5, 5)) ), 20(6, 6) )","3( 0( 10(2, -), 10(2(5, 5), 2(5, 5)) ), 20(6, 6) )","3( 0( 10(4, -), 10(-, 4(11, 11)) ), 20(6, 6) )"],"a":0,"topics":["BSTS","RECURSION"],"x":"p becomes 0 with children 10 (from p’s left side) and 10 (from its right side), and every node below is split the same way: each 4 becomes 2 and 2, each 11 becomes 5 and 5.","part":"a"},{"s":[{"p":"(b) Write splitLeft(Node p) and splitRight(Node p), which return the roots of the left split (rooted at XL) and right split (rooted at XR). They must not modify the tree, and may not use split. For example, for p = 40(8(-, 22), 12), splitLeft(p) is 20(4, 4(11, 11)) and splitRight(p) is 20(6, 6)."},{"c":"public static class Node {\n    public int value;\n    public Node left;\n    public Node right;\n    public Node(int v, Node l, Node r) {\n        value = v;\n        left = l;\n        right = r;\n    }\n}\n\npublic static Node splitLeft(Node p) {\n    if (p == null) {\n        return null;\n    }\n    Node newNode = ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n    return newNode;\n}\n\npublic static Node splitRight(Node p) {\n    if (p == null) {\n        return null;\n    }\n    Node newNode = ⟪d⟫;\n    ⟪e⟫;\n    ⟪f⟫;\n    return newNode;\n}","lang":"java","f":{"a":"new Node(p.value / 2, null, null)","b":"newNode.left = splitLeft(p.left)","c":"newNode.right = splitRight(p.left)","d":"new Node(p.value / 2, null, null)","e":"newNode.left = splitLeft(p.right)","f":"newNode.right = splitRight(p.right)"}}]},{"id":39,"l":[{"p":"(b) splitLeft: Node newNode = ____"}],"k":"blank","a":["new Node(p.value / 2, null, null)","new Node(p.value / 2, splitLeft(p.left), splitRight(p.left))"],"topics":["BSTS","RECURSION"],"part":"b"},{"id":40,"l":[{"p":"(b) splitLeft: next line"}],"k":"blank","a":["newNode.left = splitLeft(p.left)"],"topics":["BSTS","RECURSION"],"part":"b"},{"id":41,"l":[{"p":"(b) splitLeft: the line after"}],"k":"blank","a":["newNode.right = splitRight(p.left)"],"topics":["BSTS","RECURSION"],"part":"b"},{"id":42,"l":[{"p":"(b) splitRight: Node newNode = ____"}],"k":"blank","a":["new Node(p.value / 2, null, null)","new Node(p.value / 2, splitLeft(p.right), splitRight(p.right))"],"topics":["BSTS","RECURSION"],"part":"b"},{"id":43,"l":[{"p":"(b) splitRight: next line"}],"k":"blank","a":["newNode.left = splitLeft(p.right)"],"topics":["BSTS","RECURSION"],"part":"b"},{"id":44,"l":[{"p":"(b) splitRight: the line after"}],"k":"blank","a":["newNode.right = splitRight(p.right)"],"topics":["BSTS","RECURSION"],"x":"XL takes X’s left child, and that child is split in turn: its left split and right split become XL’s children. XR does the same with X’s right child.","part":"b"},{"s":[{"p":"(c) Now write void split(Node p), which modifies the tree it’s given: afterwards p.value is 0, and p.left and p.right are the left and right splits."},{"c":"public static void split(Node p) {\n    ⟪g⟫;\n    ⟪h⟫;\n    ⟪i⟫;\n}","lang":"java","f":{"g":"p.left = splitLeft(p)","h":"p.right = splitRight(p)","i":"p.value = 0"}}]},{"id":45,"l":[{"p":"(c) First line"}],"k":"blank","a":["p.left = splitLeft(p)"],"topics":["BSTS","RECURSION"],"part":"c"},{"id":46,"l":[{"p":"(c) Second line"}],"k":"blank","a":["p.right = splitRight(p)"],"topics":["BSTS","RECURSION"],"part":"c"},{"id":47,"l":[{"p":"(c) Third line"}],"k":"blank","a":["p.value = 0"],"topics":["BSTS","RECURSION"],"x":"Compute both splits from the original p before changing anything; set the value to 0 last, since the splits read p.value.","part":"c"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp23-final","t":"Spring 2023 Final","src":{"exam":"https://drive.google.com/file/d/1HqkcadiXO8XcxT3Y1E_u6F2dQ2hX6dxY/view","sol":"https://drive.google.com/file/d/1kj9i4hPPmTlJk9xCrnNU02bkF9Lr9xuj/view","topics":"sp23-final"},"p":[{"id":"61b-sp23-final/1","n":"1","t":"1. I Got A ...","b":[{"s":[{"c":"class A {\n  public void f() { B me = (B) this; g(this); }\n  public void g(A x) { System.out.println(\"Mom\"); x.h(); }\n  public void h() { System.out.println(\"I got a +2\"); }\n}\nclass B extends A {\n  public void g(B x) { System.out.println(\"Brother\"); x.h(); }\n  @Override public void h() { System.out.println(\"I got a PB!\"); }\n}\nA kam = new A(); B park = new A(); A mitch = new B();\nkam.f(); park.f(); mitch.f();","lang":"java"}]},{"id":1,"l":[{"p":"Output/error for kam.f()"}],"k":"blank","a":["RE"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":2,"l":[{"p":"Output/error for initializing park"}],"k":"blank","a":["CE"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"},{"id":3,"l":[{"p":"Output from mitch.f(), one line per output"}],"k":"blank","a":["Mom\nI got a PB!"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp23-final/2","n":"2","t":"2. Edgy Questions","b":[{"s":[{"p":"(a) In this weighted undirected graph, edges are AB=3, AC=5, AE=3, BC=2, BD=1, BE=1, CD=4, DE=3. True or false: Kruskal and Prim from B always produce the same MST, even with different tie-breaking."}]},{"id":4,"l":[{"p":"(a) True or false"}],"k":"blank","a":["false"],"topics":["MSTS"],"topicsBy":"site","part":"a"},{"s":[{"p":"(b) Removed from the exam by clarification; no question to answer."},{"p":"(c) A* graph edges: S–E 4, S–B 2, S–C 6, E–G 2, E–F 1, E–C 1, G–F 3, F–C 1, F–T 3, C–T 3, C–B 4, B–T 6. Heuristics: h(S)=3, h(B)=6, h(C)=2, h(E)=2, h(F)=5, h(G)=12, h(T)=0. Break ties alphabetically."}]},{"id":5,"l":[{"p":"(c) A* visit order from S to T"}],"k":"blank","a":["S E C B T"],"topics":["SHORTEST_PATHS"],"topicsBy":"site","part":"c"},{"s":[{"c":"static Node mystery(Node root) {\n  if (root.right == null) return root;\n  return mystery(root.right);\n}","lang":"java"}]},{"id":6,"l":[{"p":"(d) What does mystery return for any binary tree root?"}],"k":"mc","o":["The last node visited by an in-order traversal","The last node visited by a post-order traversal","The last node visited by a level-order traversal","None of the above"],"a":0,"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp23-final/3","n":"3","t":"3. Value Town","b":[{"s":[{"c":"Food burrito = new Food(\"burrito\", 8);\nratings.put(burrito, 5);\nratings.put(new Food(\"taco\", 6), 3);\nSystem.out.println(ratings.getOrDefault(burrito, -1)); // 13\nburrito.price += 3;\nSystem.out.println(ratings.getOrDefault(burrito, -1)); // 17\nratings.put(new Food(\"burger\", 13), 1);\nratings.put(new Food(\"pizza\", 7), 4);\nSystem.out.println(ratings.getOrDefault(burrito, -1)); // 21\nratings.put(new Food(\"sandwich\", 9), 2);\nSystem.out.println(ratings.getOrDefault(burrito, -1)); // 24","lang":"java"},{"p":"Food.hashCode() is price; Food does not override equals. MyHashMap begins with 4 buckets, external chaining, and doubles capacity when load factor exceeds 1."}]},{"id":7,"l":[{"p":"(a) Line 13 output"}],"k":"blank","a":["5"],"topics":["HASHING"],"topicsBy":"site","part":"a"},{"id":8,"l":[{"p":"(b) Line 17 output"}],"k":"blank","a":["-1"],"topics":["HASHING"],"topicsBy":"site","part":"b"},{"id":9,"l":[{"p":"(c) Line 21 output"}],"k":"blank","a":["-1"],"topics":["HASHING"],"topicsBy":"site","part":"c"},{"id":10,"l":[{"p":"(d) Line 24 output"}],"k":"blank","a":["5"],"topics":["HASHING"],"topicsBy":"site","part":"d"},{"id":11,"l":[{"p":"(e) Is bucket 0 empty after execution?"}],"k":"blank","a":["true"],"topics":["HASHING"],"topicsBy":"site","part":"e"},{"id":12,"l":[{"p":"(f) Does any bucket hold at least two Food objects?"}],"k":"blank","a":["false"],"topics":["HASHING"],"topicsBy":"site","part":"f"},{"id":13,"l":[{"p":"(g) Does inserting another new Food(\"sandwich\",9) increase map size?"}],"k":"blank","a":["true"],"topics":["HASHING"],"topicsBy":"site","part":"g"}],"topics":null},{"id":"61b-sp23-final/4","n":"4","t":"4. Asymptotics","b":[{"s":[{"c":"void enigma1(int N) {\n  for (int i=0; i<Math.pow(2,N); i+=5)\n    for (int j=N; j>=0; j-=1) {}\n}\nvoid enigma2(int N) {\n  for (int i=N*8; i>1; i/=4)\n    for (int j=0; j<10000; j+=N) {}\n}\nvoid enigma3(int N) {\n  for (int i=2; i<N; i*=2)\n    for (int j=0; j<N*N; j+=i/2) {}\n}\nvoid enigma4(int N) { enigma4(N,N); }\nvoid enigma4(int x,int n) {\n  if (x==1) return;\n  for (int i=0; i<n; i+=1) enigma4(x-1,n);\n}","lang":"java"}]},{"id":14,"l":[{"p":"enigma1"}],"k":"blank","a":["Theta(N * 2^N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":15,"l":[{"p":"enigma2"}],"k":"blank","a":["Theta(log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":16,"l":[{"p":"enigma3"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":17,"l":[{"p":"enigma4"}],"k":"blank","a":["Theta(N^(N-1))"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"For ben(N), work is Θ(N), base case N<=625, and each of answer recursive calls gets input N/answer."}]},{"id":18,"l":[{"p":"answer = 0"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":19,"l":[{"p":"answer = 2"}],"k":"blank","a":["Theta(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":20,"l":[{"p":"answer = N/2"}],"k":"blank","a":["Theta(N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":21,"l":[{"p":"answer = N log N"}],"k":"blank","a":["Theta(N log N)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":22,"l":[{"p":"answer = N^2"}],"k":"blank","a":["Theta(N^2)"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":23,"l":[{"p":"answer = N^N"}],"k":"blank","a":["None of the above"],"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp23-final/5","n":"5","t":"5. Wordle","b":[{"s":[{"p":"Implement a trie dictionary with fields boolean valid, Wordle[] children (26 entries), and int size. Words are unique uppercase strings or empty. Fill in the checkable code fragments."},{"c":"void insert(String word) {\n  size += 1;\n  if (word.length()==0) { this.valid=true; return; }\n  int index = charToInt(word.charAt(0));\n  if (this.children[index]==null) this.children[index]=new Wordle();\n  this.children[index].insert(word.substring(1));\n}\nboolean contains(String word) {\n  return (this.valid && word.length()==0)\n      || (word.length()!=0 && children[charToInt(word.charAt(0))]!=null\n          && children[charToInt(word.charAt(0))].contains(word.substring(1)));\n}\nList<String> wordList() {\n  List<String> words=new ArrayList<>();\n  if (this.valid) words.add(\"\");\n  for (int i=0;i<26;i+=1) if (children[i]!=null)\n    for (String s : children[i].wordList()) words.add(intToChar(i)+s);\n  return words;\n}\nString getRandomWord(Random random) {\n  int randNum=random.nextInt(this.size);\n  if (randNum==size-1 && valid) return \"\";\n  int letter=-1;\n  while (randNum>=0) {\n    letter += 1;\n    if (children[letter]!=null) randNum -= children[letter].size;\n  }\n  return intToChar(letter)+children[letter].getRandomWord(random);\n}","lang":"java"}]},{"id":24,"l":[{"p":"(insert) Empty-string case"}],"k":"blank","a":["this.valid = true;"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":25,"l":[{"p":"(insert) First-character index"}],"k":"blank","a":["charToInt(word.charAt(0))"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":26,"l":[{"p":"(insert) Create missing child"}],"k":"blank","a":["this.children[index] = new Wordle();"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":27,"l":[{"p":"(insert) Recurse on suffix"}],"k":"blank","a":["this.children[index].insert(word.substring(1));"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":28,"l":[{"p":"(contains) Blank 1: terminal word flag"}],"k":"blank","a":["this.valid"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":29,"l":[{"p":"(contains) Blank 2: empty word test"}],"k":"blank","a":["word.length() == 0"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":30,"l":[{"p":"(contains) Blank 3: nonempty word test"}],"k":"blank","a":["word.length() != 0"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":31,"l":[{"p":"(contains) Blank 4: child exists"}],"k":"blank","a":["children[charToInt(word.charAt(0))] != null"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":32,"l":[{"p":"(contains) Blank 5: recursive child result"}],"k":"blank","a":["children[charToInt(word.charAt(0))].contains(word.substring(1))"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":33,"l":[{"p":"(wordList) Include empty word"}],"k":"blank","a":["words.add(\"\");"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":34,"l":[{"p":"(wordList) Iterate over child words"}],"k":"blank","a":["String s : children[i].wordList()"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":35,"l":[{"p":"(wordList) Prefix and append"}],"k":"blank","a":["words.add(intToChar(i) + s);"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":36,"l":[{"p":"(getRandomWord) Empty word condition"}],"k":"blank","a":["randNum == size - 1 && valid"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":37,"l":[{"p":"(getRandomWord) Existing child test"}],"k":"blank","a":["children[letter]"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":38,"l":[{"p":"(getRandomWord) Skip child subtree count"}],"k":"blank","a":["randNum -= children[letter].size;"],"topics":["TRIES","RECURSION"],"topicsBy":"site"},{"id":39,"l":[{"p":"(getRandomWord) Prefix selected child result"}],"k":"blank","a":["intToChar(letter) + children[letter].getRandomWord(random)"],"topics":["TRIES","RECURSION"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp23-final/6","n":"6","t":"6. Sorta Sorting","b":[{"s":[{"p":"(A) foo returns sortedArr[9] from an array of at least 100 nonnegative integers."}]},{"id":40,"l":[{"p":"(A)(i) In at most 10 words, what does foo return?"}],"k":"blank","a":["The 10th smallest element"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"s":[{"p":"(A)(ii) Use a max-of-values heap represented by negated integers, keeping the smallest ten values."}]},{"id":41,"l":[{"p":"Initialize first loop"}],"k":"blank","a":["i = 0; i < 10; i += 1"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"id":42,"l":[{"p":"Insert first ten values"}],"k":"blank","a":["h.insert(arr[i] * -1);"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"id":43,"l":[{"p":"Second loop bounds"}],"k":"blank","a":["i = 10; i < arr.length; i += 1"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"id":44,"l":[{"p":"Insert next negated value"}],"k":"blank","a":["h.insert(arr[i] * -1);"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"id":45,"l":[{"p":"Discard largest among retained ten"}],"k":"blank","a":["h.deleteMin();"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"id":46,"l":[{"p":"Return 10th smallest"}],"k":"blank","a":["h.deleteMin() * -1"],"topics":["HEAPS","SORTING"],"topicsBy":"site"},{"s":[{"p":"(B) bar returns the smallest nonnegative integer not in the input list."}]},{"id":47,"l":[{"p":"(B)(i) What does bar return?"}],"k":"mc","o":["The smallest nonnegative integer","The smallest duplicate nonnegative integer","The smallest nonnegative integer not in the list","The smallest nonnegative integer that is not duplicated"],"a":2,"topics":["ARRAYS","SORTING"],"topicsBy":"site"},{"id":48,"l":[{"p":"(B)(ii) Guard before indexing counts"}],"k":"blank","a":["arr[i] < arr.length"],"topics":["ARRAYS","SORTING"],"topicsBy":"site"},{"id":49,"l":[{"p":"(B)(ii) Mark present value"}],"k":"blank","a":["counts[arr[i]] = true;"],"topics":["ARRAYS","SORTING"],"topicsBy":"site"},{"id":50,"l":[{"p":"(B)(ii) Detect missing value"}],"k":"blank","a":["!counts[i]"],"topics":["ARRAYS","SORTING"],"topicsBy":"site"},{"id":51,"l":[{"p":"(B)(ii) Return first missing value"}],"k":"blank","a":["return i;"],"topics":["ARRAYS","SORTING"],"topicsBy":"site"},{"id":52,"l":[{"p":"(B)(ii) If all 0..N-1 are present"}],"k":"blank","a":["return arr.length;"],"topics":["ARRAYS","SORTING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp23-final/7","n":"7","t":"7. Actually Sorting","b":[{"s":[{"p":"(Part 1)(a) Hoare partition with first-index pivot on [4,6,2,5,1,7,3,8]."}]},{"id":53,"l":[{"p":"(a) Array after partition"}],"k":"blank","a":["1,3,2,4,5,7,6,8"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":54,"l":[{"p":"(b) Can any comparison sort sort all 2023-number lists in at most 2024 worst-case comparisons? T/F"}],"k":"blank","a":["false"],"topics":["COMPARISON_SORTS"],"topicsBy":"site","part":"b"},{"id":55,"l":[{"p":"(c) Can any comparison sort be made stable by comparing original indices as a tie-break? T/F"}],"k":"blank","a":["true"],"topics":["COMPARISON_SORTS","SORTING"],"topicsBy":"site","part":"c"},{"id":56,"l":[{"p":"(Part 2)(a)(i) Quicksort pivot always the 10th smallest"}],"k":"blank","a":["Theta(N^2)"],"topics":["SORTING"],"topicsBy":"site"},{"id":57,"l":[{"p":"(Part 2)(a)(ii) Quicksort pivot always the 10th percentile"}],"k":"blank","a":["Theta(N log N)"],"topics":["SORTING"],"topicsBy":"site"},{"id":58,"l":[{"p":"(Part 2)(b)(i) quickMergeSort chooses median pivot"}],"k":"blank","a":["Theta(N log N)"],"topics":["SORTING"],"topicsBy":"site"},{"id":59,"l":[{"p":"(Part 2)(b)(ii) quickMergeSort chooses minimum pivot"}],"k":"blank","a":["Theta(N log N)"],"topics":["SORTING"],"topicsBy":"site"},{"id":60,"l":[{"p":"(Part 3)(a) Identify algorithm"}],"k":"blank","a":["LSD radix sort"],"topics":["SORTING","RADIX_SORTS"],"topicsBy":"site"},{"id":61,"l":[{"p":"(Part 3)(b) Identify algorithm"}],"k":"blank","a":["Insertion sort"],"topics":["SORTING","RADIX_SORTS"],"topicsBy":"site"},{"id":62,"l":[{"p":"(Part 3)(c) Identify algorithm"}],"k":"blank","a":["Heapsort"],"topics":["SORTING","RADIX_SORTS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp23-final/8","n":"8","t":"8. The Javaugean Stables","b":[{"s":[{"p":"Directed graph with positive edge weights. Given a fully connected graph, find the minimum water depth to flood every vertex reachable from source 0. Runtime must be O(E log E) and independent of edge weights. The exam clarification replaces PriorityQueue with MinHeap."},{"c":"int Stables(Graph g) {\n  MinHeap<GraphEdge> h = new MinHeap<>();\n  Queue<Integer> q = new Queue<>();\n  boolean[] visited = new boolean[g.size()];\n  int depth = 0;\n  q.insert(0);\n  while (h.size()>0 || q.size()>0) {\n    if (q.size()>0) {\n      int n=q.remove();\n      visited[n]=true;\n      for (GraphEdge i : g.neighbors(n)) h.insert(i);\n    } else {\n      GraphEdge smallestedge=h.deleteMin();\n      if (!visited[smallestedge.to]) {\n        q.add(smallestedge.to);\n        depth=Math.max(depth,smallestedge.weight);\n      }\n    }\n  }\n  return depth;\n}\nint TwoRiverStables(Graph g) {\n  Graph newGraph=new Graph(g);\n  newGraph.addEdge(new GraphEdge(0,1,0));\n  return Stables(newGraph);\n}","lang":"java"}]},{"id":63,"l":[{"p":"(A) Frontier edge min-heap"}],"k":"blank","a":["MinHeap<GraphEdge> h = new MinHeap<>();"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":64,"l":[{"p":"(A) Queue"}],"k":"blank","a":["Queue<Integer> q = new Queue<>();"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":65,"l":[{"p":"(A) Visited array length"}],"k":"blank","a":["g.size()"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":66,"l":[{"p":"(A) Start vertex"}],"k":"blank","a":["q.insert(0);"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":67,"l":[{"p":"(A) Continue while either structure has work"}],"k":"blank","a":["h.size() > 0 || q.size() > 0"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":68,"l":[{"p":"(A) Dequeue current vertex"}],"k":"blank","a":["q.remove()"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":69,"l":[{"p":"(A) Mark visited"}],"k":"blank","a":["visited[n] = true;"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":70,"l":[{"p":"(A) Add outgoing edges to min-heap"}],"k":"blank","a":["for (GraphEdge i : g.neighbors(n)) h.insert(i);"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":71,"l":[{"p":"(A) Remove next lightest edge"}],"k":"blank","a":["h.deleteMin()"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":72,"l":[{"p":"(A) Check destination not visited"}],"k":"blank","a":["!visited[smallestedge.to]"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":73,"l":[{"p":"(A) Enqueue destination"}],"k":"blank","a":["q.add(smallestedge.to);"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":74,"l":[{"p":"(A) Update required depth"}],"k":"blank","a":["Math.max(depth, smallestedge.weight)"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":75,"l":[{"p":"(B) Add river-1 connection"}],"k":"blank","a":["newGraph.addEdge(new GraphEdge(0, 1, 0));"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"id":76,"l":[{"p":"(B) Reuse one-river algorithm"}],"k":"blank","a":["return Stables(newGraph);"],"topics":["SHORTEST_PATHS","HEAPS","GRAPH_REPRESENTATIONS"],"topicsBy":"site"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp23-mt1","t":"Spring 2023 Midterm 1","src":{"exam":"https://drive.google.com/file/d/14-IEeTJsYHvK6Ogyro4xcDT8KH_KbB9A/view","sol":"https://drive.google.com/file/d/1IB3II-zbgUAlYMikmeSg0c-0uNi7rSnQ/view","topics":"sp23-mt1"},"p":[{"id":"61b-sp23-mt1/1","n":"1","t":"1. F1Car (300 pts)","b":[{"s":[{"c":"public class F1Car {\n    private String driver;\n    private static String[] tracks;\n    private static int trackIndex;\n\n    public F1Car(String driver, String[] tracks, int trackIndex) {\n        this.driver = driver;\n        F1Car.tracks = tracks;\n        this.trackIndex = trackIndex;\n    }\n\n    public static String nextTrack() {\n        return tracks[trackIndex];\n    }\n\n    public String getDriver() {\n        return driver;\n    }\n\n    public static void main(String args[]) {\n        F1Car ferrari = new F1Car(\"Dylan\", new String[]{\"Silverstone\", \"Spa\"}, 0);\n    }\n}","lang":"java"}]},{"id":1,"l":[{"p":"(a) Will calling F1Car.getDriver() error?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["JAVA"],"x":"A non-static method can’t be called on the class.","part":"a"},{"id":2,"l":[{"p":"(b) Will calling F1Car.nextTrack() error?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["JAVA"],"part":"b"},{"id":3,"l":[{"p":"(c) Will calling ferrari.nextTrack() error?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["JAVA"],"x":"Static methods can be called on an instance.","part":"c"},{"id":4,"l":[{"p":"(d) If getDriver becomes public static String getDriver(), will calling ferrari.getDriver() error?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["JAVA"],"x":"The static method would read the instance variable driver: a compile error.","part":"d"}],"topics":null},{"id":"61b-sp23-mt1/2","n":"2","t":"2. StudentID (500 pts)","b":[{"s":[{"p":"A StudentID has a name, an idNumber, buildingAccess (the unique buildings this student can access, initially empty) and studentDir (a directory from idNumber to name shared by all students and updated whenever a student is created). getStudentName returns the name for an idNumber, or \"\" if there is none. For example, after new StudentID(\"Eric\", 1) and new StudentID(\"Eddie\", 2), StudentID.getStudentName(1) is \"Eric\"; adding \"Soda Hall\" to s1.buildingAccess twice leaves one copy."},{"c":"public class StudentID {\n    public String name;\n    public int idNumber;\n\n    public ⟪a⟫ buildingAccess;\n    public ⟪b⟫ studentDir = ⟪c⟫;\n\n    public StudentID(String name, int idNumber) {\n        ⟪d⟫;\n        ⟪e⟫;\n        ⟪f⟫;\n        ⟪g⟫;\n    }\n\n    public ⟪h⟫ getStudentName(int idNumber) {\n        if (⟪i⟫) {\n            ⟪j⟫;\n        }\n        return \"\";\n    }\n}","lang":"java","f":{"a":"Set<String>","b":"static Map<Integer, String>","c":"new HashMap<>()","d":"this.name = name","e":"this.idNumber = idNumber","f":"studentDir.put(idNumber, name)","g":"buildingAccess = new HashSet<>()","h":"static String","i":"studentDir.containsKey(idNumber)","j":"return studentDir.get(idNumber)"}}]},{"id":5,"l":[{"p":"(a) The type of buildingAccess"}],"k":"blank","a":["Set<String>","HashSet<String>","TreeSet<String>"],"topics":["JAVA","ADTS"],"part":"a"},{"id":6,"l":[{"p":"(b) public ____ studentDir"}],"k":"blank","a":["static Map<Integer, String>","static HashMap<Integer, String>","static TreeMap<Integer, String>"],"topics":["JAVA","ADTS"],"x":"static, so all students share one directory.","part":"b"},{"id":7,"l":[{"p":"(c) studentDir = ____"}],"k":"blank","a":["new HashMap<>()","new TreeMap<>()"],"topics":["JAVA","ADTS"],"part":"c"},{"id":8,"l":[{"p":"(d) Constructor, line 1"}],"k":"blank","a":["this.name = name"],"topics":["JAVA","ADTS"],"part":"d"},{"id":9,"l":[{"p":"(e) Constructor, line 2"}],"k":"blank","a":["this.idNumber = idNumber"],"topics":["JAVA","ADTS"],"part":"e"},{"id":10,"l":[{"p":"(f) Constructor, line 3"}],"k":"blank","a":["studentDir.put(idNumber, name)"],"topics":["JAVA","ADTS"],"part":"f"},{"id":11,"l":[{"p":"(g) Constructor, line 4"}],"k":"blank","a":["buildingAccess = new HashSet<>()","this.buildingAccess = new HashSet<>()","buildingAccess = new TreeSet<>()"],"topics":["JAVA","ADTS"],"part":"g"},{"id":12,"l":[{"p":"(h) public ____ getStudentName"}],"k":"blank","a":["static String"],"topics":["JAVA","ADTS"],"part":"h"},{"id":13,"l":[{"p":"(i) if (____)"}],"k":"blank","a":["studentDir.containsKey(idNumber)"],"topics":["JAVA","ADTS"],"part":"i"},{"id":14,"l":[{"p":"(j) Inside the if"}],"k":"blank","a":["return studentDir.get(idNumber)"],"topics":["JAVA","ADTS"],"part":"j"}],"topics":null},{"id":"61b-sp23-mt1/3","n":"3","t":"3. Stars (500 pts)","b":[{"s":[{"c":"public class Star {\n    public static String glow;\n    public static int luminosity = 100;\n    public String light;\n\n    public Star(String color) {\n        light = color;\n        glow = color;\n        luminosity += 100;\n    }\n\n    public void shineBright(String st, Star s) {\n        Star stella = new Star(this.light);\n        this.light = st;\n        System.out.println(s.glow);\n    }\n\n    public static void main(String[] args) {\n        Star sun = new Star(\"pink\");\n        System.out.println(sun.light);       // blank (a)\n        System.out.println(Star.luminosity); // blank (b)\n        Star polaris = new Star(\"yellow\");\n        System.out.println(polaris.glow);    // blank (c)\n        System.out.println(Star.glow);       // blank (d)\n        sun.shineBright(\"blue\", polaris);    // blank (e)\n        System.out.println(sun.light);       // blank (f)\n        System.out.println(Star.luminosity); // blank (g)\n    }\n}","lang":"java"}]},{"id":15,"l":[{"p":"(a)"}],"k":"blank","a":["pink"],"topics":["JAVA"],"part":"a"},{"id":16,"l":[{"p":"(b)"}],"k":"blank","a":["200"],"topics":["JAVA"],"part":"b"},{"id":17,"l":[{"p":"(c)"}],"k":"blank","a":["yellow"],"topics":["JAVA"],"part":"c"},{"id":18,"l":[{"p":"(d)"}],"k":"blank","a":["yellow"],"topics":["JAVA"],"part":"d"},{"id":19,"l":[{"p":"(e)"}],"k":"blank","a":["pink"],"topics":["JAVA"],"x":"glow is static: making stella with sun’s light (\"pink\") sets glow for every Star, including polaris.","part":"e"},{"id":20,"l":[{"p":"(f)"}],"k":"blank","a":["blue"],"topics":["JAVA"],"part":"f"},{"id":21,"l":[{"p":"(g)"}],"k":"blank","a":["400"],"topics":["JAVA"],"x":"Three Stars were made (sun, polaris, stella), each adding 100.","part":"g"}],"topics":null},{"id":"61b-sp23-mt1/4","n":"4","t":"4. 61Bomberman (700 pts)","b":[{"s":[{"p":"Bombs are −1s in int[][] world. All explode at once, setting every number in a bomb’s row and column (the bomb included) to 0. resultingWorld modifies world accordingly. All rows have the same length, and there is at least one row and column. For example, [[-1, 1, -1, 8, 7], [3, 6, 1, 2, 4], [2, 3, 3, 5, 9]] becomes [[0, 0, 0, 0, 0], [0, 6, 0, 2, 4], [0, 3, 0, 5, 9]]."},{"c":"public void resultingWorld(int[][] world) {\n    Set<Integer> rows = new HashSet<>();\n    Set<Integer> cols = new HashSet<>();\n\n    // Find the bombs\n    for (int x = 0; ⟪a⟫; x += 1) {\n        for (int y = 0; ⟪b⟫; y += 1) {\n            if (⟪c⟫) {\n                ⟪d⟫;\n                ⟪e⟫;\n            }\n        }\n    }\n\n    // Trigger the bombs\n    for (int x = 0; ⟪f⟫; x += 1) {\n        for (int y = 0; ⟪g⟫; y += 1) {\n            if (⟪h⟫) {\n                world[x][y] = 0;\n            }\n        }\n    }\n}","lang":"java","f":{"a":"x < world.length","b":"y < world[x].length","c":"world[x][y] == -1","d":"rows.add(x)","e":"cols.add(y)","f":"x < world.length","g":"y < world[x].length","h":"rows.contains(x) || cols.contains(y)"}}]},{"id":22,"l":[{"p":"(a) First loop, x condition"}],"k":"blank","a":["x < world.length"],"topics":["ARRAYS"],"part":"a"},{"id":23,"l":[{"p":"(b) First loop, y condition"}],"k":"blank","a":["y < world[x].length","y < world[0].length"],"topics":["ARRAYS"],"part":"b"},{"id":24,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["world[x][y] == -1"],"topics":["ARRAYS"],"part":"c"},{"id":25,"l":[{"p":"(d) First line"}],"k":"blank","a":["rows.add(x)"],"topics":["ARRAYS"],"part":"d"},{"id":26,"l":[{"p":"(e) Second line"}],"k":"blank","a":["cols.add(y)"],"topics":["ARRAYS"],"part":"e"},{"id":27,"l":[{"p":"(f) Second loop, x condition"}],"k":"blank","a":["x < world.length"],"topics":["ARRAYS"],"part":"f"},{"id":28,"l":[{"p":"(g) Second loop, y condition"}],"k":"blank","a":["y < world[x].length","y < world[0].length"],"topics":["ARRAYS"],"part":"g"},{"id":29,"l":[{"p":"(h) if (____)"}],"k":"blank","a":["rows.contains(x) || cols.contains(y)","cols.contains(y) || rows.contains(x)"],"topics":["ARRAYS"],"x":"Find every bomb first, then clear: clearing during the search would erase bombs before they’re found.","part":"h"}],"topics":null},{"id":"61b-sp23-mt1/5","n":"5","t":"5. getEveryNth (700 pts)","b":[{"s":[{"p":"getEveryNth(int n) returns a new ArrayList of the 0th, nth, 2nth, … elements, like Python’s arr[::n] (n > 0; the size needn’t be a multiple of n). It may not modify the input, and may not use any List’s get method."},{"p":"Part A: in ArrayList, backed by T[] array and int size."},{"c":"public List<T> getEveryNth(int n) {\n    List<T> result = new ArrayList<>();\n    for (int i = 0; ⟪a⟫; ⟪b⟫) {\n        ⟪c⟫;\n    }\n    return result;\n}","lang":"java","f":{"a":"i < this.size","b":"i += n","c":"result.add(array[i])"}}]},{"id":30,"l":[{"p":"A: loop condition"}],"k":"blank","a":["i < this.size","i < size","i < size()","i < this.size()"],"topics":["LINKED_LISTS","ARRAYS"]},{"id":31,"l":[{"p":"A: loop update"}],"k":"blank","a":["i += n","i = i + n"],"topics":["LINKED_LISTS","ARRAYS"]},{"id":32,"l":[{"p":"A: loop body"}],"k":"blank","a":["result.add(array[i])"],"topics":["LINKED_LISTS","ARRAYS"]},{"s":[{"p":"Part B: in LinkedList, a circular doubly-linked list with a sentinel."},{"c":"public List<T> getEveryNth(int n) {\n    List<T> result = new ArrayList<>();\n    Node node = ⟪d⟫;\n    int counter = 0;\n    while (node != sentinel) {\n        if (counter == 0) {\n            ⟪e⟫;\n        }\n        counter = ⟪f⟫;\n        ⟪g⟫;\n    }\n    return result;\n}","lang":"java","f":{"d":"sentinel.next","e":"result.add(node.value)","f":"(counter + 1) % n","g":"node = node.next"}}]},{"id":33,"l":[{"p":"B: Node node = ____"}],"k":"blank","a":["sentinel.next"],"topics":["LINKED_LISTS","ARRAYS"]},{"id":34,"l":[{"p":"B: Inside the if"}],"k":"blank","a":["result.add(node.value)"],"topics":["LINKED_LISTS","ARRAYS"]},{"id":35,"l":[{"p":"B: counter = ____"}],"k":"blank","a":["(counter + 1) % n","(counter - 1) % n","(counter + 1 + n) % n"],"topics":["LINKED_LISTS","ARRAYS"],"x":"Anything that steps the counter by ±1 mod n works."},{"id":36,"l":[{"p":"B: Last line of the loop"}],"k":"blank","a":["node = node.next"],"topics":["LINKED_LISTS","ARRAYS"]},{"id":37,"l":[{"p":"Part C: For a list of 9999991 items, taking every 99991st, which implementation is faster?"}],"k":"mc","o":["ArrayList: it can index straight to each wanted element, skipping the rest","LinkedList: it doesn’t need to resize","They’re about the same: both visit every element","LinkedList: following pointers is faster than indexing"],"a":0,"topics":["LINKED_LISTS","ARRAYS"],"x":"A linked list has to walk through every node to reach the next wanted one."}],"topics":null},{"id":"61b-sp23-mt1/6","n":"6","t":"6. Testception (800 pts)","b":[{"s":[{"p":"numWords(String str) counts words: runs of 1 or more consecutive English letters. \"Apple\" is 1 word, \"A-tree\" and \"cat4dog\" are 2, \"1234\" and \"-\" are 0. isAlpha(char c) says whether c is a letter."},{"c":"public static int numWords(String str) {\n    int words = 0;\n    for (int i = 1; i < str.length(); i++) {\n        if (isAlpha(str.charAt(i-1)) && !isAlpha(str.charAt(i))) {\n            words += 1;\n        }\n    }\n    return words;\n}","lang":"java"}]},{"id":38,"l":[{"p":"(a) This implementation is buggy. Which tests fail with it? (The assertions themselves are correct.)"}],"k":"sata","o":["assertThat(numWords(\"Count the words\")).isEqualTo(3);","assertThat(numWords(\"Count the words!\")).isEqualTo(3);","assertThat(numWords(\"ThisIsOneLongWord\")).isEqualTo(1);","assertThat(numWords(\"The value of pi is 3.14\")).isEqualTo(5);","assertThat(numWords(\"6.25\")).isEqualTo(0);","assertThat(numWords(\"A\")).isEqualTo(1);","assertThat(numWords(\"\")).isEqualTo(0);"],"a":[0,2,5],"topics":["JAVA"],"x":"It counts a word when a letter is followed by a non-letter, so a word at the very end of the string is never counted.","part":"a"},{"s":[{"p":"(b) A correct implementation:"},{"c":"public static int numWords(String str) {\n    int words = 0;\n    boolean inWord = __(1)__;\n    for (char c : str.toCharArray()) {\n        if (__(2)__) {\n            __(3)__;\n            words += 1;\n        } else if (__(4)__) {\n            __(5)__;\n        }\n    }\n    return words;\n}","lang":"java"}]},{"id":39,"l":[{"p":"(b) (1)"}],"k":"mc","o":["true","false"],"a":1,"topics":["JAVA"],"part":"b"},{"id":40,"l":[{"p":"(b) (2)"}],"k":"mc","o":["!inWord && !isAlpha(c)","inWord && !isAlpha(c)","!inWord && isAlpha(c)","inWord && isAlpha(c)"],"a":2,"topics":["JAVA"],"part":"b"},{"id":41,"l":[{"p":"(b) (3)"}],"k":"mc","o":["inWord = true","inWord = false"],"a":0,"topics":["JAVA"],"part":"b"},{"id":42,"l":[{"p":"(b) (4)"}],"k":"mc","o":["!inWord && !isAlpha(c)","inWord && !isAlpha(c)","!inWord && isAlpha(c)","inWord && isAlpha(c)"],"a":1,"topics":["JAVA"],"part":"b"},{"id":43,"l":[{"p":"(b) (5)"}],"k":"mc","o":["inWord = true","inWord = false"],"a":1,"topics":["JAVA"],"x":"Count a word when a letter starts one. (Flipping the meaning of inWord throughout also works.)","part":"b"}],"topics":null},{"id":"61b-sp23-mt1/7","n":"7","t":"7. TwoWayStreet (600 pts)","b":[{"s":[{"p":"TelegraphAve is a singly-linked list of CrossStreets (name, nextStreet) with a circular sentinel. We add a prevStreet field, initially null everywhere; addPrevStreets should set every prevStreet so it becomes a circular doubly-linked list."},{"c":"public void addPrevStreets() {\n    ⟪a⟫;\n}\n\nprivate void addPrevStreetsHelper(CrossStreet curr) {\n    if (⟪b⟫) {\n        return;\n    }\n    ⟪c⟫;\n    ⟪d⟫;\n}","lang":"java","f":{"a":"addPrevStreetsHelper(sentinel)","b":"curr.nextStreet.prevStreet != null","c":"curr.nextStreet.prevStreet = curr","d":"addPrevStreetsHelper(curr.nextStreet)"}}]},{"id":44,"l":[{"p":"addPrevStreets"}],"k":"blank","a":["addPrevStreetsHelper(sentinel)"],"topics":["LINKED_LISTS"]},{"id":45,"l":[{"p":"Helper: if (____) return"}],"k":"blank","a":["curr.nextStreet.prevStreet != null"],"topics":["LINKED_LISTS"]},{"id":46,"l":[{"p":"Helper: next line"}],"k":"blank","a":["curr.nextStreet.prevStreet = curr"],"topics":["LINKED_LISTS"]},{"id":47,"l":[{"p":"Helper: last line"}],"k":"blank","a":["addPrevStreetsHelper(curr.nextStreet)"],"topics":["LINKED_LISTS"],"x":"Point the next street back at this one and move on, stopping once you reach a street already done (back at the start). Many other solutions work."}],"topics":null},{"id":"61b-sp23-mt1/8","n":"8","t":"8. Family Trees (700 pts)","b":[{"s":[{"c":"public interface TreeLike {\n    default boolean isFriendly() {\n        return true;\n    }\n}\n\npublic interface Needly {\n    int numNeedles();\n}\n\npublic class Pine implements TreeLike, Needly {\n    public int numNeedles;\n    public Pine(int numNeedles) { this.numNeedles = numNeedles; }\n    @Override\n    public int numNeedles() { return numNeedles; }\n}\n\npublic class SyntaxTree implements TreeLike {\n    public int branches;\n    public SyntaxTree(int branches) { this.branches = branches; }\n    @Override\n    public boolean isFriendly() { return branches < 5; }\n    public static int numNeedles() { return -1; }\n}","lang":"java"}]},{"id":48,"l":[{"p":"(a) Which lines compile?"}],"k":"sata","o":["Needly n1 = new Needly();","SyntaxTree s1 = new SyntaxTree(85);","Pine p1 = new Needly();","Needly n2 = new Pine(4);","Pine p2 = new SyntaxTree(1);","Needly n3 = new SyntaxTree(37);"],"a":[1,3],"topics":["DMS"],"part":"a"},{"s":[{"c":"Pine ponderosa = new Pine(3);\nTreeLike coulter = new Pine(5);\nSyntaxTree chomsky = new SyntaxTree(-1);\nTreeLike pinker = new SyntaxTree(8);\nNeedly weird = new Pine(-1);","lang":"java"}]},{"id":49,"l":[{"p":"(b) Which would print -1?"}],"k":"sata","o":["System.out.println(weird.numNeedles());","System.out.println(Needly.numNeedles());","System.out.println(chomsky.numNeedles());","System.out.println(SyntaxTree.numNeedles());"],"a":[0,2,3],"topics":["DMS"],"part":"b"},{"s":[{"p":"(c) Random r = new Random(); TreeLike t = ?; boolean tIsFriendly = t.isFriendly();"}]},{"id":50,"l":[{"p":"(c) Which expressions in place of ? guarantee tIsFriendly is true?"}],"k":"sata","o":["new Pine(r.nextInt(94))","new SyntaxTree(100)","new SyntaxTree(r.nextInt(6))","new SyntaxTree(r.nextInt(5))"],"a":[0,3],"topics":["DMS"],"x":"r.nextInt(6) can return 5, which isn’t < 5.","part":"c"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp23-mt2","t":"Spring 2023 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1zypNNO8rkaHFNd0zZm6X2WifXtY0yglk/view","sol":"https://drive.google.com/file/d/1WrnceY7c5UnAPTDZbDdG8qaxR3iodiza/view","topics":"sp23-mt2"},"p":[{"id":"61b-sp23-mt2/1","n":"1","t":"1. Taiko Time! (1100 pts)","b":[{"s":[{"c":"public class Taiko {\n    private String name;\n    private int size;\n    public Taiko(String name, int size) {\n        this.name = name;\n        this.size = size;\n    }\n\n    public String play() { return \"BOOM\"; }\n    public String getName() { return name; }\n}\n\npublic class Chu extends Taiko {\n    public Chu(String name, int size) {\n        super(name, size);\n    }\n\n    public String play() { return \"don kon\"; }\n}\n\npublic class Shime extends Taiko {\n    public Shime(String name, int size) {\n        super(name, size);\n    }\n\n    public String play() { return super.play(); }\n}","lang":"java"}]},{"id":1,"l":[{"p":"(a) Crystal plans to take out the equipment items one by one, starting from the item she most recently put in. Which data structure should she use?"}],"k":"mc","o":["Set","LLRB","Heap","Map","Stack"],"a":4,"topics":["ADTS"],"part":"a"},{"s":[{"p":"(b) We use a Queue for the equipment in organize below. Crystal wants to put each item in its collection: mapping its name to the Chu in chus, or putting a Shime into shimes. All elements of equipment are Chus or Shimes, and you may destructively alter equipment."},{"c":"public class Cages {\n    private Map<String, Chu> chus = new TreeMap<>();\n    private Set<Shime> shimes = new HashSet<>();\n\n    public void organize(Queue<⟪a⟫> equipment) {\n        while (⟪b⟫) {\n            ⟪c⟫;\n            if (⟪d⟫) {\n                ⟪e⟫;\n            } else {\n                ⟪f⟫;\n            }\n        }\n    }\n}","lang":"java","f":{"a":"Taiko","b":"equipment.size() != 0","c":"Taiko t = equipment.remove()","d":"t instanceof Chu chu","e":"chus.put(chu.getName(), chu)","f":"shimes.add((Shime) t)"}}]},{"id":2,"l":[{"p":"(b) Queue<____>"}],"k":"blank","a":["Taiko"],"topics":["ADTS"],"part":"b"},{"id":3,"l":[{"p":"(b) while (____)"}],"k":"blank","a":["equipment.size() != 0","!equipment.isEmpty()","equipment.size() > 0"],"topics":["ADTS"],"part":"b"},{"id":4,"l":[{"p":"(b) First line of the loop"}],"k":"blank","a":["Taiko t = equipment.remove()"],"topics":["ADTS"],"part":"b"},{"id":5,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["t instanceof Chu chu"],"topics":["ADTS"],"part":"b"},{"id":6,"l":[{"p":"(b) If it’s a Chu"}],"k":"blank","a":["chus.put(chu.getName(), chu)","chus.put(t.getName(), chu)","chus.put(t.getName(), (Chu) t)"],"topics":["ADTS"],"part":"b"},{"id":7,"l":[{"p":"(b) Otherwise"}],"k":"blank","a":["shimes.add((Shime) t)"],"topics":["ADTS"],"part":"b"},{"s":[{"p":"(c) Crystal decides that two Taiko are equal if they produce the same sound with play():"},{"c":"@Override\npublic boolean equals(Object o) {\n    // o typechecking not shown\n    ...\n    return ((Taiko) o).play().equals(this.play());\n}","lang":"java"},{"c":"Taiko m = new Taiko(\"miyake\", 5);\nShime b = new Shime(\"beato\", 2);\nChu h = new Chu(\"hachijo\", 7);\nTaiko y = new Chu(\"yatai\", 9);\nTaiko s = new Shime(\"suwari\", 6);","lang":"java"},{"p":"Evaluate each statement. If the code errors, say whether it’s a compile error or a runtime error."}]},{"id":8,"l":[{"p":"(c) m.equals(b)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":0,"topics":["DMS"],"x":"Shime’s play calls Taiko’s, so both say \"BOOM\".","part":"c"},{"id":9,"l":[{"p":"(c) h.equals(y)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":0,"topics":["DMS"],"x":"Both are Chus at runtime: \"don kon\".","part":"c"},{"id":10,"l":[{"p":"(c) s.equals((Chu) s)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":3,"topics":["DMS"],"x":"s’s static type Taiko can be cast to Chu, so it compiles, but it’s a Shime at runtime: ClassCastException.","part":"c"},{"id":11,"l":[{"p":"(c) ((Taiko) b).equals((Taiko) h)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":1,"topics":["DMS"],"x":"Dynamic types decide play: \"BOOM\" vs \"don kon\".","part":"c"},{"id":12,"l":[{"p":"(c) ((Chu) m).equals(y)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":3,"topics":["DMS"],"x":"m is a plain Taiko, so the cast fails at runtime.","part":"c"},{"id":13,"l":[{"p":"(c) b.equals((Shime) h)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":2,"topics":["DMS"],"x":"h’s static type is Chu, and a Chu can never be a Shime, so the cast doesn’t compile.","part":"c"},{"id":14,"l":[{"p":"(c) s.equals(h)"}],"k":"mc","o":["true","false","Compile error","Runtime error"],"a":1,"topics":["DMS"],"part":"c"}],"topics":null},{"id":"61b-sp23-mt2/2","n":"2","t":"2. BSTIterator (700 pts)","b":[{"id":15,"l":[{"p":"(a) Given a Binary Search Tree, which tree traversal yields the keys in sorted order?"}],"k":"mc","o":["Level-order","In-order","Pre-order","Post-order"],"a":1,"topics":["BSTS"],"part":"a"},{"s":[{"p":"(b) Complete BSTIterator so it yields the keys in sorted order. No elements are added or removed after the iterator is made. You may not instantiate any classes other than Iterators. Collections.emptyIterator() returns an empty Iterator (not null)."},{"c":"public class BST<K extends Comparable<K>> {\n    private Node root;\n    private class Node {\n        K key;\n        Node left;\n        Node right;\n        Node(K key) {\n            this.key = key;\n        }\n    }\n\n    public Iterator<K> iterator() {\n        return new BSTIterator(⟪a⟫);\n    }\n\n    private class BSTIterator implements Iterator<K> {\n        Iterator<K> iterLeft;\n        K current;\n        Iterator<K> iterRight;\n        BSTIterator(Node n) {\n            if (n == null) {\n                iterLeft = Collections.emptyIterator();\n                current = null;\n                iterRight = Collections.emptyIterator();\n            } else {\n                iterLeft = ⟪b⟫;\n                current = ⟪c⟫;\n                iterRight = ⟪d⟫;\n            }\n        }\n\n        @Override\n        public boolean hasNext() {\n            return ⟪e⟫ || ⟪f⟫ || ⟪g⟫;\n        }\n\n        @Override\n        public K next() {\n            if (!hasNext()) {\n                throw new NoSuchElementException();\n            }\n            if (iterLeft.hasNext()) {\n                return ⟪h⟫;\n            } else if (current != null) {\n                K result = ⟪i⟫;\n                current = ⟪j⟫;\n                return ⟪k⟫;\n            } else {\n                return ⟪l⟫;\n            }\n        }\n    }\n}","lang":"java","f":{"a":"root","b":"new BSTIterator(n.left)","c":"n.key","d":"new BSTIterator(n.right)","e":"iterLeft.hasNext()","f":"current != null","g":"iterRight.hasNext()","h":"iterLeft.next()","i":"current","j":"null","k":"result","l":"iterRight.next()"}}]},{"id":16,"l":[{"p":"(b) new BSTIterator(____)"}],"k":"blank","a":["root"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":17,"l":[{"p":"(b) iterLeft = ____"}],"k":"blank","a":["new BSTIterator(n.left)"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":18,"l":[{"p":"(b) current = ____"}],"k":"blank","a":["n.key"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":19,"l":[{"p":"(b) iterRight = ____"}],"k":"blank","a":["new BSTIterator(n.right)"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":20,"l":[{"p":"(b) hasNext: the first condition"}],"k":"blank","a":["iterLeft.hasNext()"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":21,"l":[{"p":"(b) hasNext: the second condition"}],"k":"blank","a":["current != null"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":22,"l":[{"p":"(b) hasNext: the third condition"}],"k":"blank","a":["iterRight.hasNext()"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":23,"l":[{"p":"(b) next: return ____ (left side not done)"}],"k":"blank","a":["iterLeft.next()"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":24,"l":[{"p":"(b) K result = ____"}],"k":"blank","a":["current"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":25,"l":[{"p":"(b) current = ____"}],"k":"blank","a":["null"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":26,"l":[{"p":"(b) return ____ (the current key)"}],"k":"blank","a":["result"],"topics":["ITERATORS","BSTS"],"part":"b"},{"id":27,"l":[{"p":"(b) Otherwise, return ____"}],"k":"blank","a":["iterRight.next()"],"topics":["ITERATORS","BSTS"],"x":"Each iterator covers one subtree in order: everything from its left subtree’s iterator, then its own key (set to null once used), then everything from its right subtree’s iterator.","part":"b"}],"topics":null},{"id":"61b-sp23-mt2/3","n":"3","t":"3. Disjoint Sets (900 pts)","b":[{"s":[{"p":"A Weighted Quick Union’s underlying array is currently (indices 0 to 9): [−4, −3, 0, −2, 0, −1, 1, 1, 3, 2]."}]},{"id":28,"l":[{"p":"(a) How many disjoint sets are there currently?"}],"k":"blank","a":["4"],"topics":["DISJOINT_SETS"],"x":"The roots (negative entries) are 0, 1, 3 and 5.","part":"a"},{"id":29,"l":[{"p":"(b) We call connect(4, 9) without path compression. How many disjoint sets are there now?"}],"k":"blank","a":["4"],"topics":["DISJOINT_SETS"],"x":"4 and 9 are both already in 0’s set.","part":"b"},{"id":30,"l":[{"p":"(c) After connect(4, 9), we call connect(4, 1), both without path compression. What is the height of the resulting tree of this set? (Height is the greatest number of edges from the root to a leaf.)"}],"k":"blank","a":["2"],"topics":["DISJOINT_SETS"],"part":"c"},{"id":31,"l":[{"p":"(d) After connect(4, 9) and connect(4, 1), what is the underlying array? (Indices 0 to 9, separated by commas.)"}],"k":"blank","a":["-7, 0, 0, -2, 0, -1, 1, 1, 3, 2","[-7, 0, 0, -2, 0, -1, 1, 1, 3, 2]","-7 0 0 -2 0 -1 1 1 3 2"],"topics":["DISJOINT_SETS"],"x":"connect(4, 1) joins root 1 (size 3) under root 0 (size 4): 0 becomes −7 and 1 becomes 0. The tree is 0 → 1 → 6, height 2.","part":"d"},{"s":[{"p":"Parts (e) and (f) are unrelated to (a)–(d). Before: [−9, −1, 0, 4, 2, 4, 2, 6, 2, 5]."}]},{"id":32,"l":[{"p":"(e) What does the underlying array look like after calling isConnected(1, 9) with path compression?"}],"k":"blank","a":["-9, -1, 0, 4, 0, 0, 2, 6, 2, 0","[-9, -1, 0, 4, 0, 0, 2, 6, 2, 0]","-9 -1 0 4 0 0 2 6 2 0"],"topics":["DISJOINT_SETS"],"x":"Finding 9’s root walks 9 → 5 → 4 → 2 → 0, and path compression points 9, 5 and 4 straight at 0 (2 already is). 1 is its own root, so nothing on its side changes.","part":"e"},{"id":33,"l":[{"p":"(f) What is the output of this call to isConnected(1, 9)?"}],"k":"blank","a":["false"],"topics":["DISJOINT_SETS"],"x":"1 is a separate root.","part":"f"}],"topics":null},{"id":"61b-sp23-mt2/4","n":"4","t":"4. Two Tree, Three Tree, Red Tree, Black Tree (1100 pts)","b":[{"id":34,"l":[{"p":"(a) What is the maximum number of leaf nodes for a 2-3 tree with height 5? (Height is the greatest number of edges from the root to a leaf.)"}],"k":"blank","a":["243"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"All 3-nodes: 3⁵ = 243 leaves.","part":"a"},{"id":35,"l":[{"p":"(b) What is the maximum number of elements for a 2-3 tree with height 4?"}],"k":"blank","a":["242"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"(1 + 3 + 9 + 27 + 81) nodes × 2 elements = 121 × 2 = 242.","part":"b"},{"s":[{"p":"For (c) and (d), consider the valid 2-3 tree with root [5] and children [1] and [7 8]."}]},{"id":36,"l":[{"p":"(c) What is the minimum number of elements to insert to trigger a change in height?"}],"k":"blank","a":["3"],"topics":["B_TREES","RED_BLACK_TREES"],"x":"One more into [7 8] splits it, filling the root to [5 8]; two more into one of the single-element children then split it and the full root.","part":"c"},{"id":37,"l":[{"p":"(d) What is the maximum number of distinct elements that can be inserted without changing the height of the tree?"}],"k":"blank","a":["4"],"topics":["B_TREES","RED_BLACK_TREES"],"part":"d"},{"s":[{"p":"For (e)–(g), the operations are independent. A single add is performed on a Left-Leaning Red-Black Tree. Which are true?"}]},{"id":38,"l":[{"p":"(e) If a rotateLeft happened, it is immediately followed by a rotateRight (no operations in between)."}],"k":"mc","o":["Always true","Sometimes true","Never true"],"a":1,"topics":["B_TREES","RED_BLACK_TREES"],"part":"e"},{"id":39,"l":[{"p":"(f) If a rotateRight happened, it is immediately followed by a colorFlip."}],"k":"mc","o":["Always true","Sometimes true","Never true"],"a":0,"topics":["B_TREES","RED_BLACK_TREES"],"x":"rotateRight fixes two left reds in a row, which always leaves a node with two red children.","part":"f"},{"id":40,"l":[{"p":"(g) If a colorFlip happened, it is immediately followed by another colorFlip."}],"k":"mc","o":["Always true","Sometimes true","Never true"],"a":1,"topics":["B_TREES","RED_BLACK_TREES"],"part":"g"},{"s":[{"p":"(h) Which of these are not well-formed 2-3 trees? Each is written node(children)."},{"c":"(i)   [8]([5]([4], [7]), [10]([9]))\n(ii)  [8]([4 6]([3], [5], [7]), [10 12]([9], [11], [13]))\n(iii) [5]([1 2 3], [9 10])\n(iv)  [7 10]([3], [8], [13 15])\n(v)   [4 8]([3], [15])","lang":"txt"}]},{"id":41,"l":[{"p":"(h) Select all that are not well-formed 2-3 trees."}],"k":"sata","o":["(i)","(ii)","(iii)","(iv)","(v)"],"a":[0,2,4],"topics":["B_TREES","RED_BLACK_TREES"],"x":"(i): [10] has one child. (iii): a node can’t hold 3 elements. (v): a 2-element node needs 3 children.","part":"h"}],"topics":null},{"id":"61b-sp23-mt2/5","n":"5","t":"5. Tree Shirts (900 pts)","b":[{"s":[{"p":"Crystal stores available shirt sizes in a BST. Fill out findShirt(int reqSize), which returns the smallest Node greater than or equal to the requested size, or null if there is none. For example, with the BST below, findShirt(13) returns the Node with 15."},{"c":"        20\n      /    \\\n    15      27\n   /  \\       \\\n  4    17      30","lang":"txt"},{"c":"public class TreeShirt {\n    private Node root;\n    private class Node {\n        int shirtSize;\n        Node left;\n        Node right;\n    }\n\n    public Node findShirt(int reqSize) {\n        Node prev = null;\n        Node curr = root;\n        while (⟪a⟫) {\n            if (⟪b⟫) {\n                return curr;\n            } else if (⟪c⟫) {\n                ⟪d⟫;\n                ⟪e⟫;\n            } else {\n                ⟪f⟫;\n            }\n        }\n        return ⟪g⟫;\n    }\n}","lang":"java","f":{"a":"curr != null","b":"curr.shirtSize == reqSize","c":"curr.shirtSize > reqSize","d":"prev = curr","e":"curr = curr.left","f":"curr = curr.right","g":"prev"}}]},{"id":42,"l":[{"p":"while (____)"}],"k":"blank","a":["curr != null"],"topics":["BSTS"]},{"id":43,"l":[{"p":"if (____) return curr"}],"k":"blank","a":["curr.shirtSize == reqSize"],"topics":["BSTS"]},{"id":44,"l":[{"p":"else if (____)"}],"k":"blank","a":["curr.shirtSize > reqSize","reqSize < curr.shirtSize"],"topics":["BSTS"]},{"id":45,"l":[{"p":"First line inside it"}],"k":"blank","a":["prev = curr"],"topics":["BSTS"]},{"id":46,"l":[{"p":"Second line inside it"}],"k":"blank","a":["curr = curr.left"],"topics":["BSTS"]},{"id":47,"l":[{"p":"Otherwise"}],"k":"blank","a":["curr = curr.right"],"topics":["BSTS"]},{"id":48,"l":[{"p":"return ____"}],"k":"blank","a":["prev"],"topics":["BSTS"],"x":"Every node larger than reqSize is a candidate: remember it and look left for a smaller one. Smaller nodes send you right. The last remembered candidate is the answer."}],"topics":null},{"id":"61b-sp23-mt2/6","n":"6","t":"6. Hash-ish (900 pts)","b":[{"s":[{"p":"Part 1: Classify each String hash function. Incorrect: not a valid hash function, or buggy. Ineffective: valid, but collisions are easy to find. Correct: valid, and collisions aren’t easy to find (only one answer below is Correct). (The exam also asked for a reason or two colliding words.)"},{"c":"(a) public int hashCode() {\n        Random random = new Random();\n        return this.length * random.nextInt();\n    }\n\n(b) public int hashCode() {\n        Random random = new Random(this.hashCode());\n        return random.nextInt();\n    }\n\n(c) public int hashCode() {\n        return 0;\n    }\n\n(d) public int hashCode() {\n        Random random = new Random(0);\n        int val = 0;\n        for (char c : this.toCharArray()) {\n            val += c * random.nextInt();\n        }\n        return val;\n    }\n\n(e) public int hashcode() {\n        int val = 0;\n        for (char c : this.toCharArray()) {\n            val += c;\n        }\n        return val;\n    }","lang":"java"}]},{"id":49,"l":[{"p":"Part 1 (a)"}],"k":"mc","o":["Incorrect","Ineffective","Correct"],"a":0,"topics":["HASHING"],"x":"An unseeded Random is nondeterministic, so the same string gets different hashes."},{"id":50,"l":[{"p":"Part 1 (b)"}],"k":"mc","o":["Incorrect","Ineffective","Correct"],"a":0,"topics":["HASHING"],"x":"It calls hashCode inside hashCode: infinite recursion."},{"id":51,"l":[{"p":"Part 1 (c)"}],"k":"mc","o":["Incorrect","Ineffective","Correct"],"a":1,"topics":["HASHING"],"x":"Every string collides, e.g. \"pot\" and \"tea\"."},{"id":52,"l":[{"p":"Part 1 (d)"}],"k":"mc","o":["Incorrect","Ineffective","Correct"],"a":2,"topics":["HASHING"],"x":"A fixed seed gives the same weights every time, and different positions get different weights."},{"id":53,"l":[{"p":"Part 1 (e)"}],"k":"mc","o":["Incorrect","Ineffective","Correct"],"a":1,"topics":["HASHING"],"x":"Anagrams collide, e.g. \"tea\" and \"eat\"."},{"s":[{"p":"Part 2: You are an evil hacker with a HashMap of instructor names (Strings). You may only insert elements and time each insertion; you know how the HashMap and the String hash function work but not the data. It uses linked-list bins and resizes when elements / bins exceeds a threshold. It already holds a few values, not all with the same hash, and the hash function distributes values evenly."},{"p":"Possible: it is sometimes impossible with a correct hash function, but always possible with an ineffective one (as defined in Part 1). Impossible: even with an ineffective hash function, it is sometimes impossible."}]},{"id":54,"l":[{"p":"Part 2 (a) Determine how many names were originally in the HashMap."}],"k":"mc","o":["Possible","Impossible"],"a":0,"topics":["HASHING"],"x":"Keep adding names and time each one: resizes are much slower. After two or three resizes you can work out the original count."},{"id":55,"l":[{"p":"Part 2 (b) Determine whether \"Justin\" is in the HashMap, without inserting \"Justin\" yourself."}],"k":"mc","o":["Possible","Impossible"],"a":1,"topics":["HASHING"],"x":"You can’t tell \"Justin\" apart from another value with the same hash."},{"id":56,"l":[{"p":"Part 2 (c) Make it arbitrarily slow for other people to access any name in the HashMap."}],"k":"mc","o":["Possible","Impossible"],"a":1,"topics":["HASHING"],"x":"You’d need the hashes of every element already there, which you can’t find out."},{"id":57,"l":[{"p":"Part 2 (d) \"Justin\" and \"Josh\" were already inserted and have the same hash. Make it arbitrarily slow to access \"Justin\", but still fast to access \"Josh\"."}],"k":"mc","o":["Possible","Impossible"],"a":1,"topics":["HASHING"],"x":"They already sit a fixed distance apart in their bucket; new items can’t be put between them."}],"topics":null},{"id":"61b-sp23-mt2/7","n":"7","t":"7. SHeap (900 pts)","b":[{"s":[{"p":"This array is a min-heap of 7 values, where each symbol is a distinct number (the symbols have no implied order). Index 0 is NULL and index 8 is unused."},{"c":"Index:  0     1  2  3  4  5  6  7  8\nValue:  NULL  !  @  #  $  %  ?  &","lang":"txt"},{"p":"Answer about the heap after removing the minimum value."}]},{"id":58,"l":[{"p":"(a) Which indices might contain & in the resulting min-heap?"}],"k":"sata","o":["1","2","3","4","5","6","7","8"],"a":[1,2,3,4,5],"topics":["HEAPS"],"part":"a"},{"id":59,"l":[{"p":"(b) Which indices might contain % in the resulting min-heap?"}],"k":"sata","o":["1","2","3","4","5","6","7","8"],"a":[1,4],"topics":["HEAPS"],"part":"b"},{"id":60,"l":[{"p":"(c) Which symbols could be at index 4 in the resulting heap?"}],"k":"sata","o":["!","@","#","$","%","?","&"],"a":[3,6],"topics":["HEAPS"],"x":"& moves to the root and sinks along some path. % is under @, so it either stays at 5 or moves up to 2.","part":"c"},{"s":[{"p":"Now return to the original heap and insert ✓."}]},{"id":61,"l":[{"p":"(d) At which indices might ✓ end up?"}],"k":"sata","o":["1","2","3","4","5","6","7","8"],"a":[0,1,3,7],"topics":["HEAPS"],"x":"It starts at index 8 and can only swim up its ancestors: 4, 2, 1.","part":"d"},{"id":62,"l":[{"p":"(e) Which symbols could be at index 2 in the resulting min-heap?"}],"k":"sata","o":["!","@","#","$","%","?","&","✓"],"a":[0,1,7],"topics":["HEAPS"],"part":"e"},{"id":63,"l":[{"p":"(f) Which indices in the resulting array might contain the 3rd smallest value?"}],"k":"sata","o":["1","2","3","4","5","6","7","8"],"a":[1,2,3,4,5,6],"topics":["HEAPS"],"part":"f"}],"topics":null},{"id":"61b-sp23-mt2/8","n":"8","t":"8. Combinatorial Explosion (1500 pts)","b":[{"s":[{"c":"public static int multiply(int a, int b) {\n    int val = 0;\n    for (int i = 0; i < a; i += 1) {\n        val = val + b;\n    }\n    return val;\n}\n\npublic static int fact(int n) {\n    if (n == 0) { return 1; }\n    return multiply(n, fact(n - 1));\n}\n\npublic static int multiplyAll(List<Integer> lst) {\n    Stack<Integer> values = new Stack<>(lst);\n    while (values.size() > 1) {\n        int i = values.remove();\n        int j = values.remove();\n        values.insert(multiply(i, j));\n    }\n    return values.remove();\n}\n\npublic static int grahamHelper(int base, int pow, int iter) {\n    if (iter == 0) { return multiply(base, pow); }\n    if (pow == 0) { return base; }\n    return grahamHelper(base, grahamHelper(base, pow - 1, iter), iter - 1);\n}\n\npublic static int grahamCracker(int n) {\n    g = grahamHelper(3, 3, 4);\n    for (int i = 1; i < 64; i += 1) {\n        g = grahamHelper(3, 3, g);\n    }\n    return g;\n}","lang":"java"},{"p":"Assume all arithmetic operations (+, −, %, and the built-in *, but not multiply) run in constant time. A sum f(1) + … + f(n) is Θ(n·f(n)) if f is polynomial or logarithmic, and Θ(f(n)) if f is exponential or larger."}]},{"id":64,"l":[{"p":"(a) What is the runtime of fact in terms of N?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)"],"a":4,"topics":["ASYMPTOTICS"],"x":"multiply runs in Θ(a); fact calls it with a = 1, 2, …, N.","part":"a"},{"s":[{"p":"(b) lst has N elements, all less than N."}]},{"id":65,"l":[{"p":"(b) multiplyAll best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)"],"a":2,"topics":["ASYMPTOTICS"],"part":"b"},{"id":66,"l":[{"p":"(b) multiplyAll worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)"],"a":8,"topics":["ASYMPTOTICS"],"x":"Best: all 1s. Worst: all N, so the left argument grows N, N², …, N^(N−1), and the last term dominates.","part":"b"},{"id":67,"l":[{"p":"(c) What is the runtime of grahamCracker in terms of N?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)"],"a":0,"topics":["ASYMPTOTICS"],"x":"It computes an enormous number, but never uses n.","part":"c"},{"s":[{"p":"Each change below is independent."}]},{"id":68,"l":[{"p":"(d) The runtime of fact if multiply were replaced with return a * b;"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)"],"a":2,"topics":["ASYMPTOTICS"],"part":"d"},{"id":69,"l":[{"p":"(e) Which correctly describe the runtime of fact if we swapped the arguments, so its last line is return multiply(fact(n-1), n);? Select all that apply."}],"k":"sata","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)","O(1)","O(log N)","O(N)","O(N log N)","O(N²)","O((N−1)!)","O(N!)","O(2ᴺ)","O(N^(N−1))","O(Nᴺ)"],"a":[5,15,16,18,19],"topics":["ASYMPTOTICS"],"x":"multiply now runs on 1, 2!, 3!, …, (N−1)!, which sums to Θ((N−1)!). That’s not Θ(N!) (they differ by a factor of N), and it grows faster than 2ᴺ.","part":"e"},{"s":[{"p":"(f) Replace the stack in multiplyAll with a queue. As before, lst has N elements, all less than N."}]},{"id":70,"l":[{"p":"(f) Best case: select all that apply."}],"k":"sata","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)","O(1)","O(log N)","O(N)","O(N log N)","O(N²)","O((N−1)!)","O(N!)","O(2ᴺ)","O(N^(N−1))","O(Nᴺ)"],"a":[2,12,13,14,15,16,17,18,19],"topics":["ASYMPTOTICS"],"part":"f"},{"id":71,"l":[{"p":"(f) Worst case: select all that apply."}],"k":"sata","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)","Θ((N−1)!)","Θ(N!)","Θ(2ᴺ)","Θ(N^(N−1))","Θ(Nᴺ)","O(1)","O(log N)","O(N)","O(N log N)","O(N²)","O((N−1)!)","O(N!)","O(2ᴺ)","O(N^(N−1))","O(Nᴺ)"],"a":[15,16,18,19],"topics":["ASYMPTOTICS"],"x":"With all values N, the queue multiplies pairs like a binary tree: the last multiplication costs between N^(N/3) and N^(N/2) depending on N, so there is no single Θ bound, but it is O(N^(N/2)), which (N−1)!, N!, N^(N−1) and Nᴺ all bound.","part":"f"}],"topics":null}],"by":["Hug"]},{"id":"61b-sp24-final","t":"Spring 2024 Final","src":{"exam":"https://drive.google.com/file/d/1wLGD_UJeK-AOQkbc4884KvFawdEpeGKj/view","sol":"https://drive.google.com/file/d/1vo_hpCq8LsMSaWpw9PlxqfSIOlE4_4Q0/view","topics":"sp24-final"},"p":[{"id":"61b-sp24-final/1","n":"1","t":"1. Vroom (9 pts)","b":[{"s":[{"p":"For each line, answer CE for compile error, RE for runtime error, OK if it runs without printing, or give the printed result. If a line errors, later lines still run. Classes: TwoWheel has public int topSpeed=200, private boolean counterSteer=true, rideWith(TwoWheel) prints “I’m TwoWheel”, and printSteer() prints counterSteer. Motorcycle extends TwoWheel, sets topSpeed=400, and overrides rideWith to print “I’m moto”. Bicycle extends TwoWheel, sets topSpeed=100, and overrides rideWith to print “I’m bike”."},{"c":"TwoWheel scooter = new TwoWheel();                 // (a)\nMotorcycle kawi = new Motorcycle();                   // (b)\nBicycle trek = new Bicycle();                         // (c)\nMotorcycle.rideWith(kawi);                            // (d)\nkawi.rideWith(trek);                                  // (e)\n((TwoWheel) trek).rideWith(scooter);                  // (f)","lang":"java"}]},{"id":1,"l":[{"p":"(a) Result"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"a"},{"id":2,"l":[{"p":"(b) Result"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"b"},{"id":3,"l":[{"p":"(c) Result"}],"k":"blank","a":["OK"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"c"},{"id":4,"l":[{"p":"(d) Result"}],"k":"blank","a":["CE"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"d"},{"id":5,"l":[{"p":"(e) Result"}],"k":"blank","a":["I'm moto"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"e"},{"id":6,"l":[{"p":"(f) Result"}],"k":"blank","a":["I'm bike"],"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"f"},{"id":7,"l":[{"p":"(g) If printSteer() becomes static while counterSteer stays an instance field, will the class compile?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["JAVA"],"topicsBy":"site","part":"g"},{"id":8,"l":[{"p":"(h) If counterSteer becomes private static, will the class compile?"}],"k":"mc","o":["Yes","No"],"a":0,"topics":["JAVA"],"topicsBy":"site","part":"h"},{"id":9,"l":[{"p":"(i) If topSpeed becomes private, will the subclasses compile?"}],"k":"mc","o":["Yes","No"],"a":1,"topics":["JAVA","INHERITANCE"],"topicsBy":"site","part":"i"}],"topics":null},{"id":"61b-sp24-final/2","n":"2","t":"2. Polynomials (22 pts)","b":[{"s":[{"p":"A Polynomial stores nonzero terms in descending exponent order in a singly linked list, ending with sentinel Term(0,-1). The zero polynomial contains only the sentinel. Implement eval(input), then report runtimes in terms of degree n. For addTerm assume coef != 0, exp >= 0, and no existing nonzero term has exponent exp."},{"c":"public double eval(double input) {\n  double result = 0;\n  ⟪a⟫\n  while (⟪b⟫) {\n    result += ⟪c⟫;\n    ⟪d⟫\n  }\n  ⟪e⟫\n}","lang":"java","f":{"a":"Term currTerm = terms;","b":"currTerm.exp != -1","c":"currTerm.coef * Math.pow(input, currTerm.exp)","d":"currTerm = currTerm.next;","e":"return result;"}}]},{"id":10,"l":[{"p":"(a) Start at the first term"}],"k":"blank","a":["Term currTerm = terms;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":11,"l":[{"p":"(a) Stop at the sentinel"}],"k":"blank","a":["currTerm.exp != -1"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":12,"l":[{"p":"(a) Accumulate a term"}],"k":"blank","a":["currTerm.coef * Math.pow(input, currTerm.exp)"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":13,"l":[{"p":"(a) Advance"}],"k":"blank","a":["currTerm = currTerm.next;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":14,"l":[{"p":"(a) Return the sum"}],"k":"blank","a":["return result;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"a"},{"id":15,"l":[{"p":"(b) Most informative general runtime bound for eval in degree n"}],"k":"blank","a":["O(n)"],"topics":["ASYMPTOTICS","LINKED_LISTS"],"topicsBy":"site","part":"b"},{"s":[{"c":"public void addTerm(int coef, int exp) {\n  Term newTerm = ⟪f⟫;\n  if (⟪g⟫) {\n    ⟪h⟫\n    ⟪i⟫\n    return;\n  }\n  Term curr = ⟪j⟫;\n  while (⟪k⟫) {\n    ⟪l⟫\n  }\n  ⟪m⟫\n  ⟪n⟫\n}","lang":"java","f":{"f":"new Term(coef, exp)","g":"newTerm.exp > terms.exp","h":"newTerm.next = terms;","i":"terms = newTerm;","j":"terms","k":"curr.next.exp > newTerm.exp","l":"curr = curr.next;","m":"newTerm.next = curr.next;","n":"curr.next = newTerm;"}}]},{"id":16,"l":[{"p":"(c) Make the term"}],"k":"blank","a":["new Term(coef, exp)"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":17,"l":[{"p":"(c) Detect insertion before head"}],"k":"blank","a":["newTerm.exp > terms.exp"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":18,"l":[{"p":"(c) Link new head to old head"}],"k":"blank","a":["newTerm.next = terms;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":19,"l":[{"p":"(c) Update head"}],"k":"blank","a":["terms = newTerm;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":20,"l":[{"p":"(c) Start traversal"}],"k":"blank","a":["terms"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":21,"l":[{"p":"(c) Continue while next exponent is larger"}],"k":"blank","a":["curr.next.exp > newTerm.exp"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":22,"l":[{"p":"(c) Advance"}],"k":"blank","a":["curr = curr.next;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":23,"l":[{"p":"(c) Link new term to successor"}],"k":"blank","a":["newTerm.next = curr.next;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":24,"l":[{"p":"(c) Link predecessor to new term"}],"k":"blank","a":["curr.next = newTerm;"],"topics":["LINKED_LISTS","JAVA"],"topicsBy":"site","part":"c"},{"id":25,"l":[{"p":"(d) Most informative general runtime bound for addTerm in terms of n and k"}],"k":"blank","a":["O(n)"],"topics":["ASYMPTOTICS","LINKED_LISTS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp24-final/3","n":"3","t":"3. Disjoint Sets (4 pts)","b":[{"id":26,"l":[{"p":"(a) Is [1, 0, -1, -1, -1] a valid Weighted Quick Union representation?"}],"k":"mc","o":["True","False"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"a"},{"id":27,"l":[{"p":"(b) Is [-1, 2, 3, 4, -4] a valid Weighted Quick Union representation?"}],"k":"mc","o":["True","False"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"b"},{"id":28,"l":[{"p":"(c) Minimum union operations needed to distinguish Quick Union from Weighted Quick Union (both accepted answers)"}],"k":"mc","o":["1","2","3","4"],"a":1,"topics":["DISJOINT_SETS"],"topicsBy":"site","also":[0],"part":"c"},{"id":29,"l":[{"p":"(d) Minimum union operations needed to distinguish Weighted Quick Union from Weighted Quick Union with Path Compression"}],"k":"mc","o":["1","2","3","4"],"a":3,"topics":["DISJOINT_SETS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp24-final/4","n":"4","t":"4. Heaps (7 pts)","b":[{"id":30,"l":[{"p":"(a) Insert 7 into min-heap [−,1,9,3,10,13,4,8]. Result?"}],"k":"mc","o":["[−,1,9,3,7,13,4,8,10]","[−,1,3,7,9,13,4,8,10]","[−,1,3,7,13,9,4,8,10]","[−,1,7,3,9,13,4,8,10]"],"a":3,"topics":["HEAPS"],"topicsBy":"site","part":"a"},{"id":31,"l":[{"p":"(b) Two remove operations from [−,1,9,3,10,13,4,8]. Result?"}],"k":"mc","o":["[−,4,9,8,10,13]","[−,4,8,9,10,13]","[−,4,8,9,13,10]","[−,4,9,8,13,10]"],"a":0,"topics":["HEAPS"],"topicsBy":"site","part":"b"},{"id":32,"l":[{"p":"(c) Give a valid max-heap array with values 1–7 and 21 inversions"}],"k":"blank","a":["[−,7,6,5,4,3,2,1]"],"topics":["HEAPS"],"topicsBy":"site","part":"c"},{"id":33,"l":[{"p":"(d) Give a valid max-heap array with values 1–7 and 12 inversions"}],"k":"blank","a":["[−,7,3,6,1,2,4,5]"],"topics":["HEAPS"],"topicsBy":"site","part":"d"}],"topics":null},{"id":"61b-sp24-final/5","n":"5","t":"5. In-Depth Analysis (5 pts)","b":[{"s":[{"p":"For (a), the pictured undirected graph has edges S–A, S–B, A–B, A–D, B–D, B–E, D–C, D–E, D–T, C–T. Run DFS preorder from S, visiting alphabetically earlier neighbors first."}]},{"id":34,"l":[{"p":"(a) DFS preorder"}],"k":"mc","o":["S,A,B,D,C,T,E","S,A,B,C,D,E,T","S,A,C,T,D,B,E"],"a":0,"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"a"},{"id":35,"l":[{"p":"(b) Maximum nodes in a rooted binary tree of height at most 10 with identical inorder and postorder traversal"}],"k":"blank","a":["11"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":36,"l":[{"p":"(c) Maximum nodes in a rooted binary tree of height at most 10 with identical preorder and postorder traversal"}],"k":"blank","a":["1"],"topics":["TREE_TRAVERSALS"],"topicsBy":"site","part":"c"}],"topics":null},{"id":"61b-sp24-final/6","n":"6","t":"6. ddEei Sort (16 pts)","b":[{"s":[{"p":"Insertion sort starts on [28,97,44,25,11,84]. It has reached [25,28,44,97,11,84], so the first four items are sorted. Append [32,84,28,61], then resume insertion sort."}]},{"id":37,"l":[{"p":"(a) State after four more elements have been inserted in sorted position"}],"k":"blank","a":["[11,25,28,32,44,84,84,97,28,61]"],"topics":["SORTING"],"topicsBy":"site","part":"a"},{"id":38,"l":[{"p":"(b) Additional runtime for P appended items after sorting N items: best case"}],"k":"blank","a":["Θ(P)"],"topics":["ASYMPTOTICS","SORTING"],"topicsBy":"site","part":"b"},{"id":39,"l":[{"p":"(b) Additional runtime for P appended items after sorting N items: worst case"}],"k":"blank","a":["Θ(P(N + P))"],"topics":["ASYMPTOTICS","SORTING"],"topicsBy":"site","part":"b"},{"id":40,"l":[{"p":"(c) Selection sort, with new data appended at any point: always correct?"}],"k":"mc","o":["Always produces a sorted list","Does not always produce a sorted list"],"a":1,"topics":["SORTING"],"topicsBy":"site","part":"c"},{"id":41,"l":[{"p":"(d) Heapsort without in-place heapification, adding new items into the heap: always correct?"}],"k":"mc","o":["Always produces a sorted list","Does not always produce a sorted list"],"a":1,"topics":["SORTING"],"topicsBy":"site","part":"d"},{"id":42,"l":[{"p":"(e) Mergesort, sorted new data merged into a sublist just before a merge: always correct?"}],"k":"mc","o":["Always produces a sorted list","Does not always produce a sorted list"],"a":0,"topics":["SORTING"],"topicsBy":"site","part":"e"},{"id":43,"l":[{"p":"(f) MSD radix sort, insert new data in its matching subproblem before a counting pass: always correct?"}],"k":"mc","o":["Always produces a sorted list","Does not always produce a sorted list"],"a":0,"topics":["SORTING"],"topicsBy":"site","part":"f"},{"id":44,"l":[{"p":"(g) Quicksort with 3-scan partitioning, append new data before a partition: always correct?"}],"k":"mc","o":["Always produces a sorted list","Does not always produce a sorted list"],"a":1,"topics":["SORTING"],"topicsBy":"site","part":"g"}],"topics":null},{"id":"61b-sp24-final/7","n":"7","t":"7. Two Seemingly Unrelated Problems (22 pts)","b":[{"s":[{"p":"Problem I: a connected (weakly connected), unweighted DAG has N nodes."}]},{"id":45,"l":[{"p":"(a) Best-case longest path length, Θ bound"}],"k":"blank","a":["Θ(1)"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":46,"l":[{"p":"(a) Worst-case longest path length, Θ bound"}],"k":"blank","a":["Θ(N)"],"topics":["GRAPH_TRAVERSALS","ASYMPTOTICS"],"topicsBy":"site","part":"a"},{"id":47,"l":[{"p":"(b) Describe extendable best-case graph"}],"k":"blank","a":["One center vertex with a directed edge to every other vertex (an outward star); longest path has one edge."],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"b"},{"id":48,"l":[{"p":"(b) Describe extendable worst-case graph"}],"k":"blank","a":["A directed chain through all N vertices; longest path has N−1 edges."],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"b"},{"s":[{"p":"Problem II: Booksort repeatedly chooses an out-of-place book and shifts it to its correct slot in Θ(1) time. State is a permutation; an edge represents one legal operation. For N=3, states are 123, 213, 132, 231, 312, 321."}]},{"id":49,"l":[{"p":"(c) Give the directed transitions for the N=3 state graph (any equivalent edge list)"}],"k":"blank","a":["213→123; 132→123; 231→123,213,321; 312→123,132,321; 321→132,213"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site","part":"c"},{"id":50,"l":[{"p":"(d) Worst-case runtime if each step scans Θ(N) and chooses the smallest misplaced book"}],"k":"blank","a":["Θ(N²)"],"topics":["ASYMPTOTICS","SORTING"],"topicsBy":"site","part":"d"},{"id":51,"l":[{"p":"(e) Tightest demonstrated lower bound for worst-case runtime when choosing leftmost misplaced book"}],"k":"blank","a":["Ω(2^N)"],"topics":["ASYMPTOTICS","SORTING"],"topicsBy":"site","part":"e"},{"id":52,"l":[{"p":"(f) Why is worst-case runtime O(N!)? Give the state-graph argument."}],"k":"blank","a":["There are N! permutation states. The transition graph is a DAG because the algorithm always terminates; a DAG with N! vertices has paths of length at most N!−1. Each transition costs Θ(1), so runtime is O(N!)."],"topics":["ASYMPTOTICS","SORTING"],"topicsBy":"site","part":"f"}],"topics":null},{"id":"61b-sp24-final/8","n":"8","t":"8. Lost in the Ceryneian H.I.N.D. (15 pts)","b":[{"s":[{"p":"Given a connected weighted undirected graph with positive integer weights, vertices S≠T, and no bridge whose removal disconnects the graph, return an edge whose deletion maximizes the new shortest-path distance from S to T. You may call black-box Dijkstra in Θ(E log V). Design an algorithm running in O(VE log V)."}]},{"id":53,"l":[{"p":"Describe the algorithm"}],"k":"blank","a":["Run Dijkstra on the original graph to recover one shortest S-to-T path. For each edge on that path, temporarily remove it, run Dijkstra again, record the resulting S-to-T distance, and restore the edge. Return the path edge whose removal gives the largest distance."],"topics":["SHORTEST_PATHS","GRAPH_TRAVERSALS"],"topicsBy":"site"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-sp24-mt1","t":"Spring 2024 Midterm 1","src":{"exam":"https://drive.google.com/file/d/1K8oZCuc37EqWlVmrBsES52Vkh-eWmYU-/view","sol":"https://drive.google.com/file/d/1v7odiqpkBhEIVFoHnpfO5uzTKDROO6IP/view","topics":"sp24-mt1"},"p":[{"id":"61b-sp24-mt1/1","n":"1","t":"1. WWJD (15.0 pts)","b":[{"s":[{"c":"public interface Sphere {\n    default void getRadius() { System.out.println(0); }\n}\n\nclass Planet implements Sphere {\n    private int radius = 5;\n\n    @Override\n    public void getRadius() { System.out.println(this.radius); }\n\n    public void orbit(Planet p) { System.out.println(\"orbit planet\"); }\n}\n\nclass Exoplanet extends Planet {\n    static int distance = 10;\n\n    public void getDistance() { System.out.println(distance); }\n\n    @Override\n    public void orbit(Planet p) { System.out.println(\"orbit exoplanet\"); }\n}","lang":"java"},{"p":"(a) For each line of main, write CE for a compile error, RE for a runtime error, OK if it runs but prints nothing, or what it prints. If a line errors, assume the program continues as if it weren’t there."},{"c":"Planet kepler = new Exoplanet();               // 1\nSphere jupiter = new Sphere();                 // 2\nSphere arion = new Exoplanet();                // 3\nPlanet earth = new Planet();                   // 4\n\nkepler.orbit((Exoplanet) arion);               // 5\n((Exoplanet) earth).orbit(kepler);             // 6\n((Exoplanet) kepler).getDistance();            // 7\nearth.getRadius();                             // 8\narion.getDistance();                           // 9\nearth.radius;                                  // 10\nExoplanet.getDistance();                       // 11","lang":"java"}]},{"id":1,"l":[{"p":"(a) Line 1"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":2,"l":[{"p":"(a) Line 2"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"An interface has no constructor.","part":"a"},{"id":3,"l":[{"p":"(a) Line 3"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":4,"l":[{"p":"(a) Line 4"}],"k":"blank","a":["OK"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":5,"l":[{"p":"(a) Line 5"}],"k":"blank","a":["orbit exoplanet","Orbit Exoplanet"],"topics":["INHERITANCE","DMS"],"x":"The signature orbit(Planet) is chosen at compile time; at runtime kepler is an Exoplanet, so its override runs.","part":"a"},{"id":6,"l":[{"p":"(a) Line 6"}],"k":"blank","a":["RE"],"topics":["INHERITANCE","DMS"],"x":"The cast compiles (Planet and Exoplanet are related), but earth is only a Planet: ClassCastException.","part":"a"},{"id":7,"l":[{"p":"(a) Line 7"}],"k":"blank","a":["10"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":8,"l":[{"p":"(a) Line 8"}],"k":"blank","a":["5"],"topics":["INHERITANCE","DMS"],"part":"a"},{"id":9,"l":[{"p":"(a) Line 9"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"Sphere has no getDistance.","part":"a"},{"id":10,"l":[{"p":"(a) Line 10"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"radius is private.","part":"a"},{"id":11,"l":[{"p":"(a) Line 11"}],"k":"blank","a":["CE"],"topics":["INHERITANCE","DMS"],"x":"getDistance isn’t static.","part":"a"},{"id":12,"l":[{"p":"(b) Why would changing line 2 to private default void getRadius() be a compile error?"}],"k":"mc","o":["Methods in an interface must be public.","Default methods cannot print.","Planet already overrides getRadius.","Interfaces cannot have default methods."],"a":0,"topics":["JAVA","INHERITANCE"],"part":"b"},{"s":[{"p":"(c) Within Exoplanet, we define public void fixRadius() { super.radius = 6; }."}]},{"id":13,"l":[{"p":"(c) Which change makes Exoplanet compile?"}],"k":"mc","o":["Change the private keyword to public on Planet’s radius.","Modify fixRadius() to be private.","Modify fixRadius() to be static."],"a":0,"topics":["JAVA","INHERITANCE"],"x":"Subclasses can’t see private fields.","part":"c"},{"id":14,"l":[{"p":"(d) True or false: we can create another interface that extends Sphere."}],"k":"mc","o":["True","False"],"a":0,"topics":["INHERITANCE"],"part":"d"},{"id":15,"l":[{"p":"(e) It is ____ possible to implement two interfaces in the same class."}],"k":"mc","o":["Always","Sometimes","Never"],"a":1,"topics":["INHERITANCE"],"x":"Not if they declare the same method signature with different return types.","part":"e"}],"topics":null},{"id":"61b-sp24-mt1/2","n":"2","t":"2. Comparable Computers (20.0 pts)","b":[{"s":[{"p":"Computer versions are strings of non-negative integers separated by periods, like \"123.4.5\". Implement compareTo: the version with the larger most significant term is greater, and missing terms count as 0, so \"1.2.3\" < \"1.2.4\", \"1.0.0\" equals \"1\", and \"2.0\" > \"1.999\". Hint: Character.getNumericValue(char c) returns the char’s integer value."},{"c":"public class Computer implements Comparable<Computer> {\n    String version;\n    ...\n    @Override\n    public int compareTo(Computer other) {\n        int i = 0, j = 0;\n        while (⟪a⟫ || ⟪b⟫) {\n            int num1 = 0, num2 = 0;\n            while (i < this.version.length() && ⟪c⟫) {\n                char c = this.version.charAt(i);\n                num1 = num1 * 10 + ⟪d⟫;\n                i += 1;\n            }\n            while (j < other.version.length() && ⟪e⟫) {\n                char c = other.version.charAt(j);\n                num2 = num2 * 10 + ⟪f⟫;\n                j += 1;\n            }\n            if (⟪g⟫) {\n                return ⟪h⟫;\n            }\n            i += 1;\n            j += 1;\n        }\n        return ⟪i⟫;\n    }\n}","lang":"java","f":{"a":"i < this.version.length()","b":"j < other.version.length()","c":"this.version.charAt(i) != '.'","d":"Character.getNumericValue(c)","e":"other.version.charAt(j) != '.'","f":"Character.getNumericValue(c)","g":"num1 != num2","h":"num1 - num2","i":"0"}}]},{"id":16,"l":[{"p":"(a) The first condition"}],"k":"blank","a":["i < this.version.length()","i < version.length()"],"topics":["JAVA","COMPARATORS"],"part":"a"},{"id":17,"l":[{"p":"(b) The second condition"}],"k":"blank","a":["j < other.version.length()"],"topics":["JAVA","COMPARATORS"],"part":"b"},{"id":18,"l":[{"p":"(c) Stop the first inner loop at a period"}],"k":"blank","a":["this.version.charAt(i) != '.'","version.charAt(i) != '.'"],"topics":["JAVA","COMPARATORS"],"part":"c"},{"id":19,"l":[{"p":"(d) num1 = num1 * 10 + ____"}],"k":"blank","a":["Character.getNumericValue(c)"],"topics":["JAVA","COMPARATORS"],"part":"d"},{"id":20,"l":[{"p":"(e) Stop the second inner loop at a period"}],"k":"blank","a":["other.version.charAt(j) != '.'"],"topics":["JAVA","COMPARATORS"],"part":"e"},{"id":21,"l":[{"p":"(f) num2 = num2 * 10 + ____"}],"k":"blank","a":["Character.getNumericValue(c)"],"topics":["JAVA","COMPARATORS"],"part":"f"},{"id":22,"l":[{"p":"(g) if (____)"}],"k":"blank","a":["num1 != num2"],"topics":["JAVA","COMPARATORS"],"part":"g"},{"id":23,"l":[{"p":"(h) return ____"}],"k":"blank","a":["num1 - num2","Integer.compare(num1, num2)"],"topics":["JAVA","COMPARATORS"],"part":"h"},{"id":24,"l":[{"p":"(i) return ____ at the end"}],"k":"blank","a":["0"],"topics":["JAVA","COMPARATORS"],"x":"Read one term from each version at a time (0 once a version runs out) and compare; the i += 1 and j += 1 skip the period.","part":"i"}],"topics":null},{"id":"61b-sp24-mt1/3","n":"3","t":"3. Connect The Dots (20.0 pts)","b":[{"s":[{"p":"paper is a rectangular 2-D array containing exactly one copy of each of 1, 2, …, n and 0s elsewhere. Lines are drawn from cell 1 to cell 2, 2 to 3, … up to n. lineLength returns the total length (adjacent cells are distance 1 apart). For example, for this paper with n = 6 the lines measure √5, √13, √2, 3 and 2, about 12.256."},{"c":"0 0 0 2\n0 1 0 0\n0 0 0 0\n0 3 0 0\n4 6 0 5","lang":"txt"},{"c":"public class Point {\n    public int x;\n    public int y;\n    public Point(int x, int y) { this.x = x; this.y = y; }\n}\n\npublic static double distance(Point a, Point b) {\n    ⟪a⟫;\n}","lang":"java","f":{"a":"return Math.sqrt(Math.pow((b.x - a.x), 2) + Math.pow((b.y - a.y), 2))"}}]},{"id":25,"l":[{"p":"(a) distance (one line)"}],"k":"blank","a":["return Math.sqrt(Math.pow((b.x - a.x), 2) + Math.pow((b.y - a.y), 2))","return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2))","return Math.sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y))","return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y))"],"topics":["JAVA"],"part":"a"},{"s":[{"c":"public static double lineLength(int[][] paper, int n) {\n    Point[] points = ⟪b⟫;\n    for (int i = 0; ⟪c⟫; i += 1) {\n        for (int j = 0; ⟪d⟫; j += 1) {\n            int z = paper[i][j];\n            ⟪e⟫;\n        }\n    }\n    double total = 0.0;\n    for (int k = ⟪f⟫; ⟪g⟫; k += 1) {\n        ⟪h⟫;\n    }\n    return total;\n}","lang":"java","f":{"b":"new Point[n + 1]","c":"i < paper.length","d":"j < paper[0].length","e":"points[z] = new Point(i, j)","f":"2","g":"k < points.length","h":"total += distance(points[k - 1], points[k])"}}]},{"id":26,"l":[{"p":"(b) Point[] points = ____"}],"k":"blank","a":["new Point[n + 1]"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":27,"l":[{"p":"(b) Outer loop condition"}],"k":"blank","a":["i < paper.length"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":28,"l":[{"p":"(b) Inner loop condition"}],"k":"blank","a":["j < paper[0].length","j < paper[i].length"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":29,"l":[{"p":"(b) Inner loop body (after int z = paper[i][j])"}],"k":"blank","a":["points[z] = new Point(i, j)"],"topics":["ARRAYS","ITERATION"],"x":"Every 0 overwrites points[0], which is never used.","part":"b"},{"id":30,"l":[{"p":"(b) k starts at"}],"k":"blank","a":["2"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":31,"l":[{"p":"(b) k’s loop condition"}],"k":"blank","a":["k < points.length","k <= n"],"topics":["ARRAYS","ITERATION"],"part":"b"},{"id":32,"l":[{"p":"(b) The loop body"}],"k":"blank","a":["total += distance(points[k - 1], points[k])","total += distance(points[k], points[k - 1])"],"topics":["ARRAYS","ITERATION"],"part":"b"}],"topics":null},{"id":"61b-sp24-mt1/4","n":"4","t":"4. Class Signatures (13.0 pts)","b":[{"s":[{"p":"Fill in the class signatures so that this code compiles and runs without errors."},{"c":"B bb = new B();\nA aa = new A();\nA ab = new B();\nD db = new B();\nA ac = new C();\nB bc = new C();\nA ad = new D();\nE ed = new D();\n\npublic __(a)__ A { ... }\npublic __(b)__ B __(f)__ __(g)__ { ... }\npublic __(c)__ C __(h)__ __(i)__ { ... }\npublic __(d)__ D extends __(j)__ implements __(k)__ { ... }\npublic __(e)__ E {\n    public default void e() {\n        System.out.println(\"E!\");\n    }\n}","lang":"java"}]},{"id":33,"l":[{"p":"(a)"}],"k":"mc","o":["class","interface"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"a"},{"id":34,"l":[{"p":"(b)"}],"k":"mc","o":["class","interface"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"b"},{"id":35,"l":[{"p":"(c)"}],"k":"mc","o":["class","interface"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"c"},{"id":36,"l":[{"p":"(d)"}],"k":"mc","o":["class","interface"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"d"},{"id":37,"l":[{"p":"(e)"}],"k":"mc","o":["class","interface"],"a":1,"topics":["JAVA","INHERITANCE"],"x":"Only an interface has default methods; A–D are instantiated, so they’re classes.","part":"e"},{"id":38,"l":[{"p":"(f)"}],"k":"mc","o":["extends","implements"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"f"},{"id":39,"l":[{"p":"(g)"}],"k":"mc","o":["A","B","C","D","E"],"a":3,"topics":["JAVA","INHERITANCE"],"part":"g"},{"id":40,"l":[{"p":"(h)"}],"k":"mc","o":["extends","implements"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"h"},{"id":41,"l":[{"p":"(i)"}],"k":"mc","o":["A","B","C","D","E"],"a":1,"topics":["JAVA","INHERITANCE"],"part":"i"},{"id":42,"l":[{"p":"(j)"}],"k":"mc","o":["A","B","C","D","E"],"a":0,"topics":["JAVA","INHERITANCE"],"part":"j"},{"id":43,"l":[{"p":"(k)"}],"k":"mc","o":["A","B","C","D","E"],"a":4,"topics":["JAVA","INHERITANCE"],"x":"From the assignments: B is a D and an A, C is a B, D is an A and an E. So A ← D ← B ← C, and D implements E.","part":"k"}],"topics":null},{"id":"61b-sp24-mt1/5","n":"5","t":"5. HOF (16.0 pts)","b":[{"s":[{"p":"Func<A, B> represents a function: B apply(A x). Complete compose, which takes f and g and returns a function that computes g(f(x)), along with the Helper class."},{"c":"interface Func<A, B> {\n    B apply(A x);\n}\n\nclass Composer<X, Y, Z> {\n    Func<X, ⟪a⟫> compose(Func<X, Y> f, Func<Y, Z> g) {\n        return ⟪b⟫;\n    }\n\n    private class Helper implements Func<⟪c⟫, ⟪d⟫> {\n        Func<X, Y> f;\n        Func<Y, Z> g;\n\n        Helper(Func<X, Y> f, Func<Y, Z> g) {\n            ⟪e⟫;\n            ⟪f⟫;\n        }\n\n        @Override\n        public ⟪g⟫ apply(⟪h⟫ x) {\n            return ⟪i⟫;\n        }\n    }\n}","lang":"java","f":{"a":"Z","b":"new Helper(f, g)","c":"X","d":"Z","e":"this.f = f","f":"this.g = g","g":"Z","h":"X","i":"g.apply(f.apply(x))"}}]},{"id":44,"l":[{"p":"(a) compose returns Func<X, ____>"}],"k":"blank","a":["Z"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"a"},{"id":45,"l":[{"p":"(b) compose returns"}],"k":"blank","a":["new Helper(f, g)"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"b"},{"id":46,"l":[{"p":"(c) Helper implements Func<____, …>"}],"k":"blank","a":["X"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"c"},{"id":47,"l":[{"p":"(d) …and the second type"}],"k":"blank","a":["Z"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"d"},{"id":48,"l":[{"p":"(e) Constructor, first line"}],"k":"blank","a":["this.f = f"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"e"},{"id":49,"l":[{"p":"(f) Constructor, second line"}],"k":"blank","a":["this.g = g"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"f"},{"id":50,"l":[{"p":"(g) apply’s return type"}],"k":"blank","a":["Z"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"g"},{"id":51,"l":[{"p":"(h) apply’s parameter type"}],"k":"blank","a":["X"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"part":"h"},{"id":52,"l":[{"p":"(i) apply returns"}],"k":"blank","a":["g.apply(f.apply(x))"],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"x":"Apply f first, then g. f.apply(g.apply(x)) computes f(g(x)) and wouldn’t compile when X, Y and Z differ.","part":"i"}],"topics":null},{"id":"61b-sp24-mt1/6","n":"6","t":"6. Lost in Pointers (16.0 pts)","b":[{"s":[{"p":"A circular DLList with a sentinel had exactly one next or prev pointer changed to point to another node (or the sentinel). Write fixDLList, defined inside DLList, to restore it."},{"c":"public void fixDLList() {\n    int count = 0;\n    for (Node n = ⟪a⟫; count <= size && n != sentinel; ⟪b⟫) {\n        ⟪c⟫;\n    }\n    if (count == size) { // The wrong pointer is a .prev pointer\n        sentinel.next.prev = ⟪d⟫;\n        for (⟪e⟫; n != sentinel; n = n.next) {\n            ⟪f⟫;\n        }\n    } else { // The wrong pointer is a .next pointer\n        sentinel.prev.next = ⟪g⟫;\n        for (⟪h⟫; n != sentinel; n = n.prev) {\n            ⟪i⟫;\n        }\n    }\n}","lang":"java","f":{"a":"sentinel.next","b":"n = n.next","c":"count += 1","d":"sentinel","e":"Node n = sentinel.next","f":"n.next.prev = n","g":"sentinel","h":"Node n = sentinel.prev","i":"n.prev.next = n"}}]},{"id":53,"l":[{"p":"(a) n starts at"}],"k":"blank","a":["sentinel.next"],"topics":["LINKED_LISTS","DEQUES"],"part":"a"},{"id":54,"l":[{"p":"(b) The update"}],"k":"blank","a":["n = n.next"],"topics":["LINKED_LISTS","DEQUES"],"part":"b"},{"id":55,"l":[{"p":"(c) The loop body"}],"k":"blank","a":["count += 1","count++"],"topics":["LINKED_LISTS","DEQUES"],"part":"c"},{"id":56,"l":[{"p":"(d) sentinel.next.prev = ____"}],"k":"blank","a":["sentinel"],"topics":["LINKED_LISTS","DEQUES"],"part":"d"},{"id":57,"l":[{"p":"(e) Start of the loop"}],"k":"blank","a":["Node n = sentinel.next"],"topics":["LINKED_LISTS","DEQUES"],"part":"e"},{"id":58,"l":[{"p":"(f) Its body"}],"k":"blank","a":["n.next.prev = n"],"topics":["LINKED_LISTS","DEQUES"],"part":"f"},{"id":59,"l":[{"p":"(g) sentinel.prev.next = ____"}],"k":"blank","a":["sentinel"],"topics":["LINKED_LISTS","DEQUES"],"part":"g"},{"id":60,"l":[{"p":"(h) Start of the loop"}],"k":"blank","a":["Node n = sentinel.prev"],"topics":["LINKED_LISTS","DEQUES"],"part":"h"},{"id":61,"l":[{"p":"(i) Its body"}],"k":"blank","a":["n.prev.next = n"],"topics":["LINKED_LISTS","DEQUES"],"x":"Walking the next pointers reaches the sentinel after exactly size steps only if every next pointer is right (a bad one skips ahead or loops back, hence count <= size). Then rebuild the other direction from the correct one.","part":"i"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-sp24-mt2","t":"Spring 2024 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1TzUHigkQEWfNvE3zqYGWf7df_tlSAWze/view","sol":"https://drive.google.com/file/d/1nDEB63ldnM5qCExsbhz5xmEBXW0Bgm7T/view","topics":"sp24-mt2"},"p":[{"id":"61b-sp24-mt2/1","n":"1","t":"1. Potpourri (22.0 pts)","b":[{"s":[{"p":"For the first two parts, consider the following BST of unique integer elements:"},{"c":"            P\n          /   \\\n         E     Y\n        / \\     \\\n       R   I     N\n          / \\\n         K   A\n        /\n       O","lang":"txt"}]},{"id":1,"l":[{"p":"(a) How many elements must be greater than the element at node K?"}],"k":"blank","a":["5"],"topics":["BSTS"],"x":"I, A, P, Y and N must all be greater than K, by the BST search property.","part":"a"},{"id":2,"l":[{"p":"(b) In what order will a post-order traversal, starting at node P, visit the nodes?"}],"k":"mc","o":["P, E, Y, R, I, N, K, A, O","R, O, K, A, I, E, N, Y, P","O, K, A, R, I, E, N, Y, P"],"a":1,"topics":["TREE_TRAVERSALS"],"part":"b"},{"id":3,"l":[{"p":"(c) True or false: it is possible for a rooted tree with more than 1 node to be simultaneously a valid max-heap and a valid BST."}],"k":"mc","o":["True","False"],"a":0,"topics":["BSTS","HEAPS"],"x":"For example, 2 with a single left child 1.","part":"c"},{"id":4,"l":[{"p":"(d) How many positions within a min-heap with 2ᴺ − 1 elements (where the height of the heap is N − 1) could the maximum element potentially occupy? Assume there are no duplicate elements and the heap is not empty."}],"k":"mc","o":["log(N)","N","2^(N−1)","2^N"],"a":2,"topics":["HEAPS"],"x":"The maximum is unique, so it must be a leaf. With 2ᴺ − 1 elements the bottom level (depth N − 1) is full and holds all the leaves: 2ᴺ⁻¹ positions.","part":"d"},{"id":5,"l":[{"p":"(e) True or false: Dijkstra’s algorithm always works on both directed and undirected graphs with positive edge weights."}],"k":"mc","o":["True","False"],"a":0,"topics":["SHORTEST_PATHS"],"x":"Treat each undirected edge as two directed edges.","part":"e"},{"id":6,"l":[{"p":"(f) True or false: A* always runs asymptotically faster than Dijkstra’s algorithm."}],"k":"mc","o":["True","False"],"a":1,"topics":["SHORTEST_PATHS"],"x":"In the worst case A* still visits every node and relaxes every edge before reaching the goal.","part":"f"},{"id":7,"l":[{"p":"(g) True or false: A* may not need to visit all nodes before completing."}],"k":"mc","o":["True","False"],"a":0,"topics":["SHORTEST_PATHS"],"x":"A* stops once it reaches the goal.","part":"g"},{"id":8,"l":[{"p":"(h) True or false: Kruskal’s algorithm always works on graphs with negative edge weights."}],"k":"mc","o":["True","False"],"a":0,"topics":["MSTS"],"x":"Kruskal’s only uses the edges’ relative order.","part":"h"},{"id":9,"l":[{"p":"(i) True or false: Prim’s algorithm always works on graphs with negative edge weights."}],"k":"mc","o":["True","False"],"a":0,"topics":["MSTS"],"x":"Prim’s picks the lightest edge across each cut, so it too only uses the edges’ relative order.","part":"i"},{"id":10,"l":[{"p":"(j) True or false: in a directed acyclic graph, any post-order traversal that visits all nodes is a valid topological sort."}],"k":"mc","o":["True","False"],"a":1,"topics":["TOPOLOGICAL_SORT"],"x":"It’s the reverse of a post-order that gives a topological sort.","part":"j"}],"topics":null},{"id":"61b-sp24-mt2/2","n":"2","t":"2. Awesometotics (22.0 pts)","b":[{"s":[{"p":"For (a) through (d), give the asymptotic behavior, with respect to N, of each scenario, in Θ notation. (On the exam these were write-in boxes.)"}]},{"id":11,"l":[{"p":"(a) An ArrayList is implemented with additive resizing, then N elements are added to it. What is the maximum number of unused indices in the underlying array?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":0,"topics":["ARRAYS","ASYMPTOTICS"],"x":"Each resize adds a constant amount of space, so at most that constant is unused, whatever the details.","part":"a"},{"id":12,"l":[{"p":"(b) An ArrayList is implemented with multiplicative resizing, then N elements are added to it. What is the maximum number of unused indices in the underlying array?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ARRAYS","ASYMPTOTICS"],"x":"If the last add triggers a doubling, the array has 2N slots and N are unused.","part":"b"},{"s":[{"p":"(c) You create a weighted quick union without path compression, containing N elements, then perform ⌊√N⌋ calls to union. You look at the underlying array and take the sum of the absolute values of all elements. For example, for [−4, 2, 0, 0] the sum is |−4| + |2| + |0| + |0| = 6."}]},{"id":13,"l":[{"p":"(c) Smallest possible sum"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":3,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"part":"c"},{"id":14,"l":[{"p":"(c) Largest possible sum"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":5,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"x":"The negative entries (−size of each root) always sum to −N, so the sum is at least N; connecting small indices (1 to √N under 0) adds only O(√N). After √N unions at most √N entries are positive, each at most about N: connect N − 2 … N − √N − 2 under N − 1 for Θ(N√N).","part":"c"},{"s":[{"p":"(d) A list of positive integers (not necessarily of length N) sums to N². All elements are inserted, one at a time, into a min-heap. What are the best- and worst-case runtimes for all the insertions?"}]},{"id":15,"l":[{"p":"(d) Best case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":0,"topics":["ASYMPTOTICS","HEAPS"],"part":"d"},{"id":16,"l":[{"p":"(d) Worst case"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":6,"topics":["ASYMPTOTICS","HEAPS"],"also":[7],"x":"Best: a constant number of items, e.g. [N²]. Worst: N² ones gives at least Θ(N²), and N² inserts of O(log N) each is at most O(N² log N). Staff accepted any bound in that range; they believe Θ(N²) is tight.","part":"d"},{"s":[{"p":"For (e) and (f), give the best- and worst-case runtimes for the functions below."},{"c":"public static void f1(int N) {\n    for (int i = 0; i < N; i += 1) {\n        for (int j = i; j < N; j += 1) {\n            if (j % 2 == 0) {\n                i += 1;\n            }\n            System.out.println(\"naming things is hard - Dylan\");\n        }\n    }\n}","lang":"java"}]},{"id":17,"l":[{"p":"(e) f1 best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS","ITERATION"],"part":"e"},{"id":18,"l":[{"p":"(e) f1 worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS","ITERATION"],"x":"The inner loop also advances i by half its length, so the outer iterations do N, N/2, N/4, … work: Θ(N) in total.","part":"e"},{"s":[{"c":"public static void f2(int N) {\n    if (N < 2) {\n        return;\n    }\n    f2(N/2);\n    for (int i = 0; i < Math.sqrt(N); i += 1) {\n        System.out.println(\"Aniruth Narayanan aka the Baller\");\n    }\n    f2(N/2);\n}","lang":"java"}]},{"id":19,"l":[{"p":"(f) f2 best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS","RECURSION"],"part":"f"},{"id":20,"l":[{"p":"(f) f2 worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(N⁴)","Θ(N⁴ log N)","Worse than Θ(N⁴ log N)","Never terminates (infinite loop)","None of the above"],"a":4,"topics":["ASYMPTOTICS","RECURSION"],"x":"Level k of the call tree has 2ᵏ calls doing √(N/2ᵏ) work each, so √N · (1 + √2 + √4 + … + √N). That geometric series is dominated by its last term √N, giving Θ(N).","part":"f"}],"topics":null},{"id":"61b-sp24-mt2/3","n":"3","t":"3. It’s All a Blur (18.0 pts)","b":[{"s":[{"p":"Noah creates a unified Node class that can act as the node of either a DLList or a BST:"},{"c":"class Node {\n    int item;\n    Node prev;    // The previous node in a DLList, or the left child in a BST\n    Node next;    // The next node in a DLList, or the right child in a BST\n}","lang":"java"},{"p":"Using these Nodes directly, Noah can connect them as a circular doubly-linked list with one sentinel, or as a binary search tree. For example, the list sentinel ⇄ A ⇄ B ⇄ C ⇄ D ⇄ E ⇄ F ⇄ G (circular) can become the BST with D at the root, B and F as its children, and A, C, E, G as leaves."},{"p":"Complete treeify. Input: the sentinel Node of a doubly-linked list. Behavior: modifies the next and prev pointers of each Node so the Nodes form a complete binary search tree. Output: the root Node of the resulting tree. In the example, treeify(sentinel) changes D.prev from C to B, D.next from E to F, C.next from D to null, and so on, then returns D."},{"p":"You may assume the list is not empty, the number of non-sentinel items is one less than a power of two, and the items are sorted in strictly increasing order. You may not create new Nodes or use any DLList or BST methods."},{"c":"public static Node treeify(Node sentinel) {\n    return helper(sentinel.next, sentinel.prev);\n}\n\nprivate static Node helper(Node begin, Node end) {\n    if (begin == end) {\n        begin.prev = null;\n        begin.next = null;\n        return begin;\n    }\n    Node forward = ⟪a⟫;\n    Node backward = ⟪b⟫;\n    while (forward != backward) {\n        ⟪c⟫;\n        ⟪d⟫;\n    }\n    ⟪e⟫;\n    ⟪f⟫;\n    return ⟪g⟫;\n}","lang":"java","f":{"a":"begin","b":"end","c":"forward = forward.next","d":"backward = backward.prev","e":"forward.prev = helper(begin, forward.prev)","f":"forward.next = helper(forward.next, end)","g":"forward"}}]},{"id":21,"l":[{"p":"(a) Node forward = ____"}],"k":"blank","a":["begin","begin.next"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":22,"l":[{"p":"(a) Node backward = ____"}],"k":"blank","a":["end","end.prev"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":23,"l":[{"p":"(a) First line of the while loop (the two lines can go in either order)"}],"k":"blank","a":["forward = forward.next","backward = backward.prev"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":24,"l":[{"p":"(a) Second line of the while loop"}],"k":"blank","a":["backward = backward.prev","forward = forward.next"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":25,"l":[{"p":"(a) First line after the loop"}],"k":"blank","a":["forward.prev = helper(begin, forward.prev)","backward.prev = helper(begin, backward.prev)","forward.prev = helper(begin, backward.prev)","backward.prev = helper(begin, forward.prev)"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":26,"l":[{"p":"(a) Second line after the loop"}],"k":"blank","a":["forward.next = helper(forward.next, end)","backward.next = helper(backward.next, end)","forward.next = helper(backward.next, end)","backward.next = helper(forward.next, end)"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"part":"a"},{"id":27,"l":[{"p":"(a) return ____"}],"k":"blank","a":["forward","backward"],"topics":["LINKED_LISTS","BSTS","RECURSION"],"x":"Walk one pointer forward from begin and one backward from end until they meet at the middle item: that is the root. Then treeify the left half (begin to the root’s prev) and the right half (the root’s next to end). After the loop forward == backward, so either name works.","part":"a"},{"id":28,"l":[{"p":"(b) What is the runtime of treeify on a list of N nodes, where N is one less than a power of 2?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(√N)","Θ(N)","Θ(N log N)","Θ(N√N)","Θ(N²)","Θ(N² log N)","Θ(N³)"],"a":4,"topics":["ASYMPTOTICS"],"x":"Each call does linear work to find the middle, then recurses on two halves, like mergesort: N work per level, log N levels.","part":"b"}],"topics":null},{"id":"61b-sp24-mt2/4","n":"4","t":"4. Lost in LLRBs (18.0 pts)","b":[{"s":[{"p":"A hacker paints all the links of your (previously valid) LLRB black. An LLRB node is red if the link to its parent is red, and black if it is the root or the link to its parent is black."},{"c":"          D\n        /   \\\n       B     F\n      / \\   /\n     A   C E","lang":"txt"}]},{"id":29,"l":[{"p":"(a) Select all nodes that must be red for this LLRB to be valid."}],"k":"sata","o":["A","B","C","E","F","None of the above"],"a":[1,3],"topics":["RED_BLACK_TREES"],"part":"a"},{"s":[{"p":"(b) Write fixLLRB, which restores the correct colors to all nodes without otherwise modifying the tree. Your code must be asymptotically optimal, and may not use any LLRB methods or attributes not listed."},{"c":"public class LLRB {\n    private class Node {\n        int value;\n        Node left;\n        Node right;\n        boolean isRed;\n    }\n\n    private Node root;\n\n    public void fixLLRB() {\n        helper(root);\n    }\n\n    private ⟪a⟫ helper(Node n) {\n        if (⟪b⟫) {\n            return ⟪c⟫;\n        }\n        int leftHeight = ⟪d⟫;\n        int rightHeight = ⟪e⟫;\n        if (⟪f⟫) {\n            n.left.isRed = true;\n        }\n        return ⟪g⟫;\n    }\n}","lang":"java","f":{"a":"int","b":"n == null","c":"0","d":"helper(n.left)","e":"helper(n.right)","f":"leftHeight != rightHeight","g":"rightHeight + 1"}}]},{"id":30,"l":[{"p":"(b) helper’s return type"}],"k":"blank","a":["int"],"topics":["RED_BLACK_TREES","RECURSION"],"part":"b"},{"id":31,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["n == null"],"topics":["RED_BLACK_TREES","RECURSION"],"part":"b"},{"id":32,"l":[{"p":"(b) return ____ (the base case)"}],"k":"blank","a":["0","1","-1"],"topics":["RED_BLACK_TREES","RECURSION"],"x":"Any constant works: every height shifts by the same amount.","part":"b"},{"id":33,"l":[{"p":"(b) int leftHeight = ____"}],"k":"blank","a":["helper(n.left)","helper(n.left) + 1"],"topics":["RED_BLACK_TREES","RECURSION"],"part":"b"},{"id":34,"l":[{"p":"(b) int rightHeight = ____"}],"k":"blank","a":["helper(n.right)","helper(n.right) + 1"],"topics":["RED_BLACK_TREES","RECURSION"],"part":"b"},{"id":35,"l":[{"p":"(b) if (____) n.left.isRed = true"}],"k":"blank","a":["leftHeight != rightHeight","leftHeight > rightHeight","leftHeight == rightHeight + 1","rightHeight < leftHeight","leftHeight - 1 == rightHeight"],"topics":["RED_BLACK_TREES","RECURSION"],"part":"b"},{"id":36,"l":[{"p":"(b) return ____"}],"k":"blank","a":["rightHeight + 1","Math.min(leftHeight, rightHeight) + 1"],"topics":["RED_BLACK_TREES","RECURSION"],"x":"helper returns a node’s height in the corresponding 2-3 tree. Right links are always black, so the right subtree is exactly one level down. If the left subtree is taller than the right, the left link must be red (red links don’t add height). (If you added 1 to both heights in (d) and (e), adjust the return accordingly; the exam’s rubric accepted consistent variants.)","part":"b"}],"topics":null},{"id":"61b-sp24-mt2/5","n":"5","t":"5. I Love Hashbrowns (12.0 pts)","b":[{"s":[{"p":"Consider two hashCodes: the default hashCode (from Object, the memory address) and the trivial hashCode (always returns 0). Also consider two equals methods: the default equals (from Object, which uses ==) and the trivial equals (always returns true). In (c) and (d), “all equals methods” means any possible equals method, not just these two."}]},{"id":37,"l":[{"p":"(a) The default hashCode is a valid hashCode for the trivial equals method."}],"k":"mc","o":["True","False"],"a":1,"topics":["EQUALS","HASHING"],"x":"Trivial equals makes every pair of objects equal, so a valid hashCode must give them all the same code. Memory addresses differ.","part":"a"},{"id":38,"l":[{"p":"(b) The trivial hashCode is a valid hashCode for the trivial equals method."}],"k":"mc","o":["True","False"],"a":0,"topics":["EQUALS","HASHING"],"x":"Every object gets 0, so equal objects (all of them) share a hash code.","part":"b"},{"id":39,"l":[{"p":"(c) The trivial hashCode is a valid hashCode for all equals methods."}],"k":"mc","o":["True","False"],"a":0,"topics":["EQUALS","HASHING"],"x":"It’s always the same integer, so any two equal objects always have equal hash codes.","part":"c"},{"id":40,"l":[{"p":"(d) The default hashCode is a valid hashCode for all equals methods."}],"k":"mc","o":["True","False"],"a":1,"topics":["EQUALS","HASHING"],"x":"(a) is a counterexample: it fails for the trivial equals.","part":"d"},{"id":41,"l":[{"p":"(e) The only valid hashCode (over all possible hashCodes) for the default equals method is the default hashCode."}],"k":"mc","o":["True","False"],"a":1,"topics":["EQUALS","HASHING"],"x":"The trivial hashCode is valid for every equals, including the default.","part":"e"},{"id":42,"l":[{"p":"(f) The only valid hashCode (over all possible hashCodes) for the trivial equals method is the trivial hashCode."}],"k":"mc","o":["True","False"],"a":1,"topics":["EQUALS","HASHING"],"x":"Any constant hashCode (always 1, always 5, …) is also valid.","part":"f"}],"topics":null},{"id":"61b-sp24-mt2/6","n":"6","t":"6. Where’s Prim? (8.0 pts)","b":[{"s":[{"p":"An undirected graph with these weighted edges:"},{"c":"A — B   1\nA — D   3\nB — C   3\nB — E   8\nC — E   5\nC — F   13\nD — E   3\nD — G   5\nE — G   4","lang":"txt"},{"p":"(a) We run Dijkstra’s on this graph from A. After visiting A and B, distTo is A 0, B 1, C 4, D 3, E 9, F ∞, G ∞. Fill in distTo after visiting one more node and relaxing all of its outgoing edges."}]},{"id":43,"l":[{"p":"(a) distTo for A, B, C, D, E, F, G, in that order, separated by commas (write ∞ or inf for infinity)"}],"k":"blank","a":["0, 1, 4, 3, 6, ∞, 8","0, 1, 4, 3, 6, inf, 8","0, 1, 4, 3, 6, infinity, 8","0, 1, 4, 3, 6, Infinity, 8","0 1 4 3 6 ∞ 8","0 1 4 3 6 inf 8","0 1 4 3 6 infinity 8","0 1 4 3 6 Infinity 8"],"topics":["SHORTEST_PATHS"],"x":"The next node is D (lowest unvisited distTo). Relaxing its edges improves E from 9 to 6 (A → D → E) and G from ∞ to 8 (A → D → G).","part":"a"},{"id":44,"l":[{"p":"(b) What is the sum of the edge weights in the minimum spanning tree of the graph?"}],"k":"blank","a":["27"],"topics":["MSTS"],"x":"AB 1 + AD 3 + BC 3 + DE 3 + EG 4 + CF 13 = 27.","part":"b"},{"id":45,"l":[{"p":"(c) Which edges are guaranteed to be in all (not necessarily minimum) spanning trees? Select all that apply."}],"k":"sata","o":["AB","AD","BC","BE","CE","CF","DE","DG","EG","None of the above"],"a":[5],"topics":["MSTS"],"x":"CF is the only edge that reaches F. Every other node can be reached by more than one edge, so each other edge can be left out of some spanning tree.","part":"c"},{"id":46,"l":[{"p":"(d) You add a new edge between F and G with weight x, and the MST of the modified graph has a lower total weight than the original MST. What is the maximum integer value that x could be?"}],"k":"blank","a":["12"],"topics":["MSTS"],"x":"With FG in place of CF, the MST weighs 1 + 3 + 3 + 3 + 4 + x = 14 + x. That must be less than 27, so x < 13: at most 12.","part":"d"}],"topics":null}],"by":["Yokota","Kao"]},{"id":"61b-sp25-final","t":"Spring 2025 Final","src":{"exam":"https://drive.google.com/file/d/1EL58K7Sk7QRiQ2jnNdZ9I_qM9z6bfjA1/view","sol":"https://drive.google.com/file/d/1C2ZX6Gy3OMkiVwxV9eUpWUzrSA1rxj0_/view","topics":"sp25-final"},"p":[{"id":"61b-sp25-final/1","n":"1","t":"1. Potpourri (14 pts)","b":[{"id":1,"l":[{"p":"Does a standard BST guarantee logarithmic height for every insertion order?"}],"k":"mc","o":["True","False"],"a":1,"topics":["BSTS"],"topicsBy":"site"},{"id":2,"l":[{"p":"If counting sort is unstable, does MSD radix sort still correctly sort?"}],"k":"mc","o":["True","False"],"a":0,"topics":["RADIX_SORTS"],"topicsBy":"site"},{"id":3,"l":[{"p":"If counting sort is unstable, does LSD radix sort still correctly sort?"}],"k":"mc","o":["True","False"],"a":1,"topics":["RADIX_SORTS"],"topicsBy":"site"},{"id":4,"l":[{"p":"Quicksort with shuffling has a Θ(N²) worst case on distinct values. Which explanation is correct?"}],"k":"mc","o":["True: poor pivots can create extremely unbalanced partitions","False: shuffling prevents a Θ(N²) worst case","True: it sorts the array twice per call","True: it copies the array"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"id":5,"l":[{"p":"Array after one selection-sort pass on [3,5,2,4,1]"}],"k":"mc","o":["[1,5,2,4,3]","[2,3,5,4,1]","[3,2,5,4,1]","[1,3,5,2,4]"],"a":0,"topics":["SORTING"],"topicsBy":"site"},{"id":6,"l":[{"p":"Array after one LSD radix pass on [17,23,45,12,34]"}],"k":"mc","o":["[12,23,34,45,17]","[12,17,23,34,45]","[12,17,23,45,34]"],"a":0,"topics":["RADIX_SORTS"],"topicsBy":"site"},{"id":7,"l":[{"p":"Insertion-sort swaps for [4,3,2,1]"}],"k":"mc","o":["3","4","5","6"],"a":3,"topics":["SORTING"],"topicsBy":"site"},{"id":8,"l":[{"p":"Worst-case removeMin runtime of a d-ary heap with N elements"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(N log_d N)","Θ(log_d N)","Θ(dN)","Θ(dN²)","Θ(log_N d)","Θ(d log_d N)","Θ(N²)"],"a":7,"topics":["HEAPS"],"topicsBy":"site"},{"id":9,"l":[{"p":"Worst-case insert runtime of a d-ary heap with N elements"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(N log_d N)","Θ(log_d N)","Θ(dN)","Θ(dN²)","Θ(log_N d)","Θ(d log_d N)","Θ(N²)"],"a":3,"topics":["HEAPS"],"topicsBy":"site"},{"id":10,"l":[{"p":"Inorder traversal of BST built by inserting [10,5,15,3,7,12,18]"}],"k":"mc","o":["[3,5,7,10,12,15,18]","[3,7,5,12,18,15,10]","[3,5,7,15,12,18,10]","None"],"a":0,"topics":["BSTS","TREE_TRAVERSALS"],"topicsBy":"site"},{"id":11,"l":[{"p":"Postorder traversal of BST built by inserting [10,5,15,3,7,12,18]"}],"k":"mc","o":["[3,5,7,10,12,15,18]","[3,7,5,12,18,15,10]","[3,5,7,15,12,18,10]","None"],"a":1,"topics":["BSTS","TREE_TRAVERSALS"],"topicsBy":"site"},{"id":12,"l":[{"p":"Does sorting a DAG’s vertices by ascending in-degree always produce a topological ordering?"}],"k":"mc","o":["Yes, low degree means fewer dependencies","Yes, by definition","No, only for trees","No, a lower-indegree vertex can depend on one with higher in-degree"],"a":3,"topics":["TOPOLOGICAL_SORT"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/2","n":"2","t":"2. PoTwourri (8 pts)","b":[{"s":[{"p":"Insert CAT, CORN, CATS, CALF, CYAN in that order. CAT sorts before CATS. LLRB result: root CATS, with red links indicated. Trie result marks terminal key nodes."}]},{"id":20,"l":[{"p":"LLRB root"}],"k":"blank","a":["CATS"],"topics":["RED_BLACK_TREES"],"topicsBy":"site"},{"id":21,"l":[{"p":"LLRB children of root and their link colors"}],"k":"blank","a":["CAT red, CYAN red"],"topics":["RED_BLACK_TREES"],"topicsBy":"site"},{"id":22,"l":[{"p":"Children of CAT in the LLRB"}],"k":"blank","a":["CALF and CORN"],"topics":["RED_BLACK_TREES"],"topicsBy":"site"},{"id":23,"l":[{"p":"Trie terminal words"}],"k":"blank","a":["CAT, CATS, CALF, CORN, CYAN"],"topics":["TRIES"],"topicsBy":"site"},{"s":[{"p":"WeightedQuickUnion has 5 elements, no path compression. Ties link the first tree under the second. Operations: connect(0,1), connect(2,3), connect(0,4), connect(2,0)."}]},{"id":24,"l":[{"p":"Root"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":25,"l":[{"p":"Parent of 0"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":26,"l":[{"p":"Parent of 4"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":27,"l":[{"p":"Parent of 3"}],"k":"blank","a":["1"],"topics":["DISJOINT_SETS"],"topicsBy":"site"},{"id":28,"l":[{"p":"Parent of 2"}],"k":"blank","a":["3"],"topics":["DISJOINT_SETS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/3","n":"3","t":"3. Lost From The Start (10 pts)","b":[{"s":[{"p":"Input nodes are exactly the distinct nodes of a noncircular singly linked list, in arbitrary order. Find its head in Θ(N) time by collecting all nodes that appear as another node’s successor, then finding the one input node absent from that collection."},{"c":"public Node findHead(List<Node> nodes) {\n  Set<Node> body = ⟪a⟫;\n  for (Node n : nodes) {\n    if (⟪b⟫) { ⟪c⟫; }\n  }\n  for (Node n : nodes) {\n    if (⟪d⟫) return ⟪e⟫;\n  }\n  return null;\n}","lang":"java"}]},{"id":30,"l":[{"p":"Create a set"}],"k":"blank","a":["new HashSet<>()"],"topics":["LINKED_LISTS","HASHING"],"topicsBy":"site"},{"id":31,"l":[{"p":"Successor exists"}],"k":"blank","a":["n.next != null"],"topics":["LINKED_LISTS","HASHING"],"topicsBy":"site"},{"id":32,"l":[{"p":"Record successor"}],"k":"blank","a":["body.add(n.next)"],"topics":["LINKED_LISTS","HASHING"],"topicsBy":"site"},{"id":33,"l":[{"p":"Node is not a successor"}],"k":"blank","a":["!body.contains(n)"],"topics":["LINKED_LISTS","HASHING"],"topicsBy":"site"},{"id":34,"l":[{"p":"Return head"}],"k":"blank","a":["n"],"topics":["LINKED_LISTS","HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/4","n":"4","t":"4. Fibonacci Fever (18 pts)","b":[{"s":[{"p":"Give time and auxiliary space in terms of N and p. Basic integer operations are Θ(1) unless part (e) says otherwise."}]},{"id":40,"l":[{"p":"fibmod1: naive two-recursion Fibonacci: time"}],"k":"blank","a":["ϕ^N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":41,"l":[{"p":"fibmod1: naive two-recursion Fibonacci: space"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":42,"l":[{"p":"fibmod2: iterative array DP modulo p: time"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":43,"l":[{"p":"fibmod2: iterative array DP modulo p: space"}],"k":"blank","a":["N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":44,"l":[{"p":"fibmod3: exponentiation of a fixed 2×2 matrix: time"}],"k":"blank","a":["log N"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":45,"l":[{"p":"fibmod3: exponentiation of a fixed 2×2 matrix: space"}],"k":"blank","a":["1"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":46,"l":[{"p":"fibmod4: build Pisano period, known ≤4p: time"}],"k":"blank","a":["p"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":47,"l":[{"p":"fibmod4: build Pisano period, known ≤4p: space"}],"k":"blank","a":["p"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"s":[{"p":"For full fib2, each BigInt uses Θ(log A) space and addition costs Θ(log(A+B)); F_N is Θ(ϕ^N)."}]},{"id":48,"l":[{"p":"Full Fibonacci DP: total time"}],"k":"blank","a":["N²"],"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":49,"l":[{"p":"Full Fibonacci DP: total space"}],"k":"blank","a":["N²"],"topics":["ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/5","n":"5","t":"5. Math DAGs (18 pts)","b":[{"s":[{"p":"A Math DAG has integer nodes and directed operator edges; evaluate a path left-to-right with no operator precedence. The original 5(a) claim was dropped from grading due to an omitted word in the exam definition."}]},{"id":50,"l":[{"p":"When is the largest-valued path guaranteed unique?"}],"k":"sata","o":["Every edge has the same operator","Every node has a unique number","Maximum outdegree is 1","Maximum indegree is 1","None of the above"],"a":[4],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"Math DAG edges: 4→1 (+), 4→3 (*), 1→9 (−), 9→4bottom (*), 3→4bottom (÷), 5→3 (+), 5→4bottom (−). The two nodes labeled 4 are distinct."}]},{"id":51,"l":[{"p":"Largest Math Path value"}],"k":"blank","a":["36"],"topics":["GRAPH_REPRESENTATIONS"],"topicsBy":"site"},{"s":[{"p":"For the code-completion part, nodes have value and outgoing GraphEdges (to, operator). `best` maps each node to the greatest path value ending at it. Iterate vertices to initialize, then process a topological order and relax every outgoing edge. Finally compare each stored best value with a singleton-node path."},{"c":"Map<Node,Integer> best = new HashMap<>();\nfor (⟪a⟫ : ⟪b⟫) { ⟪c⟫(⟪d⟫, ⟪e⟫); }\nfor (⟪f⟫ : ⟪g⟫) {\n  for (⟪h⟫ : ⟪i⟫) {\n    ⟪j⟫(⟪k⟫, Math.max(⟪l⟫, applyOp(⟪m⟫, ⟪n⟫, ⟪o⟫)));\n  }\n}\nint globalLargest = ⟪p⟫;\nfor (⟪q⟫ : ⟪r⟫) {\n  if (globalLargest < ⟪s⟫) {\n    globalLargest = ⟪t⟫;\n  }\n}","lang":"java"}]},{"id":52,"l":[{"p":"Initialization loop variable"}],"k":"blank","a":["Node n"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":53,"l":[{"p":"Initialization source"}],"k":"blank","a":["this.vertices"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":54,"l":[{"p":"Map insertion call"}],"k":"blank","a":["best.put"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":55,"l":[{"p":"Map key"}],"k":"blank","a":["n"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":56,"l":[{"p":"Initial singleton value"}],"k":"blank","a":["n.value"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":57,"l":[{"p":"Topological loop variable"}],"k":"blank","a":["Node n"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":58,"l":[{"p":"Topological order"}],"k":"blank","a":["this.toposort()"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":59,"l":[{"p":"Outgoing edge variable"}],"k":"blank","a":["GraphEdge e"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":60,"l":[{"p":"Outgoing edges"}],"k":"blank","a":["n.neighbors"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":61,"l":[{"p":"Update map call"}],"k":"blank","a":["best.put"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":62,"l":[{"p":"Map key for destination"}],"k":"blank","a":["e.to"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":63,"l":[{"p":"Current best at destination"}],"k":"blank","a":["best.get(e.to)"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":64,"l":[{"p":"Previous path value"}],"k":"blank","a":["best.get(n)"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":65,"l":[{"p":"Value at destination"}],"k":"blank","a":["e.to.value"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":66,"l":[{"p":"Operation on edge"}],"k":"blank","a":["e.operator"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":67,"l":[{"p":"Initial global max"}],"k":"blank","a":["Integer.MIN_VALUE"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":68,"l":[{"p":"Final scan variable"}],"k":"blank","a":["Node n"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":69,"l":[{"p":"Final scan source"}],"k":"blank","a":["this.vertices"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":70,"l":[{"p":"Compare against best path ending at node"}],"k":"blank","a":["best.get(n)"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"},{"id":71,"l":[{"p":"Update global maximum"}],"k":"blank","a":["best.get(n)"],"topics":["GRAPH_REPRESENTATIONS","TOPOLOGICAL_SORT","HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/6","n":"6","t":"6. 2D Hashing (7 pts)","b":[{"s":[{"p":"A 2D hashmap uses row=KarenHash(x)%N and column=PeyrinHash(x)%M. Dog equality compares birth year and name. Dog fields birthYear, name, weight are statistically independent."}]},{"id":80,"l":[{"p":"For dog1=(2018,\"Maxine\",65), dog2=(2018,\"Max\",70), dog3=(2020,\"Buddy\",60), with N=10,M=3 and hashes birthYear/name.length, which pairs collide in both row and column?"}],"k":"sata","o":["dog1 and dog2","dog1 and dog3","dog2 and dog3","None"],"a":[0],"topics":["HASHING"],"topicsBy":"site"},{"id":81,"l":[{"p":"Both hashes return birthYear"}],"k":"mc","o":["Invalid","Valid, but not independent","Valid and independent"],"a":1,"topics":["HASHING"],"topicsBy":"site"},{"id":82,"l":[{"p":"Karen returns birthYear; Peyrin returns name.length"}],"k":"mc","o":["Invalid","Valid, but not independent","Valid and independent"],"a":2,"topics":["HASHING"],"topicsBy":"site"},{"id":83,"l":[{"p":"Both return birthYear + name.length"}],"k":"mc","o":["Invalid","Valid, but not independent","Valid and independent"],"a":1,"topics":["HASHING"],"topicsBy":"site"},{"id":84,"l":[{"p":"Karen returns birthYear; Peyrin returns weight"}],"k":"mc","o":["Invalid","Valid, but not independent","Valid and independent"],"a":0,"topics":["HASHING"],"topicsBy":"site"},{"id":85,"l":[{"p":"Same valid, well-distributed hash for N=4 rows and M=6 columns: maximum nonempty bins"}],"k":"blank","a":["12"],"topics":["HASHING"],"topicsBy":"site"},{"id":86,"l":[{"p":"If name becomes mutable and KarenHash returns name.length, is it still consistent with equals?"}],"k":"mc","o":["Yes; equal names have equal lengths, even if mutable","Yes, because equals is not overridden","No; changing name makes the hash invalid","No; it is not consistent with equals"],"a":0,"topics":["HASHING"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/7","n":"7","t":"7. Find Bee Leader (10 pts)","b":[{"s":[{"p":"Given a connected weighted undirected graph G and queen set Q, return a minimum-cost forest where every hive belongs to exactly one queen’s component and no two queens share a component."}]},{"id":90,"l":[{"p":"Which construction yields the minimum-cost assignment?"}],"k":"mc","o":["Add a dummy vertex with zero-weight edges to every queen, then compute an MST","Add weight-one edges between all queens, then compute an MST","Run Dijkstra independently from every queen and union the trees","Run BFS from each queen"],"a":0,"topics":["MSTS"],"topicsBy":"site"},{"id":91,"l":[{"p":"Alternative Kruskal approach"}],"k":"blank","a":["Initialize the disjoint set by connecting all queen vertices before processing edges"],"topics":["MSTS","DISJOINT_SETS"],"topicsBy":"site"},{"id":92,"l":[{"p":"Asymptotic runtime of Kruskal solution"}],"k":"blank","a":["O(E log E)"],"topics":["MSTS","DISJOINT_SETS","ASYMPTOTICS"],"topicsBy":"site"}],"topics":null},{"id":"61b-sp25-final/8","n":"8","t":"8. Rebuild Your Own World (15 pts)","b":[{"s":[{"p":"For each game-design choice, identify its main inefficiency and a better design."}]},{"id":100,"l":[{"p":"Separate copied Java file for every level: main issue?"}],"k":"mc","o":["Duplicated code makes changes inflexible and source larger","Too many runtime branches","Poor pathfinding"],"a":0,"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":101,"l":[{"p":"Better level design"}],"k":"blank","a":["Use one generation function or Level class parameterized by data/config files"],"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":102,"l":[{"p":"Scan every tile after each move to check whether coins remain: issue?"}],"k":"mc","o":["Repeated full-grid scan","Coins are mutable","A list is too small"],"a":0,"topics":["ASYMPTOTICS"],"topicsBy":"site"},{"id":103,"l":[{"p":"Better coin tracking"}],"k":"blank","a":["Maintain coinsRemaining and decrement it when collecting a coin"],"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":104,"l":[{"p":"Enemy move() switches on name: issue?"}],"k":"mc","o":["One bloated, brittle switch makes behavior changes risky and inflexible","Iterating over enemies is necessarily inefficient","Enemies should not move"],"a":0,"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":105,"l":[{"p":"Better enemy behavior design"}],"k":"blank","a":["Use Enemy subclasses/polymorphism, with each type implementing its own move behavior"],"topics":["INHERITANCE","ABSTRACTION"],"topicsBy":"site"},{"id":106,"l":[{"p":"Save every keypress and replay all input on load: issue?"}],"k":"mc","o":["Storage and load time grow with play history","Text files cannot store coordinates","Keypresses are not deterministic"],"a":0,"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":107,"l":[{"p":"Better save/load design"}],"k":"blank","a":["Serialize the current game state and necessary parameters (including RNG state) instead of replaying history"],"topics":["ABSTRACTION"],"topicsBy":"site"},{"id":108,"l":[{"p":"Run A* separately to every board tile for visibility radius 10: issue?"}],"k":"mc","o":["Repeats point-to-point searches when a bounded all-destinations search is needed","A* cannot use a heuristic","Tiles cannot be vertices"],"a":0,"topics":["GRAPH_TRAVERSALS","SHORTEST_PATHS"],"topicsBy":"site"},{"id":109,"l":[{"p":"Better visibility algorithm"}],"k":"blank","a":["Run BFS from the player and stop expanding beyond distance 10"],"topics":["GRAPH_TRAVERSALS"],"topicsBy":"site"}],"topics":null}],"by":["Yokota","Hug"]},{"id":"61b-sp25-mt1","t":"Spring 2025 Midterm 1","src":{"exam":"https://drive.google.com/file/d/14XrrtR40_1CgEe_YySzUg7zsrS_EgqsW/view","sol":"https://drive.google.com/file/d/1qdjKy3cjzyS7QKKxq5_OAV68jZAvQDWP/view","topics":"sp25-mt1"},"p":[{"id":"61b-sp25-mt1/1","n":"1","t":"1. CS61Bot (12.0 pts)","b":[{"s":[{"c":"public interface ChatBot {\n    public void answerQuery(String q);\n    default public String myInfo() {\n        return \"I am a ChatBot!\";\n    }\n}","lang":"java"}]},{"id":1,"l":[{"p":"(a) We create a class CS61Bot that implements ChatBot. Which are true?"}],"k":"sata","o":["The CS61Bot class can compile even if it does not define an answerQuery method.","The CS61Bot class can compile even if it does not define a myInfo method.","If we override myInfo, we must add an @Override tag in order for the CS61Bot class to compile.","If we do not override answerQuery, our program may crash at runtime.","We can define a constructor for CS61Bot even though the interface doesn’t list any constructors."],"a":[1,4],"topics":["JAVA","ABSTRACTION","INHERITANCE"],"x":"Every non-default interface method must be implemented, or it won’t compile (so it can’t crash at runtime). myInfo has a default. @Override is optional.","part":"a"},{"s":[{"c":"public class CS61Bot implements ChatBot {\n    public static String versionInfo = \"CS61Bot version 5\";\n    @Override\n    public void answerQuery(String q) {\n        // implementation not shown\n    }\n    @Override\n    public String myInfo() {\n        return versionInfo;\n    }\n    public static void main(String[] args) {\n        CS61Bot bot = new CS61Bot();\n        System.out.println(bot.myInfo());\n    }\n}","lang":"java"}]},{"id":2,"l":[{"p":"(b) What happens when main runs?"}],"k":"mc","o":["The program prints \"I am a ChatBot!\".","The program prints \"CS61Bot version 5\".","The program errors at compile-time.","The program errors at run-time.","None of the above."],"a":1,"topics":["JAVA","INHERITANCE"],"x":"Instance methods can read static variables.","part":"b"},{"s":[{"p":"Aditya wants to add a new method public void answerQuery(String q, String student) to CS61Bot."}]},{"id":3,"l":[{"p":"(c) What happens if Aditya adds the method (keeping the existing answerQuery)?"}],"k":"mc","o":["The CS61Bot class will not compile because it defines two methods with the same name.","The CS61Bot class will not compile for some other reason.","The CS61Bot class will compile."],"a":2,"topics":["JAVA","INHERITANCE"],"x":"Overloading with different parameters is allowed.","part":"c"},{"id":4,"l":[{"p":"(d) What happens if Aditya replaces the existing answerQuery with it?"}],"k":"mc","o":["The CS61Bot class will not compile as it does not implement all methods of the ChatBot interface.","The CS61Bot class will compile, and calling answerQuery(q) will call answerQuery(q, null) instead.","The CS61Bot class will compile, but calling answerQuery(q) will cause a runtime error.","None of the above."],"a":0,"topics":["JAVA","INHERITANCE"],"x":"An overload isn’t an override, so answerQuery(String) is no longer implemented.","part":"d"}],"topics":null},{"id":"61b-sp25-mt1/2","n":"2","t":"2. 2048 Comparator (24.0 pts)","b":[{"s":[{"p":"A row’s rowwiseDropCount is the number of elements strictly less than the value immediately before them (left to right): [128, 64, 32, 16] has 3, [128, 4, 32, 0] has 2, [8, 0, 0, 2] has 1. columnwiseDropCount is the same down a column. totalDropCount sums both over all rows and columns. Boards are square."},{"c":"private static int totalDropCount(int[][] board) {\n    int count = 0;\n    for (int i = 0; ⟪a⟫; i += 1) {\n        for (int j = ⟪b⟫; ⟪c⟫; j += 1) {\n            if (⟪d⟫) {\n                count += 1;\n            }\n            if (⟪e⟫) {\n                count += 1;\n            }\n        }\n    }\n    return count;\n}","lang":"java","f":{"a":"i < board.length","b":"1","c":"j < board.length","d":"board[i][j-1] > board[i][j]","e":"board[j-1][i] > board[j][i]"}}]},{"id":5,"l":[{"p":"(a) The outer loop condition"}],"k":"blank","a":["i < board.length","i < board[0].length"],"topics":["ARRAYS","PROJECT_2048","ITERATION"],"part":"a"},{"id":6,"l":[{"p":"(a) The inner loop’s start"}],"k":"blank","a":["1","0"],"topics":["ARRAYS","PROJECT_2048","ITERATION"],"part":"a"},{"id":7,"l":[{"p":"(a) The inner loop condition"}],"k":"blank","a":["j < board.length","j < board.length - 1","j < board[0].length","j < board[0].length - 1"],"topics":["ARRAYS","PROJECT_2048","ITERATION"],"part":"a"},{"id":8,"l":[{"p":"(a) The row check"}],"k":"blank","a":["board[i][j-1] > board[i][j]","board[i][j] > board[i][j+1]","board[i][j] < board[i][j-1]"],"topics":["ARRAYS","PROJECT_2048","ITERATION"],"part":"a"},{"id":9,"l":[{"p":"(a) The column check"}],"k":"blank","a":["board[j-1][i] > board[j][i]","board[j][i] > board[j+1][i]","board[j][i] < board[j-1][i]"],"topics":["ARRAYS","PROJECT_2048","ITERATION"],"x":"Use j from 1 to the length with j − 1 and j, or from 0 to length − 1 with j and j + 1, consistently. i walks over rows for the row check and over columns for the column check.","part":"a"},{"s":[{"p":"(b) findMax finds the largest tile value on the board."},{"c":"private static int findMax(int[][] board) {\n    int maxTile = 0;\n    for (⟪f⟫ row : board) {\n        for (⟪g⟫ tile : row) {\n            if (⟪h⟫) {\n                maxTile = tile;\n            }\n        }\n    }\n    return maxTile;\n}","lang":"java","f":{"f":"int[]","g":"int","h":"maxTile < tile"}}]},{"id":10,"l":[{"p":"(b) for (____ row : board)"}],"k":"blank","a":["int[]"],"topics":["ARRAYS","PROJECT_2048"],"part":"b"},{"id":11,"l":[{"p":"(b) for (____ tile : row)"}],"k":"blank","a":["int","Integer"],"topics":["ARRAYS","PROJECT_2048"],"part":"b"},{"id":12,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["maxTile < tile","tile > maxTile"],"topics":["ARRAYS","PROJECT_2048"],"part":"b"},{"s":[{"p":"(c) BoardComparator compares boards by their largest tile; ties are broken by totalDropCount."},{"c":"public static class BoardComparator implements ⟪i⟫ {\n    ...\n    @Override\n    public int compare(int[][] boardA, int[][] boardB) {\n        int tileA = ⟪j⟫;\n        int tileB = ⟪k⟫;\n        if (⟪l⟫) {\n            int scoreA = ⟪m⟫;\n            int scoreB = ⟪n⟫;\n            return ⟪o⟫;\n        }\n        return ⟪p⟫;\n    }\n}","lang":"java","f":{"i":"Comparator<int[][]>","j":"findMax(boardA)","k":"findMax(boardB)","l":"tileA == tileB","m":"totalDropCount(boardA)","n":"totalDropCount(boardB)","o":"scoreA - scoreB","p":"tileA - tileB"}}]},{"id":13,"l":[{"p":"(c) implements ____"}],"k":"blank","a":["Comparator<int[][]>"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":14,"l":[{"p":"(c) tileA"}],"k":"blank","a":["findMax(boardA)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":15,"l":[{"p":"(c) tileB"}],"k":"blank","a":["findMax(boardB)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":16,"l":[{"p":"(c) if (____)"}],"k":"blank","a":["tileA == tileB"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":17,"l":[{"p":"(c) scoreA"}],"k":"blank","a":["totalDropCount(boardA)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":18,"l":[{"p":"(c) scoreB"}],"k":"blank","a":["totalDropCount(boardB)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":19,"l":[{"p":"(c) return ____ (tie)"}],"k":"blank","a":["scoreA - scoreB","Integer.compare(scoreA, scoreB)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"},{"id":20,"l":[{"p":"(c) return ____"}],"k":"blank","a":["tileA - tileB","Integer.compare(tileA, tileB)"],"topics":["COMPARATORS","PROJECT_2048"],"part":"c"}],"topics":null},{"id":"61b-sp25-mt1/3","n":"3","t":"3. Compressed Doubly-Linked List (29.0 pts)","b":[{"s":[{"p":"In a Compressed Doubly-Linked List (CDLL), each node has next, prev, value and freq, and stands for freq consecutive elements equal to value. For example, [5, -3, -3, 5, 5, 5] is sentinel ⇄ (5, freq 1) ⇄ (-3, freq 2) ⇄ (5, freq 3), circularly. No two consecutive non-sentinel nodes have the same value, and every freq is at least 1."},{"c":"public class CDLL implements Iterable<Integer> {\n    private Node sentinel;\n    private class Node {\n        Node prev;\n        Node next;\n        int value;\n        int freq;\n        public Node(Node prev, Node next, int value, int freq) { ... }\n    }\n    public CDLL(List<Integer> original) {\n        sentinel = new Node(null, null, -1, -1);\n        Node curr = sentinel;\n        for (int i : ⟪a⟫) {\n            if (i == curr.value && ⟪b⟫) {\n                ⟪c⟫;\n            } else {\n                ⟪d⟫;\n                ⟪e⟫;\n                ⟪f⟫;\n            }\n        }\n        ⟪g⟫;\n        ⟪h⟫;\n    }\n    ...\n}","lang":"java","f":{"a":"original","b":"curr != sentinel","c":"curr.freq += 1","d":"Node n = new Node(curr, sentinel, i, 1)","e":"curr.next = n","f":"curr = curr.next","g":"sentinel.prev = curr","h":"curr.next = sentinel"}}]},{"id":21,"l":[{"p":"(a) for (int i : ____)"}],"k":"blank","a":["original"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":22,"l":[{"p":"(a) The second condition"}],"k":"blank","a":["curr != sentinel","sentinel != curr"],"topics":["LISTS","LINKED_LISTS"],"x":"Without it, a first item of −1 would match the sentinel’s value.","part":"a"},{"id":23,"l":[{"p":"(a) Same value as the current node"}],"k":"blank","a":["curr.freq += 1","curr.freq++","curr.freq = curr.freq + 1"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":24,"l":[{"p":"(a) Otherwise, first line"}],"k":"blank","a":["Node n = new Node(curr, sentinel, i, 1)","Node n = new Node(curr, null, i, 1)"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":25,"l":[{"p":"(a) Second line"}],"k":"blank","a":["curr.next = n"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":26,"l":[{"p":"(a) Third line"}],"k":"blank","a":["curr = curr.next","curr = n"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":27,"l":[{"p":"(a) After the loop, first line"}],"k":"blank","a":["sentinel.prev = curr","curr.next = sentinel"],"topics":["LISTS","LINKED_LISTS"],"part":"a"},{"id":28,"l":[{"p":"(a) Second line"}],"k":"blank","a":["curr.next = sentinel","sentinel.prev = curr"],"topics":["LISTS","LINKED_LISTS"],"x":"Close the circle at the end; the two lines can go in either order.","part":"a"},{"s":[{"p":"(b) Complete CDLLIterator, which yields the CDLL’s values as they would appear in a regular List. It may not modify the CDLL."},{"c":"public class CDLLIterator implements Iterator<Integer> {\n    Node curr = ⟪i⟫;\n    int count = 0;\n\n    @Override\n    public boolean hasNext() {\n        return ⟪j⟫;\n    }\n\n    @Override\n    public Integer next() {\n        ⟪k⟫;\n        ⟪l⟫;\n        if (⟪m⟫) {\n            ⟪n⟫;\n            ⟪o⟫;\n        }\n        return ⟪p⟫;\n    }\n}","lang":"java","f":{"i":"sentinel.next","j":"curr != sentinel","k":"int i = curr.value","l":"count += 1","m":"count == curr.freq","n":"curr = curr.next","o":"count = 0","p":"i"}}]},{"id":29,"l":[{"p":"(b) curr starts at"}],"k":"blank","a":["sentinel.next"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":30,"l":[{"p":"(b) hasNext returns"}],"k":"blank","a":["curr != sentinel"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":31,"l":[{"p":"(b) First line of next"}],"k":"blank","a":["int i = curr.value"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":32,"l":[{"p":"(b) Second line"}],"k":"blank","a":["count += 1","count++"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":33,"l":[{"p":"(b) if (____)"}],"k":"blank","a":["count == curr.freq"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":34,"l":[{"p":"(b) Inside the if, first line"}],"k":"blank","a":["curr = curr.next"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":35,"l":[{"p":"(b) Inside the if, second line"}],"k":"blank","a":["count = 0"],"topics":["LINKED_LISTS","ITERATORS"],"part":"b"},{"id":36,"l":[{"p":"(b) return ____"}],"k":"blank","a":["i"],"topics":["LINKED_LISTS","ITERATORS"],"x":"Return the current node’s value freq times before moving on. (Starting curr at the sentinel and using curr.next throughout also works.)","part":"b"}],"topics":null},{"id":"61b-sp25-mt1/4","n":"4","t":"4. LargeFriend (20.0 pts)","b":[{"s":[{"p":"LargeFriend wraps a Comparator<T> and is itself a Comparator; iterating over it yields every item it has ever judged “larger”, in order. For example, after compare(\"apple\", \"zebra\"), compare(\"apple\", \"apple\"), compare(\"apple\", \"banana\") and compare(\"banana\", \"zebra\"), it iterates zebra, banana, zebra. You may call wrappedComparator’s compare only once per call."},{"c":"public class LargeFriend<T> implements ⟪a⟫, ⟪b⟫ {\n    private Comparator<T> wrappedComparator;\n    private ⟪c⟫ largevals;\n\n    public LargeFriend(Comparator<T> wrappedComparator) {\n        ⟪d⟫;\n        ⟪e⟫;\n    }\n\n    @Override\n    public ⟪f⟫ iterator() {\n        return ⟪g⟫;\n    }\n\n    @Override\n    public int compare(T a, T b) {\n        ⟪h⟫;\n        if (result > 0) {\n            ⟪i⟫;\n        } else if (result < 0) {\n            ⟪j⟫;\n        }\n        return result;\n    }\n}","lang":"java","f":{"a":"Comparator<T>","b":"Iterable<T>","c":"List<T>","d":"this.wrappedComparator = wrappedComparator","e":"largevals = new ArrayList<T>()","f":"Iterator<T>","g":"largevals.iterator()","h":"int result = wrappedComparator.compare(a, b)","i":"largevals.add(a)","j":"largevals.add(b)"}}]},{"id":37,"l":[{"p":"The first interface"}],"k":"blank","a":["Comparator<T>","Iterable<T>"],"topics":["ITERATORS","COMPARATORS"]},{"id":38,"l":[{"p":"The second interface"}],"k":"blank","a":["Iterable<T>","Comparator<T>"],"topics":["ITERATORS","COMPARATORS"],"x":"Either order; both must be parameterized by T."},{"id":39,"l":[{"p":"The type of largevals"}],"k":"blank","a":["List<T>","ArrayList<T>","LinkedList<T>","Deque<T>"],"topics":["ITERATORS","COMPARATORS"],"x":"It must keep duplicates, so not a Set; and a Map isn’t Iterable."},{"id":40,"l":[{"p":"Constructor, first line"}],"k":"blank","a":["this.wrappedComparator = wrappedComparator"],"topics":["ITERATORS","COMPARATORS"]},{"id":41,"l":[{"p":"Constructor, second line"}],"k":"blank","a":["largevals = new ArrayList<T>()","largevals = new ArrayList<>()","largevals = new LinkedList<>()"],"topics":["ITERATORS","COMPARATORS"]},{"id":42,"l":[{"p":"iterator’s return type"}],"k":"blank","a":["Iterator<T>"],"topics":["ITERATORS","COMPARATORS"]},{"id":43,"l":[{"p":"iterator returns"}],"k":"blank","a":["largevals.iterator()"],"topics":["ITERATORS","COMPARATORS"]},{"id":44,"l":[{"p":"First line of compare"}],"k":"blank","a":["int result = wrappedComparator.compare(a, b)"],"topics":["ITERATORS","COMPARATORS"]},{"id":45,"l":[{"p":"result > 0"}],"k":"blank","a":["largevals.add(a)"],"topics":["ITERATORS","COMPARATORS"]},{"id":46,"l":[{"p":"result < 0"}],"k":"blank","a":["largevals.add(b)"],"topics":["ITERATORS","COMPARATORS"]}],"topics":null},{"id":"61b-sp25-mt1/5","n":"5","t":"5. Consume and Interleave (15.0 pts)","b":[{"s":[{"p":"ExamDeque (addFirst, addLast, toList, isEmpty, size, removeFirst, removeLast) has a default method consumeAndInterleave(ExamDeque<T> other), which interleaves other (same length, not ==) into this deque without creating a new ExamDeque, leaving other empty. For x = [2, 3, 4, 5, 6] and y = [20, 30, 40, 50, 60], x.consumeAndInterleave(y) makes x [2, 20, 3, 30, 4, 40, 5, 50, 6, 60]. ExamArrayDeque implements it, with a List constructor and an equals that compares items in order."},{"p":"(a) Write a unit test using Truth’s assertThat(…).containsExactly(…).inOrder() and isEqualTo."},{"c":"@Test\npublic boolean consumeAndInterleaveTest() {\n    ExamDeque<Integer> x = new ExamArrayDeque<>(List.of(2, 3, 4));\n    ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n    ⟪d⟫;\n}","lang":"java","f":{"a":"ExamDeque<Integer> y = new ExamArrayDeque<>(List.of(10, 20, 30))","b":"x.consumeAndInterleave(y)","c":"assertThat(x.toList()).containsExactly(2, 10, 3, 20, 4, 30).inOrder()","d":"assertThat(y.toList()).containsExactly()"}}]},{"id":47,"l":[{"p":"(a) Make y"}],"k":"blank","a":["ExamDeque<Integer> y = new ExamArrayDeque<>(List.of(10, 20, 30))","ExamArrayDeque<Integer> y = new ExamArrayDeque<>(List.of(10, 20, 30))"],"topics":["TESTING","DEQUES"],"part":"a"},{"id":48,"l":[{"p":"(a) Call the method"}],"k":"blank","a":["x.consumeAndInterleave(y)"],"topics":["TESTING","DEQUES"],"part":"a"},{"id":49,"l":[{"p":"(a) Check x"}],"k":"blank","a":["assertThat(x.toList()).containsExactly(2, 10, 3, 20, 4, 30).inOrder()","assertThat(x).isEqualTo(new ExamArrayDeque<>(List.of(2, 10, 3, 20, 4, 30)))"],"topics":["TESTING","DEQUES"],"part":"a"},{"id":50,"l":[{"p":"(a) Check y"}],"k":"blank","a":["assertThat(y.toList()).containsExactly()","assertThat(y.isEmpty()).isTrue()","assertThat(y.size()).isEqualTo(0)"],"topics":["TESTING","DEQUES"],"x":"Full credit needed both x and y checked. (The numbers in y are up to you; these match the staff test.)","part":"a"},{"s":[{"p":"(b) Fill in consumeAndInterleave."},{"c":"default void consumeAndInterleave(ExamDeque<T> other) {\n    if (other.size() != this.size() || this == other) {\n        throw new IllegalArgumentException();\n    }\n    while (⟪e⟫) {\n        ⟪f⟫;\n        ⟪g⟫;\n    }\n}","lang":"java","f":{"e":"!other.isEmpty()","f":"this.addLast(this.removeFirst())","g":"this.addLast(other.removeFirst())"}}]},{"id":51,"l":[{"p":"(b) while (____)"}],"k":"blank","a":["!other.isEmpty()","other.size() > 0"],"topics":["DEQUES","ADTS"],"part":"b"},{"id":52,"l":[{"p":"(b) First line"}],"k":"blank","a":["this.addLast(this.removeFirst())","addLast(removeFirst())"],"topics":["DEQUES","ADTS"],"part":"b"},{"id":53,"l":[{"p":"(b) Second line"}],"k":"blank","a":["this.addLast(other.removeFirst())","addLast(other.removeFirst())"],"topics":["DEQUES","ADTS"],"x":"Cycle this deque’s own items to the back one at a time, each followed by the next item from other.","part":"b"}],"topics":null}],"by":["Yokota","Hug"]},{"id":"61b-sp25-mt2","t":"Spring 2025 Midterm 2","src":{"exam":"https://drive.google.com/file/d/1a-L-UCn4U9to9Y8kd97naxEWF37SOHmF/view","sol":"https://drive.google.com/file/d/1ZbLHbJlE_6zsEq1ined1AeALRwey5r4D/view","topics":"sp25-mt2"},"p":[{"id":"61b-sp25-mt2/1","n":"1","t":"1. Potpourri (16.0 pts)","b":[{"id":1,"l":[{"p":"(a) True/False: All valid Left-Leaning Red-Black Trees have the same number of black links along every root-to-leaf path."}],"k":"mc","o":["True","False"],"a":0,"topics":["RED_BLACK_TREES"],"x":"This follows from the one-to-one correspondence with 2-3 trees, whose leaves are all at the same depth.","part":"a"},{"id":2,"l":[{"p":"(b) True/False: If a binary search tree has its edges colored red/black such that the number of black links along every root-to-leaf path is the same, then it is a valid Left-Leaning Red-Black Tree."}],"k":"mc","o":["True","False"],"a":1,"topics":["RED_BLACK_TREES"],"x":"Color every edge of a big tree red: every path has 0 black links, but it isn’t a valid LLRB.","part":"b"},{"id":3,"l":[{"p":"(c) True/False: If all edges in an undirected, connected graph have the same weight, any spanning tree of the graph is a valid Minimum Spanning Tree."}],"k":"mc","o":["True","False"],"a":0,"topics":["MSTS"],"x":"Every spanning tree has exactly N − 1 edges, so they all have the same total weight.","part":"c"},{"id":4,"l":[{"p":"(d) True/False: While running Kruskal’s algorithm, we multiply all edge weights of an undirected, connected graph by −1 before inserting them into the heap. The resulting spanning tree will be a Maximum Spanning Tree of the original graph."}],"k":"mc","o":["True","False"],"a":0,"topics":["MSTS"],"x":"Kruskal’s then takes the largest original edges first, which satisfies the maximum version of the cut property.","part":"d"},{"id":5,"l":[{"p":"(e) True/False: Let G be an undirected, connected graph with a unique Minimum Spanning Tree, and let C be a cut of G with more than one crossing edge. The edge with the maximum weight across C is never included in the resulting Minimum Spanning Tree."}],"k":"mc","o":["True","False"],"a":1,"topics":["MSTS"],"x":"If G is itself a tree, its MST uses every edge, including the heaviest edge across any cut.","part":"e"},{"id":6,"l":[{"p":"(f) True/False: In Quick Find, the isConnected operation has a runtime of O(1)."}],"k":"mc","o":["True","False"],"a":0,"topics":["DISJOINT_SETS"],"x":"Quick Find stores each item’s set id, so isConnected just compares two values.","part":"f"},{"id":7,"l":[{"p":"(g) What is the fewest number of edges in an undirected graph with N vertices and exactly 3 connected components?"}],"k":"mc","o":["1 edge","2 edges","3 edges","4 edges","N − 1 edges","N − 2 edges","N − 3 edges","None of the above"],"a":6,"topics":["GRAPH_TRAVERSALS"],"x":"Each edge joins at most two components, so going from N components to 3 takes at least N − 3 edges.","part":"g"},{"s":[{"p":"For (h) and (i), consider a modified heap where, instead of a resizing array, elements are stored in a circular doubly-linked list with a sentinel."}]},{"id":8,"l":[{"p":"(h) What is the best-case runtime for removeMin in this heap, assuming the heap contains N elements?"}],"k":"mc","o":["Θ(1)","Θ(log(N))","Θ(N)","Θ(N log(N))","Θ(N²)","None of the above"],"a":0,"topics":["LINKED_LISTS","HEAPS"],"x":"Move the last item (next to the sentinel) to the front; in the best case it’s already no larger than its children, so nothing sinks.","part":"h"},{"id":9,"l":[{"p":"(i) What is the best-case runtime for insert in this heap, assuming the heap contains N elements?"}],"k":"mc","o":["Θ(1)","Θ(log(N))","Θ(N)","Θ(N log(N))","Θ(N²)","None of the above"],"a":2,"topics":["LINKED_LISTS","HEAPS"],"x":"After adding at the end, the new item must be compared with its parent, which is about N/2 positions away in a linked list: Θ(N) even when no swap is needed.","part":"i"},{"id":10,"l":[{"p":"(j) Which of the following is true about the array [-, 0, 0, 2, 5, 0, 7, 5]? Select all that apply."}],"k":"sata","o":["The array is a valid backing array of a max-heap.","The array is a valid backing array of a min-heap.","If the - is replaced with −8, the array is a valid backing array of a Weighted Quick Union without path compression.","If the - is replaced with −8, the array is a valid backing array of a Weighted Quick Union with path compression.","None of the above"],"a":[1,2,3],"topics":["DISJOINT_SETS","HEAPS"],"x":"Check each separately. Every parent is ≤ its children, so it’s a min-heap. Every valid path-compressed WQU is also a valid WQU without path compression (connect roots and never compress).","part":"j"},{"id":11,"l":[{"p":"(k) Suppose a binary search tree contains the elements {1, 2, 3, 4, 5, 6, 7, 8}, with the root containing 7. After deleting the root node using Hibbard deletion, which nodes could possibly be the new root? Select all that apply."}],"k":"sata","o":["1","2","3","4","5","6","8","None of the above"],"a":[5,6],"topics":["BSTS"],"x":"Hibbard deletion replaces the root with its predecessor (6) or successor (8), whatever the tree’s shape.","part":"k"},{"id":12,"l":[{"p":"(l) Given the backing array parents of a Weighted Quick Union, which of these returns the size of the largest connected component?"}],"k":"mc","o":["min(parents)","max(parents)","max(parents) * -1","min(parents) * -1","None of the above"],"a":3,"topics":["DISJOINT_SETS"],"x":"Roots store −size, so the most negative entry belongs to the largest component; negate it.","part":"l"}],"topics":null},{"id":"61b-sp25-mt2/2","n":"2","t":"2. LLRB (14.0 pts)","b":[{"s":[{"p":"(a) Convert the 2-3 tree below into its corresponding Left-Leaning Red-Black Tree. (The exam had a fill-in table for every node; this site asks about the result in three parts.)"},{"c":"          [10 50]\n        /    |    \\\n     [5]  [20 30]  [55 60]","lang":"txt"}]},{"id":13,"l":[{"p":"(a) Which value is at the root of the LLRB?"}],"k":"mc","o":["5","10","20","30","50","55","60"],"a":4,"topics":["B_TREES","RED_BLACK_TREES"],"part":"a"},{"id":14,"l":[{"p":"(a) Which values are in red nodes (the link to their parent is red)?"}],"k":"sata","o":["5","10","20","30","50","55","60"],"a":[1,2,5],"topics":["B_TREES","RED_BLACK_TREES"],"part":"a"},{"id":15,"l":[{"p":"(a) Which value is the left child of 30?"}],"k":"mc","o":["None","5","10","20","55","60"],"a":3,"topics":["B_TREES","RED_BLACK_TREES"],"x":"Each 3-node splits into a black node with a red left child: [10 50] becomes 50 with red child 10; [20 30] becomes 30 with red child 20; [55 60] becomes 60 with red child 55. So the LLRB is 50 → (10 red → (5, 30 → (20 red))), 60 → (55 red).","part":"a"},{"s":[{"p":"The trees below are LLRBs immediately after a new element has been added, but before any invariant-fixing operations. For each, write the sequence of operations (e.g. rotateLeft(A), rotateRight(B), colorFlip(C)) needed to fix all invariants. If it is impossible to have created the LLRB by adding a single new element, write “Not possible”. The letters are placeholders. (Each red link is labeled red; the others are black.)"},{"c":"(b)       C\n         / red\n        A\n         \\ red\n          B","lang":"txt"}]},{"id":16,"l":[{"p":"(b) Operations"}],"k":"blank","a":["rotateLeft(A), rotateRight(C), colorFlip(B)","rotateLeft(A)\nrotateRight(C)\ncolorFlip(B)","rotateLeft(A) rotateRight(C) colorFlip(B)","RotateLeft(A), RotateRight(C), ColorFlip(B)","RotateLeft(A)\nRotateRight(C)\nColorFlip(B)","RotateLeft(A) RotateRight(C) ColorFlip(B)"],"topics":["RED_BLACK_TREES"],"x":"A’s right-leaning red link needs rotateLeft(A), leaving two left-leaning reds (C, B, A), so rotateRight(C); B then has two red children, so colorFlip(B).","part":"b"},{"s":[{"c":"(c)            D\n        red  /   \\\n            B     F\n           / \\   / \\  (both red)\n          A   C E   G","lang":"txt"}]},{"id":17,"l":[{"p":"(c) Operations"}],"k":"blank","a":["colorFlip(F), colorFlip(D)","colorFlip(F)\ncolorFlip(D)","colorFlip(F) colorFlip(D)","ColorFlip(F), ColorFlip(D)","ColorFlip(F)\nColorFlip(D)","ColorFlip(F) ColorFlip(D)"],"topics":["RED_BLACK_TREES"],"x":"F has two red children: colorFlip(F) makes F–D red, so D now has two red children: colorFlip(D).","part":"c"},{"s":[{"c":"(d)            D\n        red  /   \\\n            B     F\n       red / \\   / \\\n          A   C E   G\n               red","lang":"txt"},{"p":"(In (d), D–B, B–A and F–E are red; the other links are black.)"}]},{"id":18,"l":[{"p":"(d) Operations"}],"k":"blank","a":["Not possible","not possible","Impossible","impossible"],"topics":["RED_BLACK_TREES"],"x":"Its root-to-null paths have 1, 2 and 3 black links, which can’t happen right after a single insertion into a valid LLRB.","part":"d"}],"topics":null},{"id":"61b-sp25-mt2/3","n":"3","t":"3. Anirudh’s Weighted Question (31.0 pts)","b":[{"s":[{"p":"Anirudh the Adventurer wants to find a treasure hidden on one of N islands. In the secret library of Stella the Sneaky Sorceress, many scrolls each represent a map of the N islands: an array of N numbers that is a Quick Union with a single root. For example, for N = 5, one possible array is [1, 2, 3, −5, 0]."},{"p":"All of the Quick Union trees are valid, but only one is a valid Weighted Quick Union (without path compression): the real map. A valid WQU means the array can be created by a sequence of union operations (under some tie-breaking scheme). For example, [1, 2, 3, −5, 0] is a valid QU, but not a valid WQU."},{"p":"To find the real map, Anirudh converts each array into a TreasureMap, a linked structure whose nested Island class is a node that keeps track of its children, and then calls isValid on it."},{"c":"public class TreasureMap {\n    private Island root;\n\n    private class Island {\n        public int label;\n        public List<Island> children;\n\n        public Island(int label) {\n            this.label = label;\n            this.children = new ArrayList<>();\n        }\n    }\n\n    // Converts the array representation of a QuickUnion into a TreasureMap.\n    public TreasureMap(int[] qu) {\n        Island[] isles = new Island[qu.length];\n        for (int i = 0; i < qu.length; i++) {\n            isles[i] = new Island(i);\n        }\n        for (int i = 0; ⟪a⟫; ⟪b⟫) {\n            int parent = qu[i];\n            if (⟪c⟫) {\n                ⟪d⟫;\n            } else {\n                ⟪e⟫;\n            }\n        }\n    }\n}","lang":"java","f":{"a":"i < qu.length","b":"i++","c":"parent < 0","d":"root = isles[i]","e":"isles[parent].children.add(isles[i])"}},{"p":"(a) Complete the constructor, which receives the backing array of a Quick Union with exactly one root."}]},{"id":19,"l":[{"p":"(a) The loop condition"}],"k":"blank","a":["i < qu.length"],"topics":["ARRAYS","DISJOINT_SETS"],"part":"a"},{"id":20,"l":[{"p":"(a) The loop update"}],"k":"blank","a":["i++","i += 1","i = i + 1","++i"],"topics":["ARRAYS","DISJOINT_SETS"],"part":"a"},{"id":21,"l":[{"p":"(a) if (____)"}],"k":"blank","a":["parent < 0","parent <= -1","0 > parent"],"topics":["ARRAYS","DISJOINT_SETS"],"part":"a"},{"id":22,"l":[{"p":"(a) If it’s the root"}],"k":"blank","a":["root = isles[i]"],"topics":["ARRAYS","DISJOINT_SETS"],"part":"a"},{"id":23,"l":[{"p":"(a) Otherwise"}],"k":"blank","a":["isles[parent].children.add(isles[i])"],"topics":["ARRAYS","DISJOINT_SETS"],"x":"A negative entry marks the root. Every other island is added to its parent’s children.","part":"a"},{"id":24,"l":[{"p":"(b) What is the best-case runtime of the constructor, in terms of N, the number of islands?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"part":"b"},{"id":25,"l":[{"p":"(b) What is its worst-case runtime?"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","DISJOINT_SETS"],"x":"Two passes over N islands, each step constant time, with no early exit.","part":"b"},{"s":[{"p":"(c) Two of the trees below are invalid WQUs, and one is valid. Which tree is valid?"},{"c":"Tree 1:        0\n              / \\\n             1   2\n            / \\\n           3   4\n\nTree 2:        0\n           /   |   \\\n          1    2    3\n         / \\       / \\\n        4   5     6   7\n\nTree 3:          0\n          /   /     \\    \\\n         1   2       8    3\n        / \\              / \\\n       4   5            6   7","lang":"txt"}]},{"id":26,"l":[{"p":"(c) Which tree is a valid WQU?"}],"k":"mc","o":["Tree 1","Tree 2","Tree 3"],"a":2,"topics":["DISJOINT_SETS"],"x":"Tree 3: union (1, 4), (1, 5), (3, 6), (3, 7), (0, 2), (0, 8), (0, 1), (0, 3). In Trees 1 and 2, 0 can never get big enough to become the parent of its larger subtrees.","part":"c"},{"id":27,"l":[{"p":"(d) True/False: Consider a WQU where node A is a parent of node B, and node B is a parent of node C. Node C must have been connected to node B before node B was connected to node A."}],"k":"mc","o":["True","False"],"a":0,"topics":["DISJOINT_SETS"],"x":"Once B is connected under A, B is no longer a root, and unions only ever attach roots, so C could never become B’s direct child afterwards.","part":"d"},{"s":[{"p":"(e) Complete isValid, which determines whether the TreasureMap corresponds to a valid Weighted Quick Union, and its size helper, which returns −1 if parent’s subtree is not a valid WQU and otherwise the number of nodes in it. Your solution must run in O(N log N) time. (Staff considered this significantly harder than the rest of the exam.)"},{"c":"public boolean isValid() {\n    ⟪f⟫;\n}\n\nprivate int size(Island parent) {\n    int currSize = 1;\n    ⟪g⟫ childSizes = new ⟪h⟫;\n    for (⟪i⟫) {\n        ⟪j⟫;\n    }\n    while (⟪k⟫) {\n        ⟪l⟫;\n        if (⟪m⟫) {\n            return -1; // Not a valid WQU\n        }\n        ⟪n⟫;\n    }\n    return ⟪o⟫;\n}","lang":"java","f":{"f":"return size(root) != -1","g":"PriorityQueue<Integer>","h":"PriorityQueue<>()","i":"Island child : parent.children","j":"childSizes.add(size(child))","k":"!childSizes.isEmpty()","l":"int smallest = childSizes.removeMin()","m":"smallest == -1 || smallest > currSize","n":"currSize += smallest","o":"currSize"}}]},{"id":28,"l":[{"p":"(e) The body of isValid"}],"k":"blank","a":["return size(root) != -1","return -1 != size(root)"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":29,"l":[{"p":"(e) The type of childSizes"}],"k":"blank","a":["PriorityQueue<Integer>","MinPQ<Integer>"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":30,"l":[{"p":"(e) childSizes = new ____"}],"k":"blank","a":["PriorityQueue<>()"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":31,"l":[{"p":"(e) The for loop’s header"}],"k":"blank","a":["Island child : parent.children"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":32,"l":[{"p":"(e) Inside the for loop"}],"k":"blank","a":["childSizes.add(size(child))"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":33,"l":[{"p":"(e) while (____)"}],"k":"blank","a":["!childSizes.isEmpty()","childSizes.size() > 0","childSizes.size() != 0"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":34,"l":[{"p":"(e) First line of the while loop"}],"k":"blank","a":["int smallest = childSizes.removeMin()"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":35,"l":[{"p":"(e) if (____) return -1"}],"k":"blank","a":["smallest == -1 || smallest > currSize","smallest > currSize || smallest == -1","smallest < 0 || smallest > currSize","smallest > currSize || smallest < 0"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":36,"l":[{"p":"(e) Last line of the while loop"}],"k":"blank","a":["currSize += smallest","currSize = currSize + smallest","currSize = smallest + currSize"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"part":"e"},{"id":37,"l":[{"p":"(e) size returns"}],"k":"blank","a":["currSize"],"topics":["DISJOINT_SETS","TREE_TRAVERSALS"],"x":"Build each subtree bottom-up: compute every child’s size, then union them into the parent smallest first. A child subtree can join only if it isn’t larger than the tree built so far (in a WQU the larger root wins). Any invalid subtree makes the whole tree invalid.","part":"e"}],"topics":null},{"id":"61b-sp25-mt2/4","n":"4","t":"4. Asymptotics (16.0 pts)","b":[{"s":[{"p":"For each statement, decide whether it is always true, or sometimes false. (The exam also offered “Decline”, scoring +2 per correct answer and −3 per incorrect one.)"},{"p":"Set I: Let f and g be real-valued, positive, strictly increasing functions."}]},{"id":38,"l":[{"p":"(a) If f(x) ∈ O(g(x)), then f(10¹⁰⁰) ≤ g(10¹⁰⁰)."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"O bounds only hold for large enough x, and 10¹⁰⁰ may not be large enough: f(x) = 1000 and g(x) = log₁₀(x) have f > g for all x < 10¹⁰⁰⁰.","part":"a"},{"id":39,"l":[{"p":"(b) If f(x) and g(x) are the best- and worst-case runtimes of a program, respectively, then f(x) ∈ O(g(x))."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS"],"x":"By definition f(x) ≤ g(x) for all x, so f(x) ≤ 1·g(x).","part":"b"},{"id":40,"l":[{"p":"(c) For all functions f(x), there exists some function g(x) ≠ f(x) such that f(x) ∈ Θ(g(x))."}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS"],"x":"Take g(x) = 2f(x). It equals f only where f(x) = 0, which a positive function never is.","part":"c"},{"id":41,"l":[{"p":"(d) If f(x) ∈ Θ(g(x)), then f⁻¹(x) ∈ Θ(g⁻¹(x)), where f⁻¹ is the inverse function of f."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"f(x) = log₂(x) and g(x) = log₃(x) differ by a constant factor, but their inverses 2ˣ and 3ˣ have ratio 1.5ˣ, which grows without bound.","part":"d"},{"id":42,"l":[{"p":"(e) If a program uses O(log(N)) memory in total (including inputs, local variables, and recursive function calls), then its worst-case runtime is O(Nᵏ) for some constant k."}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"while (true) {} uses constant memory and never finishes. (It is true if the program must terminate.)","part":"e"},{"s":[{"p":"Set II"}]},{"id":43,"l":[{"p":"(a) Σᵢ₌₁ᴺ i² ∈ Θ(Σᵢ₌₁^(N²) i)"}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"The first sum is Θ(N³), the second Θ(N⁴).","part":"a"},{"id":44,"l":[{"p":"(b) Σᵢ₌₁ᴺ log₁₀(i) ∈ Ω(Σᵢ₌₁ᴺ log₂(i))"}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS"],"x":"log₂(x) = log₂(10) · log₁₀(x), so the sums differ by a constant factor.","part":"b"},{"id":45,"l":[{"p":"(c) N³ ∈ Θ((N + 1)³)"}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS"],"x":"(N + 1)³ = N³ + 3N² + 3N + 1, which is Θ(N³).","part":"c"},{"id":46,"l":[{"p":"(d) log(N) ∈ O(N^0.0001)"}],"k":"mc","o":["True","False"],"a":0,"topics":["ASYMPTOTICS"],"x":"Any positive power of N eventually grows faster than log N.","part":"d"},{"id":47,"l":[{"p":"(e) N! ∈ Θ((N + 1)!)"}],"k":"mc","o":["True","False"],"a":1,"topics":["ASYMPTOTICS"],"x":"Their ratio is N + 1, which grows without bound.","part":"e"}],"topics":null},{"id":"61b-sp25-mt2/5","n":"5","t":"5. Hashing (12.0 pts)","b":[{"s":[{"p":"Putting mutable objects in a hash table is dangerous, even if the hashCode doesn’t change when an object is mutated: no hashCode can guarantee both efficiency and correctness for mutable objects."},{"p":"For each proposed hashCode for a List<Integer>, decide whether its flaw is invalidity (the hash table may behave incorrectly) or inefficiency (it works correctly, but may be slow). Two Lists are equal if they have the same items in the same order. (The exam also asked for an example or explanation; compare yours with the answer note.)"}]},{"id":48,"l":[{"p":"(a) Use the memory address of the List as its hashCode, which doesn’t change when the List is mutated."}],"k":"mc","o":["Invalidity","Inefficiency"],"a":0,"topics":["EQUALS","HASHING"],"x":"Two equal Lists at different addresses get different hash codes, so they can land in different buckets and both be added.","part":"a"},{"id":49,"l":[{"p":"(b) Have hashCode always return 0."}],"k":"mc","o":["Invalidity","Inefficiency"],"a":1,"topics":["HASHING"],"x":"Every item lands in the same bucket, so operations take linear time.","part":"b"},{"id":50,"l":[{"p":"(c) Add a cachedHash attribute to the List class. The first time hashCode is called, compute List<Integer>’s normal hashCode and save it in cachedHash; every later call returns cachedHash, even if the list has been mutated."}],"k":"mc","o":["Invalidity","Inefficiency"],"a":0,"topics":["EQUALS","HASHING"],"x":"Insert a = [1, 2], then mutate it to [1, 2, 3], then insert b = [1, 2, 3]. a keeps its old hash, so b may go to a different bucket and the set can end up with two copies of [1, 2, 3].","part":"c"}],"topics":null},{"id":"61b-sp25-mt2/6","n":"6","t":"6. Math Graphs (11.0 pts)","b":[{"s":[{"p":"Aditya has created Math Graphs to represent short arithmetic calculations. Each node contains a number, and each edge contains an arithmetic operation (addition, subtraction, multiplication, and floor division). A Math Path is a simple path in a Math Graph, and its value is the result of computing the expression along it, in path order with no precedence. For example, the path 8 →(+) 5 →(×) 3 →(−) 9 has value ((8 + 5) × 3) − 9 = 30."},{"c":"(a)  7 →(−) 2      7 →(+) 6      7 →(×) 8\n     2 →(÷) 1      2 →(+) 5\n     1 →(×) 4\n     8 →(−) 4      8 →(+) 5","lang":"txt"}]},{"id":51,"l":[{"p":"(a) For the Math Graph above, what is the value of the largest-valued Math Path starting from 7? Write your answer as an integer."}],"k":"blank","a":["61"],"topics":["GRAPH_TRAVERSALS"],"x":"7 × 8 = 56, then + 5 = 61.","part":"a"},{"id":52,"l":[{"p":"(b) True/False: If a Math Graph is a rooted tree, then its largest-valued Math Path will start at the root and end at a leaf."}],"k":"mc","o":["True","False"],"a":1,"topics":["GRAPH_TRAVERSALS"],"x":"Add a node −10000000 after each leaf of the graph above: ending earlier is now better.","part":"b"},{"s":[{"p":"Aditya wants the least-valued Math Path from one node to every other node, so he modifies Dijkstra’s: when evaluating a new path to a node, the path’s operation is applied between the current distance and the node’s value instead of adding an edge weight. A path’s value starts from the source’s own value (the table still lists distTo of the source as 0). For example, from node 1 in 1 →(+) 5, 5 →(×) 2, 5 →(+) 8, 2 →(×) 3, 8 →(−) 3, it first finds a path of value 36 to node 3 (((1 + 5) × 2) × 3), then relaxes it to 11 (((1 + 5) + 8) − 3)."},{"p":"(c) Fill out the distTo and edgeTo arrays after running this modified Dijkstra’s on the Math Graph below, starting from node A. Nodes are written name:value."},{"c":"A:3  B:6  C:3  D:2  E:1  F:4  G:5\n\nA →(+) D     A →(÷) E     A →(×) G\nB →(+) A     B →(+) C\nC →(−) F\nD →(−) F\nF →(×) B     F →(×) G\nG →(÷) E     G →(+) C","lang":"txt"}]},{"id":53,"l":[{"p":"(c) distTo for B, C, D, E, F, G, in that order, separated by commas"}],"k":"blank","a":["6, 8, 5, 3, 1, 5","6 8 5 3 1 5"],"topics":["SHORTEST_PATHS"],"part":"c"},{"id":54,"l":[{"p":"(c) edgeTo for B, C, D, E, F, G, in that order, separated by commas"}],"k":"blank","a":["F, G, A, A, D, F","F G A A D F"],"topics":["SHORTEST_PATHS"],"x":"From A (value 3): D = 3 + 2 = 5, E = 3 ÷ 1 = 3, F = 5 − 4 = 1 via D, G = 1 × 5 = 5 via F (better than 3 × 5), B = 1 × 6 = 6 via F, C = 5 + 3 = 8 via G (better than 6 + 3 via B).","part":"c"},{"s":[{"p":"For each type of Math Graph below, would the algorithm above always find a shortest paths tree? Assume all nodes are positive integers."}]},{"id":55,"l":[{"p":"(d) A Math Graph with only addition (+) and multiplication (×) operators."}],"k":"mc","o":["Always","Not always"],"a":0,"topics":["SHORTEST_PATHS"],"x":"With positive integers, + and × never make a path’s value smaller, so a finished node can’t be improved later.","part":"d"},{"id":56,"l":[{"p":"(e) A Math Graph with no division (÷) operators."}],"k":"mc","o":["Always","Not always"],"a":1,"topics":["SHORTEST_PATHS"],"x":"Subtraction alone can make a later path smaller, so Dijkstra’s can be wrong.","part":"e"},{"id":57,"l":[{"p":"(f) A Math Graph that is a tree."}],"k":"mc","o":["Always","Not always"],"a":0,"topics":["SHORTEST_PATHS"],"x":"In a tree there is only one path to each node, so the shortest paths tree is the only tree there is.","part":"f"}],"topics":null}],"by":["Yokota","Hug"]},{"id":"61b-sp26-final","t":"Spring 2026 Final","src":{"exam":"https://drive.google.com/file/d/1_hEpsaaXXBzYc7Q_-f6vNZ1Wp2wjSAIx/view","sol":"https://drive.google.com/file/d/1MQJcbLOn8YJD0sOyVpUsWvONps5nEWTl/view","topics":"sp26-final"},"p":[{"id":"61b-sp26-final/1","n":"1","t":"1. Blocking and Tackling (13.25 pts)","b":[{"s":[{"p":"Weighted Quick Union without path compression has parent array [-1, 3, -1, 6, 3, 6, -6, 6] for items 0 through 7."}]},{"id":1,"l":[{"p":"(1.1) Root of item 1"}],"k":"blank","a":["6"],"topics":["DISJOINT_SETS"],"x":"Follow 1 → 3 → 6; a negative parent entry marks the root."},{"id":2,"l":[{"p":"(1.2) Parent array after connect(1, 0)"}],"k":"blank","a":["6,3,-1,6,3,6,-7,6"],"topics":["DISJOINT_SETS"],"x":"Root 6 has weight 6 and root 0 has weight 1, so 0 joins 6."},{"s":[{"p":"A trie holds car, cast, cab, do, and dog. Each node stores one character; isKey marks the end of a key."}]},{"id":3,"l":[{"p":"(1.3) New nodes when inserting cart"}],"k":"blank","a":["1"],"topics":["TRIES"]},{"id":4,"l":[{"p":"(1.4) Keys returned by keysWithPrefix(\"ca\")"}],"k":"sata","o":["c","ca","car","cast","cab","None"],"a":[2,3,4],"topics":["TRIES"]},{"id":5,"l":[{"p":"(1.5) Insertion-sort swaps for [6, 1, 2, 4, 3, 5]"}],"k":"blank","a":["6"],"topics":["SORTING"],"x":"The number of swaps equals the number of inversions."},{"id":6,"l":[{"p":"(1.6) Why must LSD radix sort use a stable digit sort?"}],"k":"mc","o":["To preserve order from earlier digit passes","To prevent quadratic space use","To handle unequal-length keys","To avoid recursion"],"a":0,"topics":["SORTING","RADIX_SORTS"]},{"id":7,"l":[{"p":"(1.7) [123, 456, 132, 465, 100] after the ones-digit pass"}],"k":"blank","a":["100,132,123,465,456"],"topics":["RADIX_SORTS"]},{"s":[{"p":"For the next questions, use this directed graph: B→A, B→D, D→A, D→C, D→E, A→E. Weights: B→A 5, B→D 1, D→A 2, D→C 1, D→E 1, A→E 5. Consider neighbors alphabetically."}]},{"id":8,"l":[{"p":"(1.8) DFS preorder from B"}],"k":"blank","a":["B,A,E,D,C"],"topics":["GRAPH_TRAVERSALS"]},{"id":9,"l":[{"p":"(1.9) BFS order from B"}],"k":"blank","a":["B,A,D,E,C"],"topics":["GRAPH_TRAVERSALS"]},{"id":10,"l":[{"p":"(1.10) Dijkstra removal order from B"}],"k":"blank","a":["B,D,C,E,A","B,D,E,A,C"],"topics":["SHORTEST_PATHS"],"x":"The printed answer conflicts with its own trace. With alphabetical tie-breaking and the stated edges, C precedes E, and A comes last; the printed order is also accepted."},{"id":11,"l":[{"p":"(1.11) Number of valid topological sorts"}],"k":"blank","a":["3"],"topics":["TOPOLOGICAL_SORT"]},{"s":[{"p":"For Kruskal, use undirected edges with distinct weights: 1 A–B; 2 C–D; 3 B–C; 4 A–C; 5 D–E; 6 B–E; 7 E–F; 8 A–F."}]},{"id":12,"l":[{"p":"(1.12) MST edge weights in the order added"}],"k":"blank","a":["1,2,3,5,7"],"topics":["MSTS"]}],"topics":null},{"id":"61b-sp26-final/2","n":"2","t":"2. Sorta Familiar (12 pts)","b":[{"s":[{"p":"The max-heap arrays below use index 0 as the root. Start with [5,7,6,4,3,8,2,1]."}]},{"id":13,"l":[{"p":"(2.1) Result of inserting elements one at a time"}],"k":"blank","a":["8,5,7,4,3,6,2,1"],"topics":["HEAPS"]},{"id":14,"l":[{"p":"(2.2) Result of bottom-up heapifying the same array"}],"k":"blank","a":["8,7,6,4,3,5,2,1"],"topics":["HEAPS"]},{"id":15,"l":[{"p":"(2.3) [8,6,7,5,2,3,4,1] after one in-place heap-sort delete-max"}],"k":"blank","a":["7,6,4,5,2,3,1,8"],"topics":["HEAPS","SORTING"]},{"id":16,"l":[{"p":"(2.4) Which insertion order gives the maximum possible swaps for numbers 1–8?"}],"k":"mc","o":["1,2,3,4,5,6,7,8","8,7,6,5,4,3,2,1","5,7,6,4,3,8,2,1","1,3,5,7,2,4,6,8"],"a":0,"topics":["HEAPS"],"x":"In increasing order each new item swims to the root."},{"id":17,"l":[{"p":"(2.5) A bottom-up-heapify input with maximum swaps, with index 2 fixed at 1, index 5 at 2, and index 6 at 3"}],"k":"blank","a":["4,5,1,7,6,2,3,8","4,6,1,7,5,2,3,8","5,6,1,7,4,2,3,8"],"topics":["HEAPS"]},{"id":18,"l":[{"p":"(2.6) Maximum comparisons for selection sort, N=8"}],"k":"blank","a":["28"],"topics":["SORTING","COMPARISON_SORTS"]},{"id":19,"l":[{"p":"(2.6) Maximum comparisons for insertion sort, N=8"}],"k":"blank","a":["28"],"topics":["SORTING","COMPARISON_SORTS"]},{"id":20,"l":[{"p":"(2.6) Maximum comparisons for mergesort, N=8"}],"k":"blank","a":["17"],"topics":["SORTING","COMPARISON_SORTS"]},{"id":21,"l":[{"p":"(2.7) [6,3,9,2,8,1,7,4] after one Tony Hoare partition around 6"}],"k":"blank","a":["1,3,4,2,6,8,7,9"],"topics":["SORTING"]}],"topics":null},{"id":"61b-sp26-final/4","n":"4","t":"4. DS Time (13.5 pts)","b":[{"s":[{"p":"Worst-case Θ runtimes in N items. Ordinary BSTs need not be balanced; LLRBs are balanced. Hash tables use linked-list or LLRB buckets, spread evenly. The min-heap is array-backed."}]},{"id":22,"l":[{"p":"(4.1) BST find min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":23,"l":[{"p":"(4.1) BST delete min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":24,"l":[{"p":"(4.1) LLRB delete min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":1,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":25,"l":[{"p":"(4.1) Hash table (linked-list buckets) find min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":26,"l":[{"p":"(4.1) Hash table (LLRB buckets) find min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":27,"l":[{"p":"(4.1) Min-heap find min"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":0,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":28,"l":[{"p":"(4.1) Min-heap find max"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","BSTS","HASHING"]},{"id":29,"l":[{"p":"(4.2) Best-case insertion into an unbalanced BST: select every valid bound"}],"k":"sata","o":["Ω(1)","Ω(log N)","Ω(N)","Θ(1)","Θ(log N)","Θ(N)","O(1)","O(log N)","O(N)"],"a":[0,3,6,7,8],"topics":["ASYMPTOTICS","BSTS"],"x":"A new item can attach directly to the root."},{"id":30,"l":[{"p":"(4.3) Worst-case insertion into an unbalanced BST: select every valid bound"}],"k":"sata","o":["Ω(1)","Ω(log N)","Ω(N)","Θ(1)","Θ(log N)","Θ(N)","O(1)","O(log N)","O(N)"],"a":[0,1,2,5,8],"topics":["ASYMPTOTICS","BSTS"],"x":"A spindly tree can require a full descent."}],"topics":null},{"id":"61b-sp26-final/5","n":"5","t":"5. Hasheteria (8 pts)","b":[{"s":[{"p":"HashMap<Integer,String> starts with four buckets. Each bucket is an LLRB. Integer keys hash to themselves. Insert (5,cat), (0,dog), (1,egg), (4,pie), (9,fox), without resizing."}]},{"id":31,"l":[{"p":"(5.1) Bucket 0 after insertion"}],"k":"mc","o":["Black 4/pie root with red 0/dog left child","Black 0/dog root with red 4/pie right child","Black 4/pie root with black 0/dog left child","Empty"],"a":0,"topics":["RED_BLACK_TREES","HASHING"]},{"id":32,"l":[{"p":"(5.1) Bucket 1 after insertion"}],"k":"mc","o":["Black 5/cat root, black 1/egg left and 9/fox right","Black 9/fox root with red 5/cat left","Black 1/egg root with red 5/cat right","Empty"],"a":0,"topics":["RED_BLACK_TREES","HASHING"]},{"id":33,"l":[{"p":"(5.1) Buckets 2 and 3"}],"k":"mc","o":["Both empty","2 holds dog and 3 holds fox","2 empty, 3 holds egg","Both hold red nodes"],"a":0,"topics":["RED_BLACK_TREES","HASHING"]},{"id":34,"l":[{"p":"(5.2) Tightest worst-case O bound for contains in a table with N items"}],"k":"mc","o":["O(1)","O(log N)","O(N)","O(N log N)"],"a":1,"topics":["ASYMPTOTICS","HASHING"],"x":"All items can land in one balanced LLRB bucket."},{"id":35,"l":[{"p":"(5.3) Tightest worst-case O bound for a put that may resize"}],"k":"mc","o":["O(1)","O(log N)","O(N)","O(N log N)","O(N²)"],"a":3,"topics":["ASYMPTOTICS","HASHING"],"x":"Rehashing N entries into one balanced bucket can take O(N log N)."}],"topics":null},{"id":"61b-sp26-final/6","n":"6","t":"6. Hashing with Fire (5.5 pts)","b":[{"s":[{"p":"A HashSet<List<Integer>> has 10 buckets and no resizing. A list hash is its element sum plus its length. Start with L=[2,4,7], add L to the set, then mutate the same L. Its stored reference stays in its original bucket."}]},{"id":36,"l":[{"p":"(6.1) Which pair of appended values makes contains(L) print true, then false after removing that value?"}],"k":"mc","o":["9, then 0","0, then 9","9, then 19","0, then 10"],"a":0,"topics":["EQUALS","HASHING"],"x":"The original hash is 16, hence bucket 6. After appending x, the hash is 17+x."},{"s":[{"p":"Point2D.equals compares x and y, but ignores name. For each candidate hashCode body, decide if a HashSet always behaves correctly."}]},{"id":37,"l":[{"p":"(6.2) return 0;"}],"k":"mc","o":["Always correct","Sometimes incorrect"],"a":0,"topics":["EQUALS","HASHING"]},{"id":38,"l":[{"p":"(6.2) return x;"}],"k":"mc","o":["Always correct","Sometimes incorrect"],"a":0,"topics":["EQUALS","HASHING"]},{"id":39,"l":[{"p":"(6.2) return 31 * x + y;"}],"k":"mc","o":["Always correct","Sometimes incorrect"],"a":0,"topics":["EQUALS","HASHING"]},{"id":40,"l":[{"p":"(6.2) return name.hashCode();"}],"k":"mc","o":["Always correct","Sometimes incorrect"],"a":1,"topics":["EQUALS","HASHING"]},{"id":41,"l":[{"p":"(6.2) return 31 * x + y + name.hashCode();"}],"k":"mc","o":["Always correct","Sometimes incorrect"],"a":1,"topics":["EQUALS","HASHING"]}],"topics":null},{"id":"61b-sp26-final/7","n":"7","t":"7. Asymptotics (13.75 pts)","b":[{"s":[{"c":"void zoom(int[] arr, int idx) {\n    if (idx <= 1) return;\n    for (int i = 0; i < idx; i++) IO.println(\"hi\");\n    if (arr[idx-1] > 0) zoom(arr, idx/2);\n    else zoom(arr, idx-1);\n}","lang":"java"}]},{"id":42,"l":[{"p":"(7.1) Best-case runtime of zoom(arr,N)"}],"k":"mc","o":["Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":1,"topics":["ASYMPTOTICS","RECURSION"]},{"id":43,"l":[{"p":"(7.1) Worst-case runtime of zoom(arr,N)"}],"k":"mc","o":["Θ(log N)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":3,"topics":["ASYMPTOTICS","RECURSION"]},{"s":[{"p":"For each quicksort variant on distinct items, classify whether its runtime is never, sometimes, or always Θ(N²). Assume partition and shuffle cost Θ(N)."}]},{"id":44,"l":[{"p":"(7.2) Shuffle once, then use the leftmost pivot"}],"k":"mc","o":["Never Θ(N²)","Sometimes Θ(N²)","Always Θ(N²)"],"a":1,"topics":["ASYMPTOTICS","SORTING"]},{"id":45,"l":[{"p":"(7.2) No shuffle; use the leftmost pivot"}],"k":"mc","o":["Never Θ(N²)","Sometimes Θ(N²)","Always Θ(N²)"],"a":1,"topics":["ASYMPTOTICS","SORTING"]},{"id":46,"l":[{"p":"(7.2) No shuffle; find and use the median pivot in Θ(N)"}],"k":"mc","o":["Never Θ(N²)","Sometimes Θ(N²)","Always Θ(N²)"],"a":0,"topics":["ASYMPTOTICS","SORTING"]},{"id":47,"l":[{"p":"(7.2) Shuffle once; use the minimum pivot"}],"k":"mc","o":["Never Θ(N²)","Sometimes Θ(N²)","Always Θ(N²)"],"a":2,"topics":["ASYMPTOTICS","SORTING"]},{"id":48,"l":[{"p":"(7.2) Leftmost pivot; switch to mergesort at recursion depth 64"}],"k":"mc","o":["Never Θ(N²)","Sometimes Θ(N²)","Always Θ(N²)"],"a":0,"topics":["ASYMPTOTICS","SORTING"]},{"s":[{"c":"ArrayList<Integer> dedup(int[] arr) {\n    ArrayList<Integer> seen = new ArrayList<>();\n    for (int x : arr) if (!seen.contains(x)) seen.add(x);\n    return seen;\n}","lang":"java"}]},{"id":49,"l":[{"p":"(7.3) Best-case runtime of dedup"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":1,"topics":["LISTS","ASYMPTOTICS"]},{"id":50,"l":[{"p":"(7.3) Worst-case runtime of dedup"}],"k":"mc","o":["Θ(1)","Θ(N)","Θ(N log N)","Θ(N²)"],"a":3,"topics":["LISTS","ASYMPTOTICS"]},{"s":[{"c":"TreeSet<Integer> firstHundred(int[] arr) {\n    TreeSet<Integer> seen = new TreeSet<>();\n    for (int x : arr) {\n        seen.add(x);\n        if (seen.size() == 100) return seen;\n    }\n    return seen;\n}","lang":"java"}]},{"id":51,"l":[{"p":"(7.4) Best-case runtime of firstHundred"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":0,"topics":["ASYMPTOTICS","BSTS"],"x":"The first 100 items can be distinct, so the method stops after a constant number of iterations."},{"id":52,"l":[{"p":"(7.4) Worst-case runtime of firstHundred"}],"k":"mc","o":["Θ(1)","Θ(log N)","Θ(N)","Θ(N log N)"],"a":2,"topics":["ASYMPTOTICS","BSTS"],"x":"With fewer than 100 unique items it processes all N entries in a constant-size tree."}],"topics":null},{"id":"61b-sp26-final/8","n":"8","t":"8. BasicUndirectedGraph (16 pts)","b":[{"s":[{"p":"Represent an undirected graph as Map<Integer, Set<Integer>> adj. connect(p,q) adds an edge; disconnect removes one; neighbors returns the adjacent vertices or an empty set."},{"c":"BasicUndirectedGraph() { adj = ⟪a⟫; }\nvoid connect(int p, int q) {\n    if (!adj.containsKey(p)) ⟪b⟫;\n    if (!adj.containsKey(q)) ⟪c⟫;\n    ⟪d⟫;\n    ⟪e⟫;\n}","lang":"java","f":{"a":"new HashMap<>()","b":"adj.put(p, new HashSet<>())","c":"adj.put(q, new HashSet<>())","d":"adj.get(p).add(q)","e":"adj.get(q).add(p)"}}]},{"id":53,"l":[{"p":"(8.1) Initialize map"}],"k":"blank","a":["new HashMap<>()"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":54,"l":[{"p":"(8.1) Initialize p neighborhood"}],"k":"blank","a":["adj.put(p, new HashSet<>())"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":55,"l":[{"p":"(8.1) Initialize q neighborhood"}],"k":"blank","a":["adj.put(q, new HashSet<>())"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":56,"l":[{"p":"(8.1) Add q to p neighborhood"}],"k":"blank","a":["adj.get(p).add(q)"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":57,"l":[{"p":"(8.1) Add p to q neighborhood"}],"k":"blank","a":["adj.get(q).add(p)"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"s":[{"c":"void disconnect(int p, int q) {\n    if (adj.containsKey(p)) ⟪a⟫;\n    if (adj.containsKey(q)) ⟪b⟫;\n}","lang":"java","f":{"a":"adj.get(p).remove(q)","b":"adj.get(q).remove(p)"}}]},{"id":58,"l":[{"p":"(8.2) Remove q from p neighborhood"}],"k":"blank","a":["adj.get(p).remove(q)"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":59,"l":[{"p":"(8.2) Remove p from q neighborhood"}],"k":"blank","a":["adj.get(q).remove(p)"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"s":[{"c":"Set<Integer> neighbors(int p) {\n    if (!adj.containsKey(p)) return ⟪a⟫;\n    return ⟪b⟫;\n}","lang":"java","f":{"a":"new HashSet<>()","b":"adj.get(p)"}}]},{"id":60,"l":[{"p":"(8.3) Empty result for absent vertex"}],"k":"blank","a":["new HashSet<>()"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]},{"id":61,"l":[{"p":"(8.3) Existing neighborhood"}],"k":"blank","a":["adj.get(p)"],"topics":["ADTS","GRAPH_REPRESENTATIONS"]}],"topics":null},{"id":"61b-sp26-final/9","n":"9","t":"9. Concat (8 pts)","b":[{"s":[{"p":"Return true if any string in strs equals the concatenation of two strings in strs. The same element may be used twice. Assume no null strings."},{"c":"boolean concat(String[] strs) {\n    Set<String> seen = ⟪a⟫;\n    for (String s : strs) ⟪b⟫;\n    for (String a : strs) for (String b : strs) {\n        if (⟪c⟫) return true;\n    }\n    return false;\n}","lang":"java","f":{"a":"new HashSet<>()","b":"seen.add(s)","c":"seen.contains(a + b)"}}]},{"id":62,"l":[{"p":"(9.1) Efficient lookup structure"}],"k":"blank","a":["new HashSet<>()"],"topics":["ADTS","HASHING"]},{"id":63,"l":[{"p":"(9.1) Add a source string"}],"k":"blank","a":["seen.add(s)"],"topics":["ADTS","HASHING"]},{"id":64,"l":[{"p":"(9.1) Check a concatenation"}],"k":"blank","a":["seen.contains(a + b)"],"topics":["ADTS","HASHING"]}],"topics":null},{"id":"61b-sp26-final/10","n":"10","t":"10. Recursive Programming (10 pts)","b":[{"s":[{"p":"TreeNode has left, right, and int item. The methods operate on a BST."},{"c":"TreeNode max(TreeNode x) {\n    if (x == null) return null;\n    if (⟪a⟫) return x;\n    return ⟪b⟫;\n}","lang":"java","f":{"a":"x.right == null","b":"max(x.right)"}}]},{"id":65,"l":[{"p":"(10.1) Max base case"}],"k":"blank","a":["x.right == null"],"topics":["BSTS","RECURSION"]},{"id":66,"l":[{"p":"(10.1) Recurse right"}],"k":"blank","a":["max(x.right)"],"topics":["BSTS","RECURSION"]},{"s":[{"c":"TreeNode deleteMin(TreeNode x) {\n    if (x.left == null) return ⟪a⟫;\n    ⟪b⟫;\n    return x;\n}","lang":"java","f":{"a":"x.right","b":"x.left = deleteMin(x.left)"}}]},{"id":67,"l":[{"p":"(10.2) Root after deleting a minimum with no left child"}],"k":"blank","a":["x.right"],"topics":["BSTS","RECURSION"]},{"id":68,"l":[{"p":"(10.2) Reconnect the left subtree"}],"k":"blank","a":["x.left = deleteMin(x.left)"],"topics":["BSTS","RECURSION"]},{"s":[{"c":"void hibbardDelete(TreeNode x) {\n    TreeNode successor = ⟪a⟫;\n    ⟪b⟫;\n    ⟪c⟫;\n}","lang":"java","f":{"a":"min(x.right)","b":"x.item = successor.item","c":"x.right = deleteMin(x.right)"}}]},{"id":69,"l":[{"p":"(10.3) Choose successor"}],"k":"blank","a":["min(x.right)"],"topics":["BSTS","RECURSION"]},{"id":70,"l":[{"p":"(10.3) Replace item"}],"k":"blank","a":["x.item = successor.item"],"topics":["BSTS","RECURSION"]},{"id":71,"l":[{"p":"(10.3) Remove successor from right subtree"}],"k":"blank","a":["x.right = deleteMin(x.right)"],"topics":["BSTS","RECURSION"]}],"topics":null}],"by":["Hug","Ousterhout"]},{"id":"61b-sp26-mt2","t":"Spring 2026 Midterm 2","src":{"exam":"https://drive.google.com/file/d/19VDARqJvnlj-r2B6D0LCI8C2UarRPEA0/view","sol":"https://drive.google.com/file/d/1H89HDdt1d-mjn_jA3Q_P6YHyHCbULG2D/view","topics":"sp26-mt2"},"p":[{"id":"61b-sp26-mt2/1","n":"1","t":"1. Point Farming Be Like: (25.0 pts)","b":[{"id":1,"l":[{"p":"1.1 Select all of the statements that are true."}],"k":"sata","o":["Generics allow classes and interfaces to operate with multiple object types","A default method of an interface cannot be overridden","The @Test tag is just a reminder for the programmer and otherwise doesn’t do anything","The @Override tag is necessary for an overridden method to compile and run","None of the above"],"a":[0],"topics":["JAVA","INHERITANCE"]},{"id":2,"l":[{"p":"1.2 Select all options that internally use an Iterator. Assume that lst implements Iterable."}],"k":"sata","o":["for (int i = 0; i < n; i += 1)","for (int k : lst)","while (lst.size() > 0)","while (lst.next != null)","None of the above"],"a":[1],"topics":["JAVA","ITERATORS"],"x":"Only the enhanced for loop uses an Iterator. lst.next just reads an instance variable."},{"s":[{"p":"1.3 Given the code below, fill in the method header for compareTo."},{"c":"public class Mystery implements Comparable<String> {\n    ...\n    @Override\n    public _____ compareTo(_____ other) { ... }\n}","lang":"java"}]},{"id":3,"l":[{"p":"1.3 What goes in the first blank?"}],"k":"mc","o":["boolean","int","String","Mystery"],"a":1,"topics":["JAVA","COMPARATORS"],"x":"compareTo always returns an int."},{"id":4,"l":[{"p":"1.3 What goes in the second blank?"}],"k":"mc","o":["Mystery","Mystery<String>","String","Object"],"a":2,"topics":["JAVA","COMPARATORS"],"x":"The argument type is what’s in Comparable<…>."},{"id":5,"l":[{"p":"1.4 Select all of the data structures that have a height guaranteed to be O(log N)."}],"k":"sata","o":["BSTs","B-trees","LLRBs","Heaps","Weighted Quick Union with path compression","Weighted Quick Union without path compression","None of the above"],"a":[1,2,3,4,5],"topics":["DISJOINT_SETS","BSTS","HEAPS"],"x":"BSTs can be spindly, with height O(N)."},{"id":6,"l":[{"p":"1.5 Suppose we take a valid LLRB and change all red links to black, without performing any balancing operations. The resulting tree is:"}],"k":"mc","o":["Always a valid BST, and always a valid LLRB","Always a valid BST, but not always a valid LLRB","Not always a valid BST, but always a valid LLRB","Not always a valid BST, and not always a valid LLRB"],"a":1,"topics":["BSTS","RED_BLACK_TREES"],"x":"No node moves, so it’s still a BST. But 8 with a red left child 4 is a valid LLRB, and with that link black it isn’t."},{"s":[{"p":"1.6 In the LLRB below, the links labeled red are red; the others are black."},{"c":"            8\n      red /   \\\n         4     11\n        / \\    / red\n       2   5  10","lang":"txt"}]},{"id":7,"l":[{"p":"1.6 After inserting 9, which balancing operations are required? The first operation:"}],"k":"mc","o":["rotateLeft(10)","rotateRight(10)","rotateRight(11)","colorFlip(11)"],"a":2,"topics":["RED_BLACK_TREES"]},{"id":8,"l":[{"p":"1.6 The second operation:"}],"k":"mc","o":["rotateLeft(9)","rotateRight(11)","colorFlip(10)","colorFlip(11)"],"a":2,"topics":["RED_BLACK_TREES"]},{"id":9,"l":[{"p":"1.6 The third operation:"}],"k":"mc","o":["rotateLeft(8)","colorFlip(8)","colorFlip(10)","Unused"],"a":1,"topics":["RED_BLACK_TREES"],"x":"9 becomes 10’s red left child, so 11 has two left-leaning reds in a row: rotateRight(11) makes 10 the subtree root with red children 9 and 11. colorFlip(10) then makes 10 red, and 8 now has two red children, so colorFlip(8)."},{"id":10,"l":[{"p":"1.7 What is the resulting array after inserting 4 into the min heap [-, 1, 7, 2, 8, 15, 5, 3, 9]?"}],"k":"mc","o":["[-, 1, 7, 2, 8, 15, 5, 3, 9, 4]","[-, 1, 4, 2, 7, 15, 5, 3, 9, 8]","[-, 1, 2, 3, 7, 15, 5, 4, 9, 8]","[-, 1, 2, 3, 4, 5, 7, 8, 9, 15]"],"a":1,"topics":["HEAPS"],"x":"4 goes in at index 9 under 8 (index 4): swap; then under 7 (index 2): swap; then 1 at the root is smaller, so it stops."},{"s":[{"p":"1.8 Consider the Weighted Quick Union without path compression: [4, 2, -5, 6, -4, 2, 4, 2, 2]."}]},{"id":11,"l":[{"p":"1.8 What are the roots of the sets with the maximum height?"}],"k":"sata","o":["0","1","2","3","4","5","6","7","8"],"a":[4],"topics":["DISJOINT_SETS"]},{"id":12,"l":[{"p":"1.8 After calling union(6, 7), what are the new roots of the sets with the maximum height?"}],"k":"sata","o":["0","1","2","3","4","5","6","7","8"],"a":[2],"topics":["DISJOINT_SETS"],"x":"Root 2 has children 1, 5, 7, 8: height 1. Root 4 has 0 and 6 under it, and 3 under 6: height 2. union(6, 7) joins 4’s set (size 4) under 2 (size 5), giving 2 a tree of height 3."},{"id":13,"l":[{"p":"1.9 Select all of the Weighted Quick Unions that are valid without path compression."}],"k":"sata","o":["[-3, 0, 1, -2, 3]","[-5, 0, 0, 1, 2]","[-4, 0, 0, 1, -1]","[2, 0, -5, 2, 2]"],"a":[2,3],"topics":["DISJOINT_SETS"]},{"s":[{"p":"1.10 In the two heaps below, the letters represent unknown integer values. Find the range of possible values for each letter (heaps can contain duplicates)."},{"c":"Min heap:        4              Max heap:       185\n               /   \\                          /     \\\n              6     8                        M       10\n             / \\   / \\                      / \\     /  \\\n            6   K M   11                   5   99  K   -3","lang":"txt"}]},{"id":14,"l":[{"p":"1.10 The smallest possible K"}],"k":"blank","a":["6"],"topics":["HEAPS"]},{"id":15,"l":[{"p":"1.10 The largest possible K"}],"k":"blank","a":["10"],"topics":["HEAPS"]},{"id":16,"l":[{"p":"1.10 The smallest possible M"}],"k":"blank","a":["99"],"topics":["HEAPS"]},{"id":17,"l":[{"p":"1.10 The largest possible M"}],"k":"blank","a":["185"],"topics":["HEAPS"],"x":"Min heap: K ≥ 6 (its parent) and M ≥ 8. Max heap: K ≤ 10 and 99 ≤ M ≤ 185. Together: 6 ≤ K ≤ 10 and 99 ≤ M ≤ 185."},{"id":18,"l":[{"p":"1.11 What is the minimum height of a 2-3 tree with exactly 6 numbers? (Height is the number of edges from the root to a leaf.)"}],"k":"blank","a":["1"],"topics":["B_TREES"]},{"id":19,"l":[{"p":"1.11 And the maximum height?"}],"k":"blank","a":["1"],"topics":["B_TREES"],"x":"Height 0 holds at most 2 numbers; height 2 needs at least 7 (a 2-node root with two 2-node children and four leaves). So 6 numbers always give height 1."},{"id":20,"l":[{"p":"1.12 After inserting N distinct items into a hash set with resizing, the runtime of a contains operation is ____ Θ(N)."}],"k":"mc","o":["Never","Sometimes","Always"],"a":1,"topics":["ASYMPTOTICS","HASHING"],"x":"With well-spread hash codes it’s constant; if they all collide, one bucket holds all N items."},{"id":21,"l":[{"p":"1.13 Suppose you implement a hash set without resizing. The hash set will ____ return the correct answer for any call to contains."}],"k":"mc","o":["Never","Sometimes","Always"],"a":2,"topics":["HASHING"],"x":"Resizing affects speed, not correctness."},{"id":22,"l":[{"p":"1.14 Suppose you implement a hash set without resizing. After inserting N distinct items, the runtime for any call to contains will ____ be Θ(N)."}],"k":"mc","o":["Never","Sometimes","Always"],"a":1,"topics":["ASYMPTOTICS","HASHING"],"x":"With 4 buckets holding 1, 1, 1 and N − 3 items, contains is constant or linear depending on the bucket."}],"topics":null},{"id":"61b-sp26-mt2/2","n":"2","t":"2. Pregame (6.0 pts)","b":[{"s":[{"p":"Given the tree below, select the correct output for each traversal. Break ties alphabetically."},{"c":"           A\n         /   \\\n        B     C\n       / \\\n      D   E\n       \\  / \\\n       F G   H","lang":"txt"}]},{"id":23,"l":[{"p":"2.1 Level-order (BFS)"}],"k":"mc","o":["ABCDEFGH","ABDEFGHC","FGHDEBCA","FDGHEBCA"],"a":0,"topics":["TREE_TRAVERSALS"]},{"id":24,"l":[{"p":"2.2 DFS pre-order"}],"k":"mc","o":["ABCDEFGH","ABDEFGHC","ABDFEGHC","ABDFGEHC"],"a":2,"topics":["TREE_TRAVERSALS"]},{"id":25,"l":[{"p":"2.3 DFS post-order"}],"k":"mc","o":["FDBGHECA","FDGHEBCA","FGHCDEBA","FGHDEBCA"],"a":1,"topics":["TREE_TRAVERSALS"]},{"id":26,"l":[{"p":"2.4 DFS in-order"}],"k":"mc","o":["ABCDEFGH","DFBGEHAC","DFGEHBAC","FGHDEBCA"],"a":1,"topics":["TREE_TRAVERSALS"]},{"id":27,"l":[{"p":"2.5 Select all statements that are true."}],"k":"sata","o":["When run from the same starting node, DFS and BFS will always visit the same set of nodes","DFS is typically implemented with a queue, and BFS is typically implemented with a stack","DFS and BFS have the same time complexity when run on a spindly tree","For an unweighted, connected graph, BFS will always find the shortest path tree from the starting node","None of the above"],"a":[0,2,3],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"],"x":"DFS uses a stack (or recursion) and BFS a queue. Both are O(V + E) whatever the shape. BFS on an unweighted graph is like Dijkstra’s with equal weights, so it finds the shortest paths tree."}],"topics":null},{"id":"61b-sp26-mt2/3","n":"3","t":"3. Can I Speak to Your Supervisor? (25.0 pts)","b":[{"s":[{"p":"In Aditya’s family, a child’s last name is their father’s first name: if Aditya’s father is Lebron James, Aditya’s full name is Aditya Lebron. An AdityaLink is a parent-child relationship (an edge) where the parent node’s firstName equals the child node’s lastName. Not all links in a tree are necessarily AdityaLinks."}]},{"id":28,"l":[{"p":"3.1 In a tree with V vertices, at most how many AdityaLinks can there be?"}],"k":"mc","o":["1","V/2","V − 1","V","Cannot be determined with just V"],"a":2,"topics":["TREE_TRAVERSALS"],"x":"A tree with V vertices has V − 1 edges."},{"s":[{"p":"3.2 Implement countAdityaLinks, which takes the root node of a tree and returns the total number of AdityaLinks in it."},{"c":"public class Node {\n    public String firstName;\n    public String lastName;\n    public List<Node> children;\n    ...\n}\n\npublic int countAdityaLinks(Node root) {\n    int num = 0;\n    Queue<Node> queue = new LinkedList<>();\n    ⟪a⟫;\n    while (⟪b⟫) {\n        Node n = ⟪c⟫;\n        for (Node child : ⟪d⟫) {\n            if (⟪e⟫) {\n                ⟪f⟫;\n            }\n            ⟪g⟫;\n        }\n    }\n    return num;\n}","lang":"java","f":{"a":"queue.add(root)","b":"queue.size() != 0","c":"queue.remove()","d":"n.children","e":"n.firstName.equals(child.lastName)","f":"num++","g":"queue.add(child)"}}]},{"id":29,"l":[{"p":"3.2 Before the loop"}],"k":"blank","a":["queue.add(root)"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":30,"l":[{"p":"3.2 while (____)"}],"k":"blank","a":["queue.size() != 0","!queue.isEmpty()","queue.size() > 0"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":31,"l":[{"p":"3.2 Node n = ____"}],"k":"blank","a":["queue.remove()"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":32,"l":[{"p":"3.2 for (Node child : ____)"}],"k":"blank","a":["n.children"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":33,"l":[{"p":"3.2 if (____)"}],"k":"blank","a":["n.firstName.equals(child.lastName)","child.lastName.equals(n.firstName)"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":34,"l":[{"p":"3.2 Inside the if"}],"k":"blank","a":["num++","num += 1","num = num + 1","++num"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":35,"l":[{"p":"3.2 After the if"}],"k":"blank","a":["queue.add(child)"],"topics":["TREE_TRAVERSALS","GRAPH_TRAVERSALS"]},{"id":36,"l":[{"p":"3.3 Which algorithm best describes countAdityaLinks?"}],"k":"mc","o":["Iterative BFS","Recursive BFS","Iterative DFS","Recursive DFS"],"a":0,"topics":["GRAPH_TRAVERSALS"],"x":"It takes nodes from a queue in a loop. (Some students wrote a recursive DFS instead, which also works.)"},{"s":[{"p":"Note: 3.4–3.6 are independent of 3.1–3.3."},{"p":"A KarenTree is a tree where, for every node, the node’s supervisor equals the name of any one of its ancestors. The ancestors of a non-root node n are all the nodes on the path from the root to n, excluding n. The root’s ancestor is itself."},{"c":"public class Node {\n    public String name;\n    public String supervisor;\n    public List<Node> children;\n    ...\n}","lang":"java"},{"p":"3.4 Which of the following trees is a valid KarenTree? Exactly one is valid. Each node is written name (supervisor), with children indented under their parent."},{"c":"Tree 1:\nAditya (Aditya)\n  Natalia (Aditya)\n    Rushil (Natalia)\n      Avik (Aditya)\n      Ishanth (Brian)\n      Amanda (Natalia)\n\nTree 2:\nPeyrin (Peyrin)\n  Alvin (Peyrin)\n  Joey (Peyrin)\n    Narges (Joey)\n    Kubi (Alvin)\n\nTree 3:\nJustin (Justin)\n  Gireeja (Justin)\n    Sergey (Gireeja)\n  Alyosha (Justin)\n  Miki (Justin)\n    John (Miki)\n    Dan (Justin)","lang":"txt"}]},{"id":37,"l":[{"p":"3.4 Which tree is a valid KarenTree?"}],"k":"mc","o":["Tree 1","Tree 2","Tree 3"],"a":2,"topics":["TREE_TRAVERSALS"],"x":"In Tree 1, Brian isn’t an ancestor of Ishanth. In Tree 2, Alvin is higher up but on a different branch, so not an ancestor of Kubi."},{"s":[{"p":"3.5 Implement isKarenTree, which takes the root node of a tree and returns whether it is a KarenTree. All names are unique, the input isn’t null, no Nodes in children are null, supervisor is never null, and the root’s supervisor equals its name."},{"c":"public boolean isKarenTree(Node root) {\n    ⟪a⟫ ancestors = ⟪b⟫;\n    ⟪c⟫;\n    ⟪d⟫;\n}\n\nprivate boolean karenHelper(Node n, Set<String> ancestors) {\n    if (⟪e⟫) {\n        return false;\n    }\n    ⟪f⟫;\n    for (Node child : ⟪g⟫) {\n        if (⟪h⟫) {\n            ⟪i⟫;\n        }\n    }\n    ⟪j⟫;\n    ⟪k⟫;\n}","lang":"java","f":{"a":"Set<String>","b":"new HashSet<>()","c":"ancestors.add(root.supervisor)","d":"return karenHelper(root, ancestors)","e":"!ancestors.contains(n.supervisor)","f":"ancestors.add(n.name)","g":"n.children","h":"!karenHelper(child, ancestors)","i":"return false","j":"ancestors.remove(n.name)","k":"return true"}}]},{"id":38,"l":[{"p":"3.5 The type of ancestors"}],"k":"blank","a":["Set<String>","HashSet<String>"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":39,"l":[{"p":"3.5 ancestors = ____"}],"k":"blank","a":["new HashSet<>()","new HashSet<String>()","new TreeSet<>()"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":40,"l":[{"p":"3.5 Next line of isKarenTree"}],"k":"blank","a":["ancestors.add(root.supervisor)","ancestors.add(root.name)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":41,"l":[{"p":"3.5 Last line of isKarenTree"}],"k":"blank","a":["return karenHelper(root, ancestors)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":42,"l":[{"p":"3.5 if (____) return false"}],"k":"blank","a":["!ancestors.contains(n.supervisor)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":43,"l":[{"p":"3.5 After that check"}],"k":"blank","a":["ancestors.add(n.name)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":44,"l":[{"p":"3.5 for (Node child : ____)"}],"k":"blank","a":["n.children"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":45,"l":[{"p":"3.5 if (____) inside the loop"}],"k":"blank","a":["!karenHelper(child, ancestors)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":46,"l":[{"p":"3.5 Inside that if"}],"k":"blank","a":["return false"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":47,"l":[{"p":"3.5 After the loop"}],"k":"blank","a":["ancestors.remove(n.name)"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"]},{"id":48,"l":[{"p":"3.5 Last line of karenHelper"}],"k":"blank","a":["return true"],"topics":["ADTS","TREE_TRAVERSALS","RECURSION"],"x":"Keep the set of names on the path from the root. Each node’s supervisor must be in it; add the node’s name before visiting its children, and remove it afterwards so siblings’ subtrees don’t see it."},{"id":49,"l":[{"p":"3.6 Which algorithm best describes isKarenTree?"}],"k":"mc","o":["Iterative BFS","Recursive BFS","Iterative DFS","Recursive DFS"],"a":3,"topics":["GRAPH_TRAVERSALS","RECURSION"]}],"topics":null},{"id":"61b-sp26-mt2/4","n":"4","t":"4. FAHHHHHH-symptotics (12.0 pts)","b":[{"s":[{"p":"4.1 What is the runtime of factor in terms of N?"},{"c":"public void factor(int N) {\n    if (N <= 1) {\n        return;\n    }\n    for (int i = 2; i <= N; i += 1) {\n        if (N % i == 0) {\n            factor(N/i);\n            return;\n        }\n    }\n}","lang":"java"}]},{"id":50,"l":[{"p":"4.1 Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(3ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":2,"topics":["ASYMPTOTICS","RECURSION"]},{"id":51,"l":[{"p":"4.1 Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(3ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":4,"topics":["ASYMPTOTICS","RECURSION"],"x":"Best: N is a power of 2, so each call divides by 2 right away: Θ(log N). Worst: N is prime, so the loop runs to N once. Note the return right after the recursive call."},{"s":[{"p":"4.2 What is the runtime of ethan in terms of N?"},{"c":"public void ethan(int N) {\n    int remaining = N;\n    while (remaining > 1) {\n        if (Math.random() > 0.5) {\n            return;\n        }\n        remaining -= tam(N);\n    }\n}\n\npublic int tam(int k) {\n    int m = 0;\n    for (int i = 1; i < Math.sqrt(k); i += 1) {\n        m += 1;\n    }\n    return m;\n}","lang":"java"}]},{"id":52,"l":[{"p":"4.2 Best case"}],"k":"mc","o":["Θ(1)","Θ(√(log N))","Θ(log N)","Θ(N^(1/4))","Θ(√N)","Θ(√N log N)","Θ(N)","Θ(N√N)","Θ(N²)","Infinite loop"],"a":0,"topics":["ASYMPTOTICS","ITERATION"]},{"id":53,"l":[{"p":"4.2 Worst case"}],"k":"mc","o":["Θ(1)","Θ(√(log N))","Θ(log N)","Θ(N^(1/4))","Θ(√N)","Θ(√N log N)","Θ(N)","Θ(N√N)","Θ(N²)","Infinite loop"],"a":6,"topics":["ASYMPTOTICS","ITERATION"],"x":"Best: Math.random() > 0.5 at once. Worst: each iteration does √N work and subtracts about √N, so √N iterations: Θ(N)."},{"s":[{"p":"4.3 What is the runtime of removeDupesAndSort in terms of N, where N = arr.length? Assume all HashSet operations run in Θ(1)."},{"c":"public int[] removeDupesAndSort(int[] arr) {\n    Set<Integer> seen = new HashSet<>();\n    MinPQ<Integer> pq = new MinPQ<>(); // heap based MinPQ\n\n    for (int x : arr) {\n        if (!seen.contains(x)) {\n            pq.insert(x);\n            seen.add(x);\n        }\n    }\n\n    int[] result = new int[pq.size()];\n    for (int i = 0; i < result.length; i += 1) {\n        result[i] = pq.removeSmallest();\n    }\n    return result;\n}","lang":"java"}]},{"id":54,"l":[{"p":"4.3 Best case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(3ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":4,"topics":["ASYMPTOTICS","HASHING","HEAPS"]},{"id":55,"l":[{"p":"4.3 Worst case"}],"k":"mc","o":["Θ(1)","Θ(log(log N))","Θ(log N)","Θ((log N)²)","Θ(N)","Θ(N log N)","Θ(N²)","Θ(N² log N)","Θ(N³)","Θ(N³ log N)","Θ(2ᴺ)","Θ(3ᴺ)","Θ(N!)","Θ(Nᴺ)","Infinite loop"],"a":5,"topics":["ASYMPTOTICS","HASHING","HEAPS"],"x":"Best: all duplicates, so one insert and one removal after a Θ(N) scan. Worst: no duplicates, N inserts and N removals at Θ(log N) each."}],"topics":null},{"id":"61b-sp26-mt2/5","n":"5","t":"5. Tell Your Cat I Said pspspSPTs (and msmsMSTs i guess) (23.0 pts)","b":[{"s":[{"p":"5.1 Suppose we run Dijkstra’s algorithm on this directed graph, starting from A and breaking ties alphabetically:"},{"c":"A → B   4        B → D   6        F → A   7\nA → C   2        B → F   1        F → C   3\nC → E   5        D → E   2        F → D   2\n                                  F → E   3","lang":"txt"}]},{"id":56,"l":[{"p":"5.1 distTo for B, C, D, E, F (in that order, separated by commas) immediately after removing B from the fringe and relaxing all of B’s outgoing edges"}],"k":"blank","a":["4, 2, 10, 7, 5","4 2 10 7 5"],"topics":["SHORTEST_PATHS"]},{"id":57,"l":[{"p":"5.1 edgeTo for B, C, D, E, F at that point"}],"k":"blank","a":["A, A, B, C, B","A A B C B"],"topics":["SHORTEST_PATHS"],"x":"A is removed first (C = 2, B = 4), then C (E = 7 via C), then B (D = 10 and F = 5 via B)."},{"s":[{"p":"5.2 Suppose we run Kruskal’s algorithm on this undirected graph. For each iteration, select the edge(s) that could be added to the MST."},{"c":"A — B   6        A — E   5        B — E   3\nA — D   7        B — C   3        C — E   2\nC — D   8        D — E   5","lang":"txt"}]},{"id":58,"l":[{"p":"5.2 First iteration"}],"k":"sata","o":["A-B","A-D","A-E","B-C","B-E","C-D","C-E","D-E"],"a":[6],"topics":["MSTS"],"x":"The lightest edge is C–E (2)."},{"id":59,"l":[{"p":"5.2 Second iteration"}],"k":"sata","o":["A-B","A-D","A-E","B-C","B-E","C-D","C-E","D-E"],"a":[3,4],"topics":["MSTS"],"x":"B–C and B–E both weigh 3 and no tiebreak is given."},{"id":60,"l":[{"p":"5.2 Third iteration"}],"k":"sata","o":["A-B","A-D","A-E","B-C","B-E","C-D","C-E","D-E"],"a":[2,7],"topics":["MSTS"],"x":"Once either B edge is in, the other makes a cycle, so the next lightest is 5: A–E or D–E."},{"id":61,"l":[{"p":"5.3 True or false: for every vertex in a directed acyclic graph with positive edge weights, Josh wants the length of the longest path from a source s. A valid solution is to negate the edge weights, run Dijkstra’s from s, and use the final distTo values as the lengths."}],"k":"mc","o":["True","False"],"a":1,"topics":["GRAPH_TRAVERSALS","SHORTEST_PATHS"],"x":"Counterexample: s → A (1), s → B (2), A → B (1000), B → C (2). Negated, Dijkstra’s takes s → B (−2) first and finishes B before finding s → A → B, so it never finds the longest path s → A → B → C."},{"id":62,"l":[{"p":"5.4 True or false: given a graph G with V ≥ 3 vertices and only non-negative edge weights, Karen can change exactly one edge’s weight to 0 to minimize the shortest path from A to B. A valid solution is to run Dijkstra’s from A to find the shortest path to B, then set the heaviest edge on that path to 0."}],"k":"mc","o":["True","False"],"a":1,"topics":["SHORTEST_PATHS"],"x":"Counterexample: A–B 8, A–C 2, C–B 3. The shortest path is A–C–B; zeroing its heaviest edge gives 2, but zeroing A–B gives 0."},{"id":63,"l":[{"p":"5.5 For a connected graph G with N ≥ 3 vertices and N edges with unique edge weights, the MST of G will ____ consist of all edges except the one with maximum weight."}],"k":"mc","o":["Always","Not always"],"a":1,"topics":["MSTS"],"x":"Counterexample: A–B 4, B–C 2, B–D 3, C–D 1. The heaviest edge A–B is the only way to reach A, so the MST drops B–D instead."},{"s":[{"p":"5.6 No valid topological ordering exists for this directed graph:"},{"c":"R → H    R → I    U → I    I → U    U → L\nS → L    L → I    I → H","lang":"txt"}]},{"id":64,"l":[{"p":"5.6 Which single edge needs to be removed so that a valid topological ordering exists?"}],"k":"mc","o":["I → H","I → U","L → I","R → H","R → I","S → L","U → I","U → L"],"a":1,"topics":["TOPOLOGICAL_SORT"],"x":"I → U is in both cycles: U → L → I → U and U → I → U."},{"s":[{"p":"5.7 Consider the DAG with edges A → V, V → K and I → K. Select all vertices that could be at each index of any valid topological ordering."}]},{"id":65,"l":[{"p":"5.7 Index 0"}],"k":"sata","o":["A","V","I","K"],"a":[0,2],"topics":["TOPOLOGICAL_SORT"]},{"id":66,"l":[{"p":"5.7 Index 1"}],"k":"sata","o":["A","V","I","K"],"a":[0,1,2],"topics":["TOPOLOGICAL_SORT"]},{"id":67,"l":[{"p":"5.7 Index 2"}],"k":"sata","o":["A","V","I","K"],"a":[1,2],"topics":["TOPOLOGICAL_SORT"]},{"id":68,"l":[{"p":"5.7 Index 3"}],"k":"sata","o":["A","V","I","K"],"a":[3],"topics":["TOPOLOGICAL_SORT"],"x":"The orderings are AVIK, AIVK and IAVK, so index 0 can be A or I, index 1 A, V or I, index 2 V or I, and K is always last."}],"topics":null},{"id":"61b-sp26-mt2/6","n":"6","t":"6. Dear Chat, (9.0 pts)","b":[{"id":69,"l":[{"p":"6.1 Select all of the statements that are true about Project 3: Percolation."}],"k":"sata","o":["For an N × N grid, if percolates returns true, then at most N sites must be open","The percolates method does not require any arguments","The backwash problem was solved by making all methods run in O(log N) time","isOpen runs in Θ(log N) in the worst case","None of the above"],"a":[1],"topics":["DISJOINT_SETS","PERCOLATION"],"x":"With every site open it percolates. percolates just checks whether the virtual top connects to the virtual bottom. Backwash has nothing to do with runtime, and isOpen uses a separate (non-WQU) structure."},{"id":70,"l":[{"p":"6.2 Select all of the statements that are true about Project 4: WordNet."}],"k":"sata","o":["The k == 0 case did not use NGramMap, and the k != 0 case did use NGramMap","A word can appear in multiple synsets, and a synset can contain multiple words","If our input was [\"dog\", \"cow\"], then HyponymsHandler returns all the hyponyms of \"dog\" plus all the hyponyms of \"cow\"","A recursive graph traversal is more efficient than an iterative traversal due to the WordNet graph’s cyclical nature","None of the above"],"a":[0,1],"topics":["GRAPH_TRAVERSALS"],"x":"k != 0 needs word counts from NGramMap. Multiple words return the intersection of their hyponyms, not the union. The WordNet graph isn’t cyclic, and cycles wouldn’t make recursion faster anyway."},{"s":[{"p":"6.3 Suppose we execute the following lines using the BSTMap from Homework 6."},{"c":"BSTMap<Integer, String> map = new BSTMap<>();\nmap.put(3, \"Kevin\");\nmap.put(3, \"Gru\");\nmap.put(50, \"Stuart\");\nmap.put(34, \"Agnes\");","lang":"java"}]},{"id":71,"l":[{"p":"6.3 What does map.size() return?"}],"k":"mc","o":["1","2","3","4"],"a":2,"topics":["ADTS","BSTS"]},{"id":72,"l":[{"p":"6.3 Calling map.put(66, \"Victor\") requires comparisons to which of the following?"}],"k":"sata","o":["3","34","50","\"Agnes\"","\"Gru\"","\"Kevin\"","\"Stuart\""],"a":[0,2],"topics":["ADTS","BSTS"],"x":"The second put replaces 3’s value, so the map is 3 → 50 → 34 (left of 50). Only keys are compared: 66 goes right of 3, then right of 50."},{"s":[{"p":"6.4 Given the stack trace below, which method of ArrayDeque61B.java contains the line that triggers the exception?"},{"c":"java.lang.IndexOutOfBoundsException: Index 8 out of bounds for length 8\n  at ArrayDeque61B.get(ArrayDeque61B.java:34)\n  at ArrayDeque61B.toList(ArrayDeque61B.java:67)\n  at ArrayDeque61B.printDeque(ArrayDeque61B.java:99)\n  at TestDeque.test1(TestDeque.java:64)","lang":"txt"}]},{"id":73,"l":[{"p":"6.4 Which method?"}],"k":"mc","o":["get","toList","printDeque","test1"],"a":0,"topics":["TESTING","DEQUES"],"x":"The top of a stack trace is the most recent call, where the exception was thrown."}],"topics":null}],"by":["Hug","Ousterhout"]}],"collections":[{"id":"midterm1","label":"Mini-Midterm 1","ref":"Mini-Midterm 1","sub":"Lectures 1–12","coverage":{"text":"Fall 2026 Mini-Midterm 1 (Wed 9/23, 8–9:20pm), given after lecture 12. This option assumes it covered lectures 1–12.","url":"https://fa26.datastructur.es/"},"scope":{"basis":"topics","topics":["JAVA","GIT","TESTING","LISTS","LINKED_LISTS","ARRAYS","DEQUES","ABSTRACTION","INHERITANCE","DMS","ITERATORS","COMPARATORS","EQUALS","ITERATION","RECURSION"],"note":"Problems are included when every topic tagged on them was taught before Mini-Midterm 1. That classification is this site’s, not a staff recommendation."},"noPicks":"Course staff haven’t named practice questions here yet, so nothing is marked recommended.","timed":{"pool":"source","lengths":[{"min":50,"count":3},{"min":110,"count":6}],"balanced":false,"intro":"Each exam draws past Midterm 1 problems at random. They aren’t modified, so you may have seen some of them already."},"exams":[{"exam":"61b-fa25-mt1"},{"exam":"61b-sp25-mt1","note":"The printed staff key for 2(a) reads index j − 1 starting from j = 0, which would go out of bounds; this site accepts the corrected loop."},{"exam":"61b-fa24-mt1","note":"The staff key for 1(a) line 3 reads “spawn FootballPlayer”, but the code prints “spawn Footballer”; this site accepts both."},{"exam":"61b-sp24-mt1"},{"exam":"61b-fa23-mt1","note":"Staff note that Q2 mixes overloading and overriding, which more recent semesters treat as out of scope."},{"exam":"61b-sp23-mt1","note":"This exam’s points total 4800."},{"exam":"61b-fa22-mt1","note":"This exam’s points total 2400. The box-and-pointer diagram (1a) is asked as questions about the final state."},{"exam":"61b-sp21-mt1","note":"This exam’s points total 1280. Written explanations are asked as multiple choice, and 6(d) (0 points) is left out."},{"exam":"61b-fa20-mt1","note":"Coding answers follow the staff solution’s structure. Testing prompts in Q6 are adapted to multiple choice; the administrative Q1 is left out."},{"exam":"61b-sp19-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp18-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp17-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp16-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp15-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."}]},{"id":"midterm2","label":"Midterm 2","ref":"Midterm 2","sub":"Through tries","coverage":{"text":"Fall 2026 Midterm 2 (Wed 11/4, 8–10pm). This site hasn’t confirmed its scope yet; this option assumes everything through lecture 28 (Tries).","url":"https://fa26.datastructur.es/"},"scope":{"basis":"topics","topics":["JAVA","GIT","TESTING","LISTS","LINKED_LISTS","ARRAYS","DEQUES","ABSTRACTION","INHERITANCE","DMS","ITERATORS","COMPARATORS","EQUALS","ITERATION","RECURSION","ASYMPTOTICS","DISJOINT_SETS","ADTS","BSTS","B_TREES","RED_BLACK_TREES","HEAPS","TREE_TRAVERSALS","GRAPH_TRAVERSALS","GRAPH_REPRESENTATIONS","SHORTEST_PATHS","MSTS","TOPOLOGICAL_SORT","HASHING","TRIES","PERCOLATION"],"note":"Problems are included when every topic tagged on them was taught by lecture 28. The scope is this site’s guess until course staff confirm it."},"noPicks":"Course staff haven’t named practice questions here yet, so nothing is marked recommended.","timed":{"pool":"source","lengths":[{"min":50,"count":3},{"min":110,"count":7}],"balanced":false,"intro":"Each exam draws past Midterm 2 problems at random. They aren’t modified, so you may have seen some of them already."},"exams":[{"exam":"61b-fa25-mt2"},{"exam":"61b-sp26-mt2","note":"This site asks 5.3–5.5 as True/False only; the counterexamples are in the answer notes."},{"exam":"61b-sp25-mt2","note":"This site asks the LLRB table (2a) as three questions, the hashing parts (5) for the verdict only, and the asymptotics sets (4) without the exam’s Decline option."},{"exam":"61b-fa24-mt2","note":"This site asks the drawn answers (the pairs in 3b, the LLRB in 4a) as multiple choice, and 3e as which listed hash lists loop forever."},{"exam":"61b-sp24-mt2","note":"Staff removed 1(k) after grading, so it’s left out. This site asks the write-in Θ answers in 2(a)–(d) as multiple choice."},{"exam":"61b-fa23-mt2","note":"This site asks the LLRB operation table (2b) one operation at a time, and the tables in 4 as two blanks each (the numbers, then their indices)."},{"exam":"61b-sp23-mt2","note":"This exam’s point values are written ×100. This site asks Q6 Part 1 for the classification only; the reasons and colliding words are in the answer notes."},{"exam":"61b-fa22-mt2","note":"This exam’s points total 4000. This site asks the hash table and 2-3 tree drawings (3, 4a) as fill-in questions, and the design question (8) as multiple choice with the method descriptions in the answer note."},{"exam":"61b-sp21-mt2","note":"This exam’s points total 1920. Pictures are written as text, and the free-form setIterator (6) has blanks following the solution’s structure."},{"exam":"61b-fa20-mt2","note":"This exam’s points total 960. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Pictures are written as text, and compress (5) and window (8c) have blanks following the solution’s structure."},{"exam":"61b-sp19-mt2","note":"This exam’s points total 480. Drawn trees are written as value(left, right); drawn answers are multiple choice or fill-in. In 10(a), g2’s loop as printed never ends, so this site accepts that as well as the staff answer."},{"exam":"61b-sp18-mt2","note":"This exam’s points total 240. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers and the free-response algorithm (9) are multiple choice or fill-in."},{"exam":"61b-sp17-mt2","note":"This exam’s points total 120. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers and the free-response algorithm (8d) are multiple choice or fill-in; 7(e), graded on the explanation alone, is left out."},{"exam":"61b-sp16-mt2","note":"This exam’s points total 60. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers are fill-in or multiple choice; Q7, drawn with pictorial symbols, is left out."},{"exam":"61b-sp15-mt2","note":"The course’s topic index doesn’t cover this exam, so its topic tags are this site’s. Drawn answers are fill-in or multiple choice, and the short-answer and design questions (2c, 4a, 6, 7, 10) are multiple choice with the staff’s reasoning in the answer notes."}]},{"id":"final","label":"Final","ref":"the final","sub":"Comprehensive","coverage":{"text":"Fall 2026 Final (Thu 12/17, 3–6pm). This option assumes the whole course.","url":"https://fa26.datastructur.es/"},"scope":{"basis":"topics","topics":["JAVA","GIT","TESTING","LISTS","LINKED_LISTS","ARRAYS","DEQUES","ABSTRACTION","INHERITANCE","DMS","ITERATORS","COMPARATORS","EQUALS","ITERATION","RECURSION","ASYMPTOTICS","DISJOINT_SETS","ADTS","BSTS","B_TREES","RED_BLACK_TREES","HASHING","HEAPS","TREE_TRAVERSALS","GRAPH_TRAVERSALS","GRAPH_REPRESENTATIONS","SHORTEST_PATHS","MSTS","TOPOLOGICAL_SORT","TRIES","K_D_TREES","SORTING","COMPARISON_SORTS","RADIX_SORTS","REDUCTIONS","GAME_TREES","REGEX","BITS","PROJECT_2048","PERCOLATION"],"note":"Problems from any topic in the course are included. That classification is this site’s, not a staff recommendation."},"noPicks":"Course staff haven’t named practice questions here yet, so nothing is marked recommended.","timed":{"pool":"source","lengths":[{"min":50,"count":3}],"balanced":false,"intro":"Each exam draws problems from the whole course at random."},"exams":[{"exam":"61b-sp26-final"},{"exam":"61b-fa25-final"},{"exam":"61b-sp25-final"},{"exam":"61b-fa24-final"},{"exam":"61b-sp24-final"},{"exam":"61b-fa23-final"},{"exam":"61b-sp23-final"},{"exam":"61b-fa22-final","note":"The solution PDF is scanned. Diagram questions are described in text; the struck A* question is omitted."},{"exam":"61b-sp21-final"},{"exam":"61b-fa20-final"},{"exam":"61b-sp19-final"},{"exam":"61b-sp18-final"},{"exam":"61b-sp17-final"},{"exam":"61b-sp16-final"},{"exam":"61b-sp15-final"},{"exam":"61b-sp26-mt2","note":"This site asks 5.3–5.5 as True/False only; the counterexamples are in the answer notes."},{"exam":"61b-fa25-mt2"},{"exam":"61b-sp25-mt2","note":"This site asks the LLRB table (2a) as three questions, the hashing parts (5) for the verdict only, and the asymptotics sets (4) without the exam’s Decline option."},{"exam":"61b-fa24-mt2","note":"This site asks the drawn answers (the pairs in 3b, the LLRB in 4a) as multiple choice, and 3e as which listed hash lists loop forever."},{"exam":"61b-sp24-mt2","note":"Staff removed 1(k) after grading, so it’s left out. This site asks the write-in Θ answers in 2(a)–(d) as multiple choice."},{"exam":"61b-fa23-mt2","note":"This site asks the LLRB operation table (2b) one operation at a time, and the tables in 4 as two blanks each (the numbers, then their indices)."},{"exam":"61b-sp23-mt2","note":"This exam’s point values are written ×100. This site asks Q6 Part 1 for the classification only; the reasons and colliding words are in the answer notes."},{"exam":"61b-fa22-mt2","note":"This exam’s points total 4000. This site asks the hash table and 2-3 tree drawings (3, 4a) as fill-in questions, and the design question (8) as multiple choice with the method descriptions in the answer note."},{"exam":"61b-sp21-mt2","note":"This exam’s points total 1920. Pictures are written as text, and the free-form setIterator (6) has blanks following the solution’s structure."},{"exam":"61b-fa20-mt2","note":"This exam’s points total 960. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Pictures are written as text, and compress (5) and window (8c) have blanks following the solution’s structure."},{"exam":"61b-sp19-mt2","note":"This exam’s points total 480. Drawn trees are written as value(left, right); drawn answers are multiple choice or fill-in. In 10(a), g2’s loop as printed never ends, so this site accepts that as well as the staff answer."},{"exam":"61b-sp18-mt2","note":"This exam’s points total 240. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers and the free-response algorithm (9) are multiple choice or fill-in."},{"exam":"61b-sp17-mt2","note":"This exam’s points total 120. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers and the free-response algorithm (8d) are multiple choice or fill-in; 7(e), graded on the explanation alone, is left out."},{"exam":"61b-sp16-mt2","note":"This exam’s points total 60. The course’s topic index doesn’t cover it, so its topic tags are this site’s. Drawn answers are fill-in or multiple choice; Q7, drawn with pictorial symbols, is left out."},{"exam":"61b-sp15-mt2","note":"The course’s topic index doesn’t cover this exam, so its topic tags are this site’s. Drawn answers are fill-in or multiple choice, and the short-answer and design questions (2c, 4a, 6, 7, 10) are multiple choice with the staff’s reasoning in the answer notes."},{"exam":"61b-fa25-mt1"},{"exam":"61b-sp25-mt1","note":"The printed staff key for 2(a) reads index j − 1 starting from j = 0, which would go out of bounds; this site accepts the corrected loop."},{"exam":"61b-fa24-mt1","note":"The staff key for 1(a) line 3 reads “spawn FootballPlayer”, but the code prints “spawn Footballer”; this site accepts both."},{"exam":"61b-sp24-mt1"},{"exam":"61b-fa23-mt1","note":"Staff note that Q2 mixes overloading and overriding, which more recent semesters treat as out of scope."},{"exam":"61b-sp23-mt1","note":"This exam’s points total 4800."},{"exam":"61b-fa22-mt1","note":"This exam’s points total 2400. The box-and-pointer diagram (1a) is asked as questions about the final state."},{"exam":"61b-sp21-mt1","note":"This exam’s points total 1280. Written explanations are asked as multiple choice, and 6(d) (0 points) is left out."},{"exam":"61b-fa20-mt1","note":"Coding answers follow the staff solution’s structure. Testing prompts in Q6 are adapted to multiple choice; the administrative Q1 is left out."},{"exam":"61b-sp19-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp18-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp17-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp16-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."},{"exam":"61b-sp15-mt1","note":"All scored problems are represented. Coding answers follow the staff solution’s structure; some diagrams and written responses are adapted to checkable questions. See the original PDF for the exact exam format."}]}],"timed":{},"defaultCollection":"midterm2","legacyOrder":[],"version":"af4db21893"}