{"question": "Add a method isFull() to /******************************************************************************\n * Compilation: javac FixedCapacityStackOfStrings.java\n * Execution: java FixedCapacityStackOfStrings\n * Dependencies: StdIn.java StdOut.java\n *\n * Stack of strings implementation with a fixed-size array.\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java FixedCapacityStackOfStrings 5 < tobe.txt\n * to be not that or be\n *\n * Remark: bare-bones implementation. Does not do repeated\n * doubling or null out empty array entries to avoid loitering.\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class FixedCapacityStackOfStrings implements Iterable {\n private String[] a; // holds the items\n private int n; // number of items in stack\n\n // create an empty stack with given capacity\n public FixedCapacityStackOfStrings(int capacity) {\n a = new String[capacity];\n n = 0;\n }\n\n public boolean isEmpty() {\n return n == 0;\n }\n\n public boolean isFull() {\n return n == a.length;\n }\n\n public void push(String item) {\n a[n++] = item;\n }\n\n public String pop() {\n return a[--n];\n }\n\n public String peek() {\n return a[n-1];\n }\n\n public Iterator iterator() {\n return new ReverseArrayIterator();\n }\n\n // an array iterator, in reverse order\n public class ReverseArrayIterator implements Iterator {\n private int i = n-1;\n\n public boolean hasNext() {\n return i >= 0;\n }\n\n public String next() {\n if (!hasNext()) throw new NoSuchElementException();\n return a[i--];\n }\n }\n\n\n public static void main(String[] args) {\n int max = Integer.parseInt(args[0]);\n FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) stack.push(item);\n else if (stack.isEmpty()) StdOut.println(\"BAD INPUT\");\n else StdOut.print(stack.pop() + \" \");\n }\n StdOut.println();\n\n // print what's left on the stack\n StdOut.print(\"Left on stack: \");\n for (String s : stack) {\n StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}", "answer": "/******************************************************************************\n * Compilation: javac FixedCapacityStackOfStrings.java\n * Execution: java FixedCapacityStackOfStrings\n * Dependencies: StdIn.java StdOut.java\n *\n * Stack of strings implementation with a fixed-size array.\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java FixedCapacityStackOfStrings 5 < tobe.txt\n * to be not that or be\n *\n * Remark: bare-bones implementation. Does not do repeated\n * doubling or null out empty array entries to avoid loitering.\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class FixedCapacityStackOfStrings implements Iterable {\n private String[] a; // holds the items\n private int n; // number of items in stack\n\n // create an empty stack with given capacity\n public FixedCapacityStackOfStrings(int capacity) {\n a = new String[capacity];\n n = 0;\n }\n\n public boolean isEmpty() {\n return n == 0;\n }\n\n public boolean isFull() {\n return n == a.length;\n }\n\n public void push(String item) {\n a[n++] = item;\n }\n\n public String pop() {\n return a[--n];\n }\n\n public String peek() {\n return a[n-1];\n }\n\n public Iterator iterator() {\n return new ReverseArrayIterator();\n }\n\n // an array iterator, in reverse order\n public class ReverseArrayIterator implements Iterator {\n private int i = n-1;\n\n public boolean hasNext() {\n return i >= 0;\n }\n\n public String next() {\n if (!hasNext()) throw new NoSuchElementException();\n return a[i--];\n }\n }\n\n\n public static void main(String[] args) {\n int max = Integer.parseInt(args[0]);\n FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) stack.push(item);\n else if (stack.isEmpty()) StdOut.println(\"BAD INPUT\");\n else StdOut.print(stack.pop() + \" \");\n }\n StdOut.println();\n\n // print what's left on the stack\n StdOut.print(\"Left on stack: \");\n for (String s : stack) {\n StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}\n", "support_files": [], "metadata": {"number": "1.3.1", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/FixedCapacityStackOfStrings.java", "params": ["5 < tobe.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Write a stack client Parentheses.java that reads in sequence of left and right parentheses, braces, and brackets from standard input and uses a stack to determine whether the sequence is properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]). ", "answer": "/******************************************************************************\n * Compilation: javac Parentheses.java\n * Execution: java Parentheses\n * Dependencies: In.java Stack.java\n *\n * Reads in a text file and checks to see if the parentheses are balanced.\n *\n * % java Parentheses\n * [()]{}{[()()]()}\n * true\n *\n * % java Parentheses\n * [(])\n * false\n *\n ******************************************************************************/\n\npublic class Parentheses {\n private static final char LEFT_PAREN = '(';\n private static final char RIGHT_PAREN = ')';\n private static final char LEFT_BRACE = '{';\n private static final char RIGHT_BRACE = '}';\n private static final char LEFT_BRACKET = '[';\n private static final char RIGHT_BRACKET = ']';\n\n public static boolean isBalanced(String s) {\n Stack stack = new Stack();\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN);\n if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE);\n if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);\n\n if (s.charAt(i) == RIGHT_PAREN) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_PAREN) return false;\n }\n\n else if (s.charAt(i) == RIGHT_BRACE) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_BRACE) return false;\n }\n\n else if (s.charAt(i) == RIGHT_BRACKET) {\n if (stack.isEmpty()) return false;\n if (stack.pop() != LEFT_BRACKET) return false;\n }\n }\n return stack.isEmpty();\n }\n\n\n public static void main(String[] args) {\n In in = new In();\n String s = in.readAll().trim();\n StdOut.println(isBalanced(s));\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.4", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Parentheses.java", "params": ["<<< \"[(])\"", "<<< \"[()]{}{[()()]()}\""], "dependencies": ["In.java", "Stack.java"]}} {"question": "Add a method peek to '/******************************************************************************\n * Compilation: javac Stack.java\n * Execution: java Stack < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt\n *\n * A generic stack, implemented using a singly linked list.\n * Each stack element is of type Item.\n *\n * This version uses a static nested class Node (to save 8 bytes per\n * Node), whereas the version in the textbook uses a non-static nested\n * class (for simplicity).\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java Stack < tobe.txt\n * to be not that or be (2 left on stack)\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n/**\n * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.\n * It supports the usual push and pop operations, along with methods\n * for peeking at the top item, testing if the stack is empty, and iterating through\n * the items in LIFO order.\n *

\n * This implementation uses a singly linked list with a static nested class for\n * linked-list nodes. See {@link LinkedStack} for the version from the\n * textbook that uses a non-static nested class.\n * See {@link ResizingArrayStack} for a version that uses a resizing array.\n * The push, pop, peek, size, and is-empty\n * operations all take constant time in the worst case.\n *

\n * For additional documentation,\n * see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n *\n * @param the generic type each item in this stack\n */\npublic class Stack implements Iterable {\n private Node first; // top of stack\n private int n; // size of the stack\n\n // helper linked list class\n private static class Node {\n private Item item;\n private Node next;\n }\n\n /**\n * Initializes an empty stack.\n */\n public Stack() {\n first = null;\n n = 0;\n }\n\n /**\n * Returns true if this stack is empty.\n *\n * @return true if this stack is empty; false otherwise\n */\n public boolean isEmpty() {\n return first == null;\n }\n\n /**\n * Returns the number of items in this stack.\n *\n * @return the number of items in this stack\n */\n public int size() {\n return n;\n }\n\n /**\n * Adds the item to this stack.\n *\n * @param item the item to add\n */\n public void push(Item item) {\n Node oldfirst = first;\n first = new Node();\n first.item = item;\n first.next = oldfirst;\n n++;\n }\n\n /**\n * Removes and returns the item most recently added to this stack.\n *\n * @return the item most recently added\n * @throws NoSuchElementException if this stack is empty\n */\n public Item pop() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n Item item = first.item; // save item to return\n first = first.next; // delete first node\n n--;\n return item; // return the saved item\n }\n\n\n /**\n * Returns (but does not remove) the item most recently added to this stack.\n *\n * @return the item most recently added to this stack\n * @throws NoSuchElementException if this stack is empty\n */\n public Item peek() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n return first.item;\n }\n\n /**\n * Returns a string representation of this stack.\n *\n * @return the sequence of items in this stack in LIFO order, separated by spaces\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n for (Item item : this) {\n s.append(item);\n s.append(' ');\n }\n return s.toString();\n }\n\n\n /**\n * Returns an iterator to this stack that iterates through the items in LIFO order.\n *\n * @return an iterator to this stack that iterates through the items in LIFO order\n */\n public Iterator iterator() {\n return new LinkedIterator(first);\n }\n\n // the iterator\n private class LinkedIterator implements Iterator {\n private Node current;\n\n public LinkedIterator(Node first) {\n current = first;\n }\n\n // is there a next item?\n public boolean hasNext() {\n return current != null;\n }\n\n // returns the next item\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = current.item;\n current = current.next;\n return item;\n }\n }\n\n\n /**\n * Unit tests the {@code Stack} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\"))\n stack.push(item);\n else if (!stack.isEmpty())\n StdOut.print(stack.pop() + \" \");\n }\n StdOut.println(\"(\" + stack.size() + \" left on stack)\");\n }\n}\n\n' that returns the most recently inserted item on the stack (without popping it). ", "answer": "/******************************************************************************\n * Compilation: javac Stack.java\n * Execution: java Stack < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt\n *\n * A generic stack, implemented using a singly linked list.\n * Each stack element is of type Item.\n *\n * This version uses a static nested class Node (to save 8 bytes per\n * Node), whereas the version in the textbook uses a non-static nested\n * class (for simplicity).\n *\n * % more tobe.txt\n * to be or not to - be - - that - - - is\n *\n * % java Stack < tobe.txt\n * to be not that or be (2 left on stack)\n *\n ******************************************************************************/\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n/**\n * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.\n * It supports the usual push and pop operations, along with methods\n * for peeking at the top item, testing if the stack is empty, and iterating through\n * the items in LIFO order.\n *

\n * This implementation uses a singly linked list with a static nested class for\n * linked-list nodes. See {@link LinkedStack} for the version from the\n * textbook that uses a non-static nested class.\n * See {@link ResizingArrayStack} for a version that uses a resizing array.\n * The push, pop, peek, size, and is-empty\n * operations all take constant time in the worst case.\n *

\n * For additional documentation,\n * see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n *\n * @param the generic type each item in this stack\n */\npublic class Stack implements Iterable {\n private Node first; // top of stack\n private int n; // size of the stack\n\n // helper linked list class\n private static class Node {\n private Item item;\n private Node next;\n }\n\n /**\n * Initializes an empty stack.\n */\n public Stack() {\n first = null;\n n = 0;\n }\n\n /**\n * Returns true if this stack is empty.\n *\n * @return true if this stack is empty; false otherwise\n */\n public boolean isEmpty() {\n return first == null;\n }\n\n /**\n * Returns the number of items in this stack.\n *\n * @return the number of items in this stack\n */\n public int size() {\n return n;\n }\n\n /**\n * Adds the item to this stack.\n *\n * @param item the item to add\n */\n public void push(Item item) {\n Node oldfirst = first;\n first = new Node();\n first.item = item;\n first.next = oldfirst;\n n++;\n }\n\n /**\n * Removes and returns the item most recently added to this stack.\n *\n * @return the item most recently added\n * @throws NoSuchElementException if this stack is empty\n */\n public Item pop() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n Item item = first.item; // save item to return\n first = first.next; // delete first node\n n--;\n return item; // return the saved item\n }\n\n\n /**\n * Returns (but does not remove) the item most recently added to this stack.\n *\n * @return the item most recently added to this stack\n * @throws NoSuchElementException if this stack is empty\n */\n public Item peek() {\n if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n return first.item;\n }\n\n /**\n * Returns a string representation of this stack.\n *\n * @return the sequence of items in this stack in LIFO order, separated by spaces\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n for (Item item : this) {\n s.append(item);\n s.append(' ');\n }\n return s.toString();\n }\n\n\n /**\n * Returns an iterator to this stack that iterates through the items in LIFO order.\n *\n * @return an iterator to this stack that iterates through the items in LIFO order\n */\n public Iterator iterator() {\n return new LinkedIterator(first);\n }\n\n // the iterator\n private class LinkedIterator implements Iterator {\n private Node current;\n\n public LinkedIterator(Node first) {\n current = first;\n }\n\n // is there a next item?\n public boolean hasNext() {\n return current != null;\n }\n\n // returns the next item\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = current.item;\n current = current.next;\n return item;\n }\n }\n\n\n /**\n * Unit tests the {@code Stack} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\"))\n stack.push(item);\n else if (!stack.isEmpty())\n StdOut.print(stack.pop() + \" \");\n }\n StdOut.println(\"(\" + stack.size() + \" left on stack)\");\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Stack.java", "params": ["< tobe.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Write a filter Program InfixToPostfix.java that converts an arithmetic expression from infix to postfix. ", "answer": "/******************************************************************************\n * Compilation: javac InfixToPostfix.java\n * Execution: java InfixToPostFix\n * Dependencies: Stack.java StdIn.java StdOut.java\n *\n * Reads in a fully parenthesized infix expression from standard input\n * and prints an equivalent postfix expression to standard output.\n *\n * Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file.\n *\n * % java InfixToPostfix\n * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\n * [Ctrl-d]\n * 2 3 4 + 5 6 * * +\n *\n * % java InfixToPostfix\n * ( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )\n * 5 7 1 1 + * + 3 * 2 1 1 + * +\n *\n * % java InfixToPostfix | java EvaluatePostfix\n * ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\n * [Ctrl-d]\n * 212\n *\n ******************************************************************************/\n\npublic class InfixToPostfix {\n public static void main(String[] args) {\n Stack stack = new Stack();\n while (!StdIn.isEmpty()) {\n String s = StdIn.readString();\n if (s.equals(\"+\")) stack.push(s);\n else if (s.equals(\"*\")) stack.push(s);\n else if (s.equals(\")\")) StdOut.print(stack.pop() + \" \");\n else if (s.equals(\"(\")) StdOut.print(\"\");\n else StdOut.print(s + \" \");\n }\n StdOut.println();\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.10", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/InfixToPostfix.java", "params": ["< stack = new Stack();\n\n while (!StdIn.isEmpty()) {\n String s = StdIn.readString();\n if (s.equals(\"+\")) stack.push(stack.pop() + stack.pop());\n else if (s.equals(\"*\")) stack.push(stack.pop() * stack.pop());\n else stack.push(Integer.parseInt(s));\n }\n StdOut.println(stack.pop());\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.11", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/EvaluatePostfix.java", "params": ["<enqueue and dequeue\n * operations, along with methods for peeking at the first item,\n * testing if the queue is empty, and iterating through\n * the items in FIFO order.\n *

\n * This implementation uses a resizing array, which double the underlying array\n * when it is full and halves the underlying array when it is one-quarter full.\n * The enqueue and dequeue operations take constant amortized time.\n * The size, peek, and is-empty operations takes\n * constant time in the worst case.\n *

\n * For additional documentation, see Section 1.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class ResizingArrayQueue implements Iterable {\n // initial capacity of underlying resizing array\n private static final int INIT_CAPACITY = 8;\n\n private Item[] q; // queue elements\n private int n; // number of elements on queue\n private int first; // index of first element of queue\n private int last; // index of next available slot\n\n\n /**\n * Initializes an empty queue.\n */\n public ResizingArrayQueue() {\n q = (Item[]) new Object[INIT_CAPACITY];\n n = 0;\n first = 0;\n last = 0;\n }\n\n /**\n * Is this queue empty?\n * @return true if this queue is empty; false otherwise\n */\n public boolean isEmpty() {\n return n == 0;\n }\n\n /**\n * Returns the number of items in this queue.\n * @return the number of items in this queue\n */\n public int size() {\n return n;\n }\n\n // resize the underlying array\n private void resize(int capacity) {\n assert capacity >= n;\n Item[] copy = (Item[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n copy[i] = q[(first + i) % q.length];\n }\n q = copy;\n first = 0;\n last = n;\n }\n\n /**\n * Adds the item to this queue.\n * @param item the item to add\n */\n public void enqueue(Item item) {\n // double size of array if necessary and recopy to front of array\n if (n == q.length) resize(2*q.length); // double size of array if necessary\n q[last++] = item; // add item\n if (last == q.length) last = 0; // wrap-around\n n++;\n }\n\n /**\n * Removes and returns the item on this queue that was least recently added.\n * @return the item on this queue that was least recently added\n * @throws java.util.NoSuchElementException if this queue is empty\n */\n public Item dequeue() {\n if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n Item item = q[first];\n q[first] = null; // to avoid loitering\n n--;\n first++;\n if (first == q.length) first = 0; // wrap-around\n // shrink size of array if necessary\n if (n > 0 && n == q.length/4) resize(q.length/2);\n return item;\n }\n\n /**\n * Returns the item least recently added to this queue.\n * @return the item least recently added to this queue\n * @throws java.util.NoSuchElementException if this queue is empty\n */\n public Item peek() {\n if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n return q[first];\n }\n\n\n /**\n * Returns an iterator that iterates over the items in this queue in FIFO order.\n * @return an iterator that iterates over the items in this queue in FIFO order\n */\n public Iterator iterator() {\n return new ArrayIterator();\n }\n\n // an array iterator, from first to last-1\n private class ArrayIterator implements Iterator {\n private int i = 0;\n\n public boolean hasNext() {\n return i < n;\n }\n\n public Item next() {\n if (!hasNext()) throw new NoSuchElementException();\n Item item = q[(i + first) % q.length];\n i++;\n return item;\n }\n }\n\n /**\n * Unit tests the {@code ResizingArrayQueue} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n ResizingArrayQueue queue = new ResizingArrayQueue();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) queue.enqueue(item);\n else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + \" \");\n }\n StdOut.println(\"(\" + queue.size() + \" left on queue)\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "1.3.14", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java", "params": ["< tobe.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange themselves in a circle (at positions numbered from 0 to N-1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus.java that takes M and N from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle).\n\n % java Josephus 2 7\n 1 3 5 0 4 2 6\n", "answer": "/******************************************************************************\n * Compilation: javac Josephus.java\n * Execution: java Josephus m n\n * Dependencies: Queue.java\n *\n * Solves the Josephus problem.\n *\n * % java Josephus 2 7\n * 1 3 5 0 4 2 6\n *\n ******************************************************************************/\n\npublic class Josephus {\n public static void main(String[] args) {\n int m = Integer.parseInt(args[0]);\n int n = Integer.parseInt(args[1]);\n\n // initialize the queue\n Queue queue = new Queue();\n for (int i = 0; i < n; i++)\n queue.enqueue(i);\n\n while (!queue.isEmpty()) {\n for (int i = 0; i < m-1; i++)\n queue.enqueue(queue.dequeue());\n StdOut.print(queue.dequeue() + \" \");\n }\n StdOut.println();\n }\n}\n\n", "support_files": [], "metadata": {"number": "1.3.37", "code_execution": true, "url": "https://algs4.cs.princeton.edu/13stacks/Josephus.java", "params": ["2 7"], "dependencies": ["Queue.java"]}} {"question": "Develop classes QuickUnionUF.java that implement quick-union.", "answer": "/******************************************************************************\n * Compilation: javac QuickUnionUF.java\n * Execution: java QuickUnionUF < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt\n * https://algs4.cs.princeton.edu/15uf/mediumUF.txt\n * https://algs4.cs.princeton.edu/15uf/largeUF.txt\n *\n * Quick-union algorithm.\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickUnionUF} class represents a union\u2013find data type\n * (also known as the disjoint-sets data type).\n * It supports the classic union and find operations,\n * along with a count operation that returns the total number\n * of sets.\n *

\n * The union\u2013find data type models a collection of sets containing\n * n elements, with each element in exactly one set.\n * The elements are named 0 through n\u20131.\n * Initially, there are n sets, with each element in its\n * own set. The canonical element of a set\n * (also known as the root, identifier,\n * leader, or set representative)\n * is one distinguished element in the set. Here is a summary of\n * the operations:\n *

    \n *
  • find(p) returns the canonical element\n * of the set containing p. The find operation\n * returns the same value for two elements if and only if\n * they are in the same set.\n *
  • union(p, q) merges the set\n * containing element p with the set containing\n * element q. That is, if p and q\n * are in different sets, replace these two sets\n * with a new set that is the union of the two.\n *
  • count() returns the number of sets.\n *
\n *

\n * The canonical element of a set can change only when the set\n * itself changes during a call to union—it cannot\n * change during a call to either find or count.\n *

\n * This implementation uses quick union.\n * The constructor takes Θ(n) time, where\n * n is the number of sites.\n * The union and find operations take\n * Θ(n) time in the worst case.\n * The count operation takes Θ(1) time.\n *

\n * For alternative implementations of the same API, see\n * {@link UF}, {@link QuickFindUF}, and {@link WeightedQuickUnionUF}.\n * For additional documentation,\n * see Section 1.5 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class QuickUnionUF {\n private int[] parent; // parent[i] = parent of i\n private int count; // number of components\n\n /**\n * Initializes an empty union-find data structure with\n * {@code n} elements {@code 0} through {@code n-1}.\n * Initially, each element is in its own set.\n *\n * @param n the number of elements\n * @throws IllegalArgumentException if {@code n < 0}\n */\n public QuickUnionUF(int n) {\n parent = new int[n];\n count = n;\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n\n /**\n * Returns the number of sets.\n *\n * @return the number of sets (between {@code 1} and {@code n})\n */\n public int count() {\n return count;\n }\n\n /**\n * Returns the canonical element of the set containing element {@code p}.\n *\n * @param p an element\n * @return the canonical element of the set containing {@code p}\n * @throws IllegalArgumentException unless {@code 0 <= p < n}\n */\n public int find(int p) {\n validate(p);\n while (p != parent[p])\n p = parent[p];\n return p;\n }\n\n // validate that p is a valid index\n private void validate(int p) {\n int n = parent.length;\n if (p < 0 || p >= n) {\n throw new IllegalArgumentException(\"index \" + p + \" is not between 0 and \" + (n-1));\n }\n }\n\n /**\n * Returns true if the two elements are in the same set.\n *\n * @param p one element\n * @param q the other element\n * @return {@code true} if {@code p} and {@code q} are in the same set;\n * {@code false} otherwise\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n * @deprecated Replace with two calls to {@link #find(int)}.\n */\n @Deprecated\n public boolean connected(int p, int q) {\n return find(p) == find(q);\n }\n\n /**\n * Merges the set containing element {@code p} with the set\n * containing element {@code q}.\n *\n * @param p one element\n * @param q the other element\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n */\n public void union(int p, int q) {\n int rootP = find(p);\n int rootQ = find(q);\n if (rootP == rootQ) return;\n parent[rootP] = rootQ;\n count--;\n }\n\n /**\n * Reads an integer {@code n} and a sequence of pairs of integers\n * (between {@code 0} and {@code n-1}) from standard input, where each integer\n * in the pair represents some element;\n * if the elements are in different sets, merge the two sets\n * and print the pair to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int n = StdIn.readInt();\n QuickUnionUF uf = new QuickUnionUF(n);\n while (!StdIn.isEmpty()) {\n int p = StdIn.readInt();\n int q = StdIn.readInt();\n if (uf.find(p) == uf.find(q)) continue;\n uf.union(p, q);\n StdOut.println(p + \" \" + q);\n }\n StdOut.println(uf.count() + \" components\");\n }\n\n\n}\n", "support_files": [], "metadata": {"number": "1.5.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/15uf/QuickUnionUF.java", "params": ["< tinyUF.txt", "< mediumUF.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Develop classes QuickFindUF.java that implement quick-find.", "answer": "/******************************************************************************\n * Compilation: javac QuickFindUF.java\n * Execution: java QuickFindUF < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt\n * https://algs4.cs.princeton.edu/15uf/mediumUF.txt\n * https://algs4.cs.princeton.edu/15uf/largeUF.txt\n *\n * Quick-find algorithm.\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickFindUF} class represents a union\u2013find data type\n * (also known as the disjoint-sets data type).\n * It supports the classic union and find operations,\n * along with a count operation that returns the total number\n * of sets.\n *

\n * The union\u2013find data type models a collection of sets containing\n * n elements, with each element in exactly one set.\n * The elements are named 0 through n\u20131.\n * Initially, there are n sets, with each element in its\n * own set. The canonical element of a set\n * (also known as the root, identifier,\n * leader, or set representative)\n * is one distinguished element in the set. Here is a summary of\n * the operations:\n *

    \n *
  • find(p) returns the canonical element\n * of the set containing p. The find operation\n * returns the same value for two elements if and only if\n * they are in the same set.\n *
  • union(p, q) merges the set\n * containing element p with the set containing\n * element q. That is, if p and q\n * are in different sets, replace these two sets\n * with a new set that is the union of the two.\n *
  • count() returns the number of sets.\n *
\n *

\n * The canonical element of a set can change only when the set\n * itself changes during a call to union—it cannot\n * change during a call to either find or count.\n *

\n * This implementation uses quick find.\n * The constructor takes Θ(n) time, where n\n * is the number of sites.\n * The find, connected, and count\n * operations take Θ(1) time; the union operation\n * takes Θ(n) time.\n *

\n * For alternative implementations of the same API, see\n * {@link UF}, {@link QuickUnionUF}, and {@link WeightedQuickUnionUF}.\n * For additional documentation, see\n * Section 1.5 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class QuickFindUF {\n private int[] id; // id[i] = component identifier of i\n private int count; // number of components\n\n /**\n * Initializes an empty union-find data structure with\n * {@code n} elements {@code 0} through {@code n-1}.\n * Initially, each element is in its own set.\n *\n * @param n the number of elements\n * @throws IllegalArgumentException if {@code n < 0}\n */\n public QuickFindUF(int n) {\n count = n;\n id = new int[n];\n for (int i = 0; i < n; i++)\n id[i] = i;\n }\n\n /**\n * Returns the number of sets.\n *\n * @return the number of sets (between {@code 1} and {@code n})\n */\n public int count() {\n return count;\n }\n\n /**\n * Returns the canonical element of the set containing element {@code p}.\n *\n * @param p an element\n * @return the canonical element of the set containing {@code p}\n * @throws IllegalArgumentException unless {@code 0 <= p < n}\n */\n public int find(int p) {\n validate(p);\n return id[p];\n }\n\n // validate that p is a valid index\n private void validate(int p) {\n int n = id.length;\n if (p < 0 || p >= n) {\n throw new IllegalArgumentException(\"index \" + p + \" is not between 0 and \" + (n-1));\n }\n }\n\n /**\n * Returns true if the two elements are in the same set.\n *\n * @param p one element\n * @param q the other element\n * @return {@code true} if {@code p} and {@code q} are in the same set;\n * {@code false} otherwise\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n * @deprecated Replace with two calls to {@link #find(int)}.\n */\n @Deprecated\n public boolean connected(int p, int q) {\n validate(p);\n validate(q);\n return id[p] == id[q];\n }\n\n /**\n * Merges the set containing element {@code p} with the set\n * containing element {@code q}.\n *\n * @param p one element\n * @param q the other element\n * @throws IllegalArgumentException unless\n * both {@code 0 <= p < n} and {@code 0 <= q < n}\n */\n public void union(int p, int q) {\n validate(p);\n validate(q);\n int pID = id[p]; // needed for correctness\n int qID = id[q]; // to reduce the number of array accesses\n\n // p and q are already in the same component\n if (pID == qID) return;\n\n for (int i = 0; i < id.length; i++)\n if (id[i] == pID) id[i] = qID;\n count--;\n }\n\n /**\n * Reads an integer {@code n} and a sequence of pairs of integers\n * (between {@code 0} and {@code n-1}) from standard input, where each integer\n * in the pair represents some element;\n * if the elements are in different sets, merge the two sets\n * and print the pair to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int n = StdIn.readInt();\n QuickFindUF uf = new QuickFindUF(n);\n while (!StdIn.isEmpty()) {\n int p = StdIn.readInt();\n int q = StdIn.readInt();\n if (uf.find(p) == uf.find(q)) continue;\n uf.union(p, q);\n StdOut.println(p + \" \" + q);\n }\n StdOut.println(uf.count() + \" components\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "1.5.7", "code_execution": true, "url": "https://algs4.cs.princeton.edu/15uf/QuickFindUF.java", "params": ["< tinyUF.txt", "< mediumUF.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Transaction sort test client. Write a class SortTransactions.java that consists of a static method main() that reads a sequence of transactions from standard\ninput, sorts them, and prints the result on standard output.", "answer": "/******************************************************************************\n * Compilation: javac SortTransactions.java\n * Execution: java SortTransactions < input.txt\n * Dependencies: StdOut.java\n * Data file: https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt\n *\n * % java SortTransactions < transactions.txt\n * Turing 1/11/2002 66.10\n * Knuth 6/14/1999 288.34\n * Turing 6/17/1990 644.08\n * Dijkstra 9/10/2000 708.95\n * Dijkstra 11/18/1995 837.42\n * Hoare 8/12/2003 1025.70\n * Bellman 10/26/2007 1358.62\n * Knuth 7/25/2008 1564.55\n * Turing 2/11/1991 2156.86\n * Tarjan 10/13/1993 2520.97\n * Dijkstra 8/22/2007 2678.40\n * Hoare 5/10/1993 3229.27\n * Knuth 11/11/2008 3284.33\n * Turing 10/12/1993 3532.36\n * Hoare 2/10/2005 4050.20\n * Tarjan 3/26/2002 4121.85\n * Hoare 8/18/1992 4381.21\n * Tarjan 1/11/1999 4409.74\n * Tarjan 2/12/1994 4732.35\n * Thompson 2/27/2000 4747.08\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\npublic class SortTransactions {\n public static Transaction[] readTransactions() {\n Queue queue = new Queue();\n while (StdIn.hasNextLine()) {\n String line = StdIn.readLine();\n Transaction transaction = new Transaction(line);\n queue.enqueue(transaction);\n }\n\n int n = queue.size();\n Transaction[] transactions = new Transaction[n];\n for (int i = 0; i < n; i++)\n transactions[i] = queue.dequeue();\n\n return transactions;\n }\n\n public static void main(String[] args) {\n Transaction[] transactions = readTransactions();\n Arrays.sort(transactions);\n for (int i = 0; i < transactions.length; i++)\n StdOut.println(transactions[i]);\n }\n}\n", "support_files": [], "metadata": {"number": "2.1.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/SortTransactions.java", "params": ["< tinyBatch.txt"], "dependencies": ["StdOut.java"]}} {"question": "Insertion sort with sentinel. Develop an implementation InsertionX.java of insertion sort that eliminates the j > 0 test in the inner loop by first putting the smallest item into position", "answer": "/******************************************************************************\n * Compilation: javac InsertionX.java\n * Execution: java InsertionX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt\n * https://algs4.cs.princeton.edu/21elementary/words3.txt\n *\n * Sorts a sequence of strings from standard input using an optimized\n * version of insertion sort that uses half exchanges instead of\n * full exchanges to reduce data movement..\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java InsertionX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java InsertionX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n/**\n * The {@code InsertionX} class provides static methods for sorting\n * an array using an optimized version of insertion sort (with half exchanges\n * and a sentinel).\n *

\n * In the worst case, this implementation makes ~ 1/2 n2\n * compares to sort an array of length n.\n * So, it is not suitable for sorting large arrays\n * (unless the number of inversions is small).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(1) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class InsertionX {\n\n // This class should not be instantiated.\n private InsertionX() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n int n = a.length;\n\n // put smallest element in position to serve as sentinel\n int exchanges = 0;\n for (int i = n-1; i > 0; i--) {\n if (less(a[i], a[i-1])) {\n exch(a, i, i-1);\n exchanges++;\n }\n }\n if (exchanges == 0) return;\n\n\n // insertion sort with half-exchanges\n for (int i = 2; i < n; i++) {\n Comparable v = a[i];\n int j = i;\n while (less(v, a[j-1])) {\n a[j] = a[j-1];\n j--;\n }\n a[j] = v;\n }\n\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; insertion sorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n InsertionX.sort(a);\n show(a);\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.1.23", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java", "params": ["< words3.txt", "< tiny.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Insertion sort without exchanges. Develop an implementation InsertionX.java of insertion sort that moves larger items to the right one position rather\nthan doing full exchanges.", "answer": "/******************************************************************************\n * Compilation: javac InsertionX.java\n * Execution: java InsertionX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt\n * https://algs4.cs.princeton.edu/21elementary/words3.txt\n *\n * Sorts a sequence of strings from standard input using an optimized\n * version of insertion sort that uses half exchanges instead of\n * full exchanges to reduce data movement..\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java InsertionX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java InsertionX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n/**\n * The {@code InsertionX} class provides static methods for sorting\n * an array using an optimized version of insertion sort (with half exchanges\n * and a sentinel).\n *

\n * In the worst case, this implementation makes ~ 1/2 n2\n * compares to sort an array of length n.\n * So, it is not suitable for sorting large arrays\n * (unless the number of inversions is small).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(1) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class InsertionX {\n\n // This class should not be instantiated.\n private InsertionX() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n int n = a.length;\n\n // put smallest element in position to serve as sentinel\n int exchanges = 0;\n for (int i = n-1; i > 0; i--) {\n if (less(a[i], a[i-1])) {\n exch(a, i, i-1);\n exchanges++;\n }\n }\n if (exchanges == 0) return;\n\n\n // insertion sort with half-exchanges\n for (int i = 2; i < n; i++) {\n Comparable v = a[i];\n int j = i;\n while (less(v, a[j-1])) {\n a[j] = a[j-1];\n j--;\n }\n a[j] = v;\n }\n\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; insertion sorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n InsertionX.sort(a);\n show(a);\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.1.24", "code_execution": true, "url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java", "params": ["< words3.txt", "< tiny.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Use of a static array like aux[] is inadvisable in library software because\nmultiple clients might use the class concurrently. Give an implementation of Merge.java that \ndoes not use a static array.", "answer": "/******************************************************************************\n * Compilation: javac Merge.java\n * Execution: java Merge < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java Merge < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java Merge < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\n/**\n * The {@code Merge} class provides static methods for sorting an\n * array using a top-down, recursive version of mergesort.\n *

\n * This implementation takes Θ(n log n) time\n * to sort any array of length n (assuming comparisons\n * take constant time). It makes between\n * ~ ½ n log2 n and\n * ~ 1 n log2 n compares.\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For an optimized version, see {@link MergeX}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Merge {\n\n // This class should not be instantiated.\n private Merge() { }\n\n // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\n // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays\n assert isSorted(a, lo, mid);\n assert isSorted(a, mid+1, hi);\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) a[k] = aux[j++];\n else a[k] = aux[i++];\n }\n\n // postcondition: a[lo .. hi] is sorted\n assert isSorted(a, lo, hi);\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, aux, lo, mid);\n sort(a, aux, mid + 1, hi);\n merge(a, aux, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = new Comparable[a.length];\n sort(a, aux, 0, a.length-1);\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting function.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n\n /***************************************************************************\n * Index mergesort.\n ***************************************************************************/\n // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = index[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) index[k] = aux[j++];\n else if (j > hi) index[k] = aux[i++];\n else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];\n else index[k] = aux[i++];\n }\n }\n\n /**\n * Returns a permutation that gives the elements in the array in ascending order.\n * @param a the array\n * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},\n * ..., {@code a[p[n-1]]} are in ascending order\n */\n public static int[] indexSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n for (int i = 0; i < n; i++)\n index[i] = i;\n\n int[] aux = new int[n];\n sort(a, index, aux, 0, n-1);\n return index;\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, index, aux, lo, mid);\n sort(a, index, aux, mid + 1, hi);\n merge(a, index, aux, lo, mid, hi);\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n Merge.sort(a);\n show(a);\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.9", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Improvements. Write a program MergeX.java that implements the three improvements to mergesort that are described in the text: add a cutoff from small subarrays, test whether the array is already in order, and avoid the copy by switching arguments in the recursive code", "answer": "/******************************************************************************\n * Compilation: javac MergeX.java\n * Execution: java MergeX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using an\n * optimized version of mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java MergeX < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java MergeX < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\nimport java.util.Comparator;\n\n/**\n * The {@code MergeX} class provides static methods for sorting an\n * array using an optimized version of mergesort.\n *

\n * In the worst case, this implementation takes\n * Θ(n log n) time to sort an array of\n * length n (assuming comparisons take constant time).\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class MergeX {\n private static final int CUTOFF = 7; // cutoff to insertion sort\n\n // This class should not be instantiated.\n private MergeX() { }\n\n private static void merge(Comparable[] src, Comparable[] dst, int lo, int mid, int hi) {\n\n // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays\n assert isSorted(src, lo, mid);\n assert isSorted(src, mid+1, hi);\n\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) dst[k] = src[j++];\n else if (j > hi) dst[k] = src[i++];\n else if (less(src[j], src[i])) dst[k] = src[j++]; // to ensure stability\n else dst[k] = src[i++];\n }\n\n // postcondition: dst[lo .. hi] is sorted subarray\n assert isSorted(dst, lo, hi);\n }\n\n private static void sort(Comparable[] src, Comparable[] dst, int lo, int hi) {\n // if (hi <= lo) return;\n if (hi <= lo + CUTOFF) {\n insertionSort(dst, lo, hi);\n return;\n }\n int mid = lo + (hi - lo) / 2;\n sort(dst, src, lo, mid);\n sort(dst, src, mid+1, hi);\n\n // if (!less(src[mid+1], src[mid])) {\n // for (int i = lo; i <= hi; i++) dst[i] = src[i];\n // return;\n // }\n\n // using System.arraycopy() is a bit faster than the above loop\n if (!less(src[mid+1], src[mid])) {\n System.arraycopy(src, lo, dst, lo, hi - lo + 1);\n return;\n }\n\n merge(src, dst, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = a.clone();\n sort(aux, a, 0, a.length-1);\n assert isSorted(a);\n }\n\n // sort from a[lo] to a[hi] using insertion sort\n private static void insertionSort(Comparable[] a, int lo, int hi) {\n for (int i = lo; i <= hi; i++)\n for (int j = i; j > lo && less(a[j], a[j-1]); j--)\n exch(a, j, j-1);\n }\n\n\n /*******************************************************************\n * Utility methods.\n *******************************************************************/\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n // is a[i] < a[j]?\n private static boolean less(Comparable a, Comparable b) {\n return a.compareTo(b) < 0;\n }\n\n // is a[i] < a[j]?\n private static boolean less(Object a, Object b, Comparator comparator) {\n return comparator.compare(a, b) < 0;\n }\n\n\n /*******************************************************************\n * Version that takes Comparator as argument.\n *******************************************************************/\n\n /**\n * Rearranges the array in ascending order, using the provided order.\n *\n * @param a the array to be sorted\n * @param comparator the comparator that defines the total order\n */\n public static void sort(Object[] a, Comparator comparator) {\n Object[] aux = a.clone();\n sort(aux, a, 0, a.length-1, comparator);\n assert isSorted(a, comparator);\n }\n\n private static void merge(Object[] src, Object[] dst, int lo, int mid, int hi, Comparator comparator) {\n\n // precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays\n assert isSorted(src, lo, mid, comparator);\n assert isSorted(src, mid+1, hi, comparator);\n\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) dst[k] = src[j++];\n else if (j > hi) dst[k] = src[i++];\n else if (less(src[j], src[i], comparator)) dst[k] = src[j++];\n else dst[k] = src[i++];\n }\n\n // postcondition: dst[lo .. hi] is sorted subarray\n assert isSorted(dst, lo, hi, comparator);\n }\n\n\n private static void sort(Object[] src, Object[] dst, int lo, int hi, Comparator comparator) {\n // if (hi <= lo) return;\n if (hi <= lo + CUTOFF) {\n insertionSort(dst, lo, hi, comparator);\n return;\n }\n int mid = lo + (hi - lo) / 2;\n sort(dst, src, lo, mid, comparator);\n sort(dst, src, mid+1, hi, comparator);\n\n // using System.arraycopy() is a bit faster than the above loop\n if (!less(src[mid+1], src[mid], comparator)) {\n System.arraycopy(src, lo, dst, lo, hi - lo + 1);\n return;\n }\n\n merge(src, dst, lo, mid, hi, comparator);\n }\n\n // sort from a[lo] to a[hi] using insertion sort\n private static void insertionSort(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo; i <= hi; i++)\n for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--)\n exch(a, j, j-1);\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n private static boolean isSorted(Object[] a, Comparator comparator) {\n return isSorted(a, 0, a.length - 1, comparator);\n }\n\n private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1], comparator)) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Object[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them\n * (using an optimized version of mergesort);\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n MergeX.sort(a);\n show(a);\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.11", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/MergeX.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Inversions. Develop and implement a linearithmic algorithm Inversions.java for computing the number of inversions in a given array (the number of exchanges that would be performed by insertion sort for that array—see Section 2.1). This quantity is related to the Kendall tau distance", "answer": "/******************************************************************************\n * Compilation: javac Inversions.java\n * Execution: java Inversions < input.txt\n * Dependencies: StdIn.java StdOut.java\n *\n * Read array of n integers and count number of inversions in n log n time.\n *\n ******************************************************************************/\n\n/**\n * The {@code Inversions} class provides static methods to count the\n * number of inversions in either an array of integers or comparables.\n * An inversion in an array {@code a[]} is a pair of indicies {@code i} and\n * {@code j} such that {@code i < j} and {@code a[i] > a[j]}.\n *

\n * This implementation uses a generalization of mergesort. The count\n * operation takes Θ(n log n) time to count the\n * number of inversions in any array of length n (assuming\n * comparisons take constant time).\n *

\n * For additional documentation, see\n * Section 2.2\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Inversions {\n\n // do not instantiate\n private Inversions() { }\n\n // merge and count\n private static long merge(int[] a, int[] aux, int lo, int mid, int hi) {\n long inversions = 0;\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (aux[j] < aux[i]) { a[k] = aux[j++]; inversions += (mid - i + 1); }\n else a[k] = aux[i++];\n }\n return inversions;\n }\n\n // return the number of inversions in the subarray b[lo..hi]\n // side effect b[lo..hi] is rearranged in ascending order\n private static long count(int[] a, int[] b, int[] aux, int lo, int hi) {\n long inversions = 0;\n if (hi <= lo) return 0;\n int mid = lo + (hi - lo) / 2;\n inversions += count(a, b, aux, lo, mid);\n inversions += count(a, b, aux, mid+1, hi);\n inversions += merge(b, aux, lo, mid, hi);\n assert inversions == brute(a, lo, hi);\n return inversions;\n }\n\n\n /**\n * Returns the number of inversions in the integer array.\n * The argument array is not modified.\n * @param a the array\n * @return the number of inversions in the array. An inversion is a pair of\n * indicies {@code i} and {@code j} such that {@code i < j}\n * and {@code a[i] > a[j]}.\n */\n public static long count(int[] a) {\n int[] b = new int[a.length];\n int[] aux = new int[a.length];\n for (int i = 0; i < a.length; i++)\n b[i] = a[i];\n long inversions = count(a, b, aux, 0, a.length - 1);\n return inversions;\n }\n\n\n\n // merge and count (Comparable version)\n private static > long merge(Key[] a, Key[] aux, int lo, int mid, int hi) {\n long inversions = 0;\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) { a[k] = aux[j++]; inversions += (mid - i + 1); }\n else a[k] = aux[i++];\n }\n return inversions;\n }\n\n // return the number of inversions in the subarray b[lo..hi]\n // side effect b[lo..hi] is rearranged in ascending order\n private static > long count(Key[] a, Key[] b, Key[] aux, int lo, int hi) {\n long inversions = 0;\n if (hi <= lo) return 0;\n int mid = lo + (hi - lo) / 2;\n inversions += count(a, b, aux, lo, mid);\n inversions += count(a, b, aux, mid+1, hi);\n inversions += merge(b, aux, lo, mid, hi);\n assert inversions == brute(a, lo, hi);\n return inversions;\n }\n\n\n /**\n * Returns the number of inversions in the comparable array.\n * The argument array is not modified.\n * @param a the array\n * @param the inferred type of the elements in the array\n * @return the number of inversions in the array. An inversion is a pair of\n * indicies {@code i} and {@code j} such that {@code i < j}\n * and {@code a[i].compareTo(a[j]) > 0}.\n */\n public static > long count(Key[] a) {\n Key[] b = a.clone();\n Key[] aux = a.clone();\n long inversions = count(a, b, aux, 0, a.length - 1);\n return inversions;\n }\n\n\n // is v < w ?\n private static > boolean less(Key v, Key w) {\n return (v.compareTo(w) < 0);\n }\n\n // count number of inversions in a[lo..hi] via brute force (for debugging only)\n private static > long brute(Key[] a, int lo, int hi) {\n long inversions = 0;\n for (int i = lo; i <= hi; i++)\n for (int j = i + 1; j <= hi; j++)\n if (less(a[j], a[i])) inversions++;\n return inversions;\n }\n\n // count number of inversions in a[lo..hi] via brute force (for debugging only)\n private static long brute(int[] a, int lo, int hi) {\n long inversions = 0;\n for (int i = lo; i <= hi; i++)\n for (int j = i + 1; j <= hi; j++)\n if (a[j] < a[i]) inversions++;\n return inversions;\n }\n\n /**\n * Reads a sequence of integers from standard input and\n * prints the number of inversions to standard output.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n int[] a = StdIn.readAllInts();\n int n = a.length;\n Integer[] b = new Integer[n];\n for (int i = 0; i < n; i++)\n b[i] = a[i];\n StdOut.println(Inversions.count(a));\n StdOut.println(Inversions.count(b));\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.19", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Inversions.java", "params": ["< 1Kints.txt", "< 2Kints.txt", "< 4Kints.txt", "< 8Kints.txt", "< 16Kints.txt", "< 32Kints.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Index sort. Develop a version of Merge.java that does not rearrange the array, but returns an int[] perm such that perm[i] is the index of the ith smallest entry in the array.", "answer": "/******************************************************************************\n * Compilation: javac Merge.java\n * Execution: java Merge < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt\n * https://algs4.cs.princeton.edu/22mergesort/words3.txt\n *\n * Sorts a sequence of strings from standard input using mergesort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java Merge < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java Merge < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\n/**\n * The {@code Merge} class provides static methods for sorting an\n * array using a top-down, recursive version of mergesort.\n *

\n * This implementation takes Θ(n log n) time\n * to sort any array of length n (assuming comparisons\n * take constant time). It makes between\n * ~ ½ n log2 n and\n * ~ 1 n log2 n compares.\n *

\n * This sorting algorithm is stable.\n * It uses Θ(n) extra memory (not including the input array).\n *

\n * For additional documentation, see\n * Section 2.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For an optimized version, see {@link MergeX}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Merge {\n\n // This class should not be instantiated.\n private Merge() { }\n\n // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\n // precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays\n assert isSorted(a, lo, mid);\n assert isSorted(a, mid+1, hi);\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = a[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) a[k] = aux[j++];\n else if (j > hi) a[k] = aux[i++];\n else if (less(aux[j], aux[i])) a[k] = aux[j++];\n else a[k] = aux[i++];\n }\n\n // postcondition: a[lo .. hi] is sorted\n assert isSorted(a, lo, hi);\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, aux, lo, mid);\n sort(a, aux, mid + 1, hi);\n merge(a, aux, lo, mid, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n Comparable[] aux = new Comparable[a.length];\n sort(a, aux, 0, a.length-1);\n assert isSorted(a);\n }\n\n\n /***************************************************************************\n * Helper sorting function.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length - 1);\n }\n\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i <= hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n\n /***************************************************************************\n * Index mergesort.\n ***************************************************************************/\n // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]\n private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {\n\n // copy to aux[]\n for (int k = lo; k <= hi; k++) {\n aux[k] = index[k];\n }\n\n // merge back to a[]\n int i = lo, j = mid+1;\n for (int k = lo; k <= hi; k++) {\n if (i > mid) index[k] = aux[j++];\n else if (j > hi) index[k] = aux[i++];\n else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];\n else index[k] = aux[i++];\n }\n }\n\n /**\n * Returns a permutation that gives the elements in the array in ascending order.\n * @param a the array\n * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},\n * ..., {@code a[p[n-1]]} are in ascending order\n */\n public static int[] indexSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n for (int i = 0; i < n; i++)\n index[i] = i;\n\n int[] aux = new int[n];\n sort(a, index, aux, 0, n-1);\n return index;\n }\n\n // mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, index, aux, lo, mid);\n sort(a, index, aux, mid + 1, hi);\n merge(a, index, aux, lo, mid, hi);\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; mergesorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n Merge.sort(a);\n show(a);\n }\n}\n", "support_files": [], "metadata": {"number": "2.2.20", "code_execution": true, "url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Write a program Sort2distinct.java that sorts an array that is known to contain just two distinct key values. ", "answer": "/******************************************************************************\n * Compilation: javac Sort2distinct.java\n * Execution: java Sort2distinct binary-string\n * Dependencies: StdOut.java\n *\n * Partitions the array of specified as the command-line.\n * Assumes there are at most 2 distinct elements.\n *\n ******************************************************************************/\n\npublic class Sort2distinct {\n\n // rearranges a[] in ascending order assuming a[] has at most 3 distinct values\n public static void sort(Comparable[] a) {\n int lt = 0, gt = a.length - 1;\n int i = 0;\n while (i <= gt) {\n int cmp = a[i].compareTo(a[lt]);\n if (cmp < 0) exch(a, lt++, i++);\n else if (cmp > 0) exch(a, i, gt--);\n else i++;\n }\n }\n\n // exchange a[i] and a[j]\n private static void exch(Comparable[] a, int i, int j) {\n Comparable swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n // test client\n public static void main(String[] args) {\n\n // parse command-line argument as an array of 1-character strings\n String s = args[0];\n int n = s.length();\n String[] a = new String[n];\n for (int i = 0; i < n; i++)\n a[i] = s.substring(i, i+1);\n\n // sort a print results\n sort(a);\n for (int i = 0; i < n; i++)\n StdOut.print(a[i]);\n StdOut.println();\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.3.5", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/Sort2distinct.java", "params": ["01001111011100111011011101001100", "10110111001101111100001011011011", "10110100010000111011000111110000", "01110100010010011010011111001001", "11000101001001011100011011010111"], "dependencies": ["StdOut.java"]}} {"question": "Best case. Write a program QuickBest.java that produces a best-case array (with no duplicates) for Quick.sort(): an array of N distinct keys with the property that every partition will produce subarrays that differ in size by at most 1 (the same subarray sizes that would happen for an array of N equal keys). For the purposes of this exercise, ignore the initial shuffle. ", "answer": "/******************************************************************************\n * Compilation: javac QuickBest.java\n * Execution: java QuickBest n\n * Dependencies: StdOut.java\n *\n * Generate a best-case input of size n for standard quicksort.\n *\n * % java QuickBest 3\n * BAC\n *\n * % java QuickBest 7\n * DACBFEG\n *\n * % java QuickBest 15\n * HACBFEGDLIKJNMO\n *\n ******************************************************************************/\n\npublic class QuickBest {\n\n // postcondition: a[lo..hi] is best-case input for quicksorting that subarray\n private static void best(int[] a, int lo, int hi) {\n\n // precondition: a[lo..hi] contains keys lo to hi, in order\n for (int i = lo; i <= hi; i++)\n assert a[i] == i;\n\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n best(a, lo, mid-1);\n best(a, mid+1, hi);\n exch(a, lo, mid);\n }\n\n public static int[] best(int n) {\n int[] a = new int[n];\n for (int i = 0; i < n; i++)\n a[i] = i;\n best(a, 0, n-1);\n return a;\n }\n\n // exchange a[i] and a[j]\n private static void exch(int[] a, int i, int j) {\n int swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n public static void main(String[] args) {\n String alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n int n = Integer.parseInt(args[0]);\n int[] a = best(n);\n for (int i = 0; i < n; i++)\n // StdOut.println(a[i]);\n StdOut.print(alphabet.charAt(a[i]));\n StdOut.println();\n }\n}\n", "support_files": [], "metadata": {"number": "2.3.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickBest.java", "params": ["3", "7", "15"], "dependencies": ["StdOut.java"]}} {"question": "Fast three-way partitioning. (J. Bentley and D. McIlroy). Implement an entropy-optimal sort QuickBentleyMcIlroy.java based on keeping equal keys at both the left and right ends of the subarray. Maintain indices p and q such that a[lo..p-1] that a[q+1..hi] are all equal to a[lo], an index i such that a[p..i-1] are all less than a[lo] and an index j such that a[j+1..q] are all greater than a[lo]. Add to the inner partitioning loop code to swap a[i] with a[p] (and increment p) if it is equal to v and to swap a[j] with a[q] (and decrement q) if it is equal to v before the usual comparisons of a[i] and a[j] with v. After the partitioning loop has terminated, add code to swap the equal keys into position", "answer": "/******************************************************************************\n * Compilation: javac QuickX.java\n * Execution: java QuickX < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt\n * https://algs4.cs.princeton.edu/23quicksort/words3.txt\n *\n * Uses the Hoare's 2-way partitioning scheme, chooses the partitioning\n * element using median-of-3, and cuts off to insertion sort.\n *\n ******************************************************************************/\n\n/**\n * The {@code QuickX} class provides static methods for sorting an array\n * using an optimized version of quicksort (using Hoare's 2-way partitioning\n * algorithm, median-of-3 to choose the partitioning element, and cutoff\n * to insertion sort).\n *

\n * For additional documentation, see\n * Section 2.3\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class QuickX {\n\n // cutoff to insertion sort, must be >= 1\n private static final int INSERTION_SORT_CUTOFF = 8;\n\n // This class should not be instantiated.\n private QuickX() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n // StdRandom.shuffle(a);\n sort(a, 0, a.length - 1);\n assert isSorted(a);\n }\n\n // quicksort the subarray from a[lo] to a[hi]\n private static void sort(Comparable[] a, int lo, int hi) {\n if (hi <= lo) return;\n\n // cutoff to insertion sort (Insertion.sort() uses half-open intervals)\n int n = hi - lo + 1;\n if (n <= INSERTION_SORT_CUTOFF) {\n Insertion.sort(a, lo, hi + 1);\n return;\n }\n\n int j = partition(a, lo, hi);\n sort(a, lo, j-1);\n sort(a, j+1, hi);\n }\n\n // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]\n // and return the index j.\n private static int partition(Comparable[] a, int lo, int hi) {\n int n = hi - lo + 1;\n int m = median3(a, lo, lo + n/2, hi);\n exch(a, m, lo);\n\n int i = lo;\n int j = hi + 1;\n Comparable v = a[lo];\n\n // a[lo] is unique largest element\n while (less(a[++i], v)) {\n if (i == hi) { exch(a, lo, hi); return hi; }\n }\n\n // a[lo] is unique smallest element\n while (less(v, a[--j])) {\n if (j == lo + 1) return lo;\n }\n\n // the main loop\n while (i < j) {\n exch(a, i, j);\n while (less(a[++i], v)) ;\n while (less(v, a[--j])) ;\n }\n\n // put partitioning item v at a[j]\n exch(a, lo, j);\n\n // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]\n return j;\n }\n\n // return the index of the median element among a[i], a[j], and a[k]\n private static int median3(Comparable[] a, int i, int j, int k) {\n return (less(a[i], a[j]) ?\n (less(a[j], a[k]) ? j : less(a[i], a[k]) ? k : i) :\n (less(a[k], a[j]) ? j : less(a[k], a[i]) ? k : i));\n }\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n for (int i = 1; i < a.length; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; quicksorts them\n * (using an optimized version of 2-way quicksort);\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n QuickX.sort(a);\n assert isSorted(a);\n show(a);\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/23quicksort/QuickX.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.", "answer": "/******************************************************************************\n * Compilation: javac MaxPQ.java\n * Execution: java MaxPQ < input.txt\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/24pq/tinyPQ.txt\n *\n * Generic max priority queue implementation with a binary heap.\n * Can be used with a comparator instead of the natural order,\n * but the generic Key type must still be Comparable.\n *\n * % java MaxPQ < tinyPQ.txt\n * Q X P (6 left on pq)\n *\n * We use a one-based array to simplify parent and child calculations.\n *\n * Can be optimized by replacing full exchanges with half exchanges\n * (ala insertion sort).\n *\n ******************************************************************************/\n\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code MaxPQ} class represents a priority queue of generic keys.\n * It supports the usual insert and delete-the-maximum\n * operations, along with methods for peeking at the maximum key,\n * testing if the priority queue is empty, and iterating through\n * the keys.\n *

\n * This implementation uses a binary heap.\n * The insert and delete-the-maximum operations take\n * Θ(log n) amortized time, where n is the number\n * of elements in the priority queue. This is an amortized bound\n * (and not a worst-case bound) because of array resizing operations.\n * The min, size, and is-empty operations take\n * Θ(1) time in the worst case.\n * Construction takes time proportional to the specified capacity or the\n * number of items used to initialize the data structure.\n *

\n * For additional documentation, see\n * Section 2.4 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n *\n * @param the generic type of key on this priority queue\n */\n\npublic class MaxPQ implements Iterable {\n private Key[] pq; // store items at indices 1 to n\n private int n; // number of items on priority queue\n private Comparator comparator; // optional comparator\n\n /**\n * Initializes an empty priority queue with the given initial capacity.\n *\n * @param initCapacity the initial capacity of this priority queue\n */\n public MaxPQ(int initCapacity) {\n pq = (Key[]) new Object[initCapacity + 1];\n n = 0;\n }\n\n /**\n * Initializes an empty priority queue.\n */\n public MaxPQ() {\n this(1);\n }\n\n /**\n * Initializes an empty priority queue with the given initial capacity,\n * using the given comparator.\n *\n * @param initCapacity the initial capacity of this priority queue\n * @param comparator the order in which to compare the keys\n */\n public MaxPQ(int initCapacity, Comparator comparator) {\n this.comparator = comparator;\n pq = (Key[]) new Object[initCapacity + 1];\n n = 0;\n }\n\n /**\n * Initializes an empty priority queue using the given comparator.\n *\n * @param comparator the order in which to compare the keys\n */\n public MaxPQ(Comparator comparator) {\n this(1, comparator);\n }\n\n /**\n * Initializes a priority queue from the array of keys.\n * Takes time proportional to the number of keys, using sink-based heap construction.\n *\n * @param keys the array of keys\n */\n public MaxPQ(Key[] keys) {\n n = keys.length;\n pq = (Key[]) new Object[keys.length + 1];\n for (int i = 0; i < n; i++)\n pq[i+1] = keys[i];\n for (int k = n/2; k >= 1; k--)\n sink(k);\n assert isMaxHeap();\n }\n\n\n\n /**\n * Returns true if this priority queue is empty.\n *\n * @return {@code true} if this priority queue is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return n == 0;\n }\n\n /**\n * Returns the number of keys on this priority queue.\n *\n * @return the number of keys on this priority queue\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns a largest key on this priority queue.\n *\n * @return a largest key on this priority queue\n * @throws NoSuchElementException if this priority queue is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"Priority queue underflow\");\n return pq[1];\n }\n\n // resize the underlying array to have the given capacity\n private void resize(int capacity) {\n assert capacity > n;\n Key[] temp = (Key[]) new Object[capacity];\n for (int i = 1; i <= n; i++) {\n temp[i] = pq[i];\n }\n pq = temp;\n }\n\n\n /**\n * Adds a new key to this priority queue.\n *\n * @param x the new key to add to this priority queue\n */\n public void insert(Key x) {\n\n // double size of array if necessary\n if (n == pq.length - 1) resize(2 * pq.length);\n\n // add x, and percolate it up to maintain heap invariant\n pq[++n] = x;\n swim(n);\n assert isMaxHeap();\n }\n\n /**\n * Removes and returns a largest key on this priority queue.\n *\n * @return a largest key on this priority queue\n * @throws NoSuchElementException if this priority queue is empty\n */\n public Key delMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Priority queue underflow\");\n Key max = pq[1];\n exch(1, n--);\n sink(1);\n pq[n+1] = null; // to avoid loitering and help with garbage collection\n if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2);\n assert isMaxHeap();\n return max;\n }\n\n\n /***************************************************************************\n * Helper functions to restore the heap invariant.\n ***************************************************************************/\n\n private void swim(int k) {\n while (k > 1 && less(k/2, k)) {\n exch(k/2, k);\n k = k/2;\n }\n }\n\n private void sink(int k) {\n while (2*k <= n) {\n int j = 2*k;\n if (j < n && less(j, j+1)) j++;\n if (!less(k, j)) break;\n exch(k, j);\n k = j;\n }\n }\n\n /***************************************************************************\n * Helper functions for compares and swaps.\n ***************************************************************************/\n private boolean less(int i, int j) {\n if (comparator == null) {\n return ((Comparable) pq[i]).compareTo(pq[j]) < 0;\n }\n else {\n return comparator.compare(pq[i], pq[j]) < 0;\n }\n }\n\n private void exch(int i, int j) {\n Key swap = pq[i];\n pq[i] = pq[j];\n pq[j] = swap;\n }\n\n // is pq[1..n] a max heap?\n private boolean isMaxHeap() {\n for (int i = 1; i <= n; i++) {\n if (pq[i] == null) return false;\n }\n for (int i = n+1; i < pq.length; i++) {\n if (pq[i] != null) return false;\n }\n if (pq[0] != null) return false;\n return isMaxHeapOrdered(1);\n }\n\n // is subtree of pq[1..n] rooted at k a max heap?\n private boolean isMaxHeapOrdered(int k) {\n if (k > n) return true;\n int left = 2*k;\n int right = 2*k + 1;\n if (left <= n && less(k, left)) return false;\n if (right <= n && less(k, right)) return false;\n return isMaxHeapOrdered(left) && isMaxHeapOrdered(right);\n }\n\n\n /***************************************************************************\n * Iterator.\n ***************************************************************************/\n\n /**\n * Returns an iterator that iterates over the keys on this priority queue\n * in descending order.\n * The iterator doesn't implement {@code remove()} since it's optional.\n *\n * @return an iterator that iterates over the keys in descending order\n */\n public Iterator iterator() {\n return new HeapIterator();\n }\n\n private class HeapIterator implements Iterator {\n\n // create a new pq\n private MaxPQ copy;\n\n // add all items to copy of heap\n // takes linear time since already in heap order so no keys move\n public HeapIterator() {\n if (comparator == null) copy = new MaxPQ(size());\n else copy = new MaxPQ(size(), comparator);\n for (int i = 1; i <= n; i++)\n copy.insert(pq[i]);\n }\n\n public boolean hasNext() { return !copy.isEmpty(); }\n public void remove() { throw new UnsupportedOperationException(); }\n\n public Key next() {\n if (!hasNext()) throw new NoSuchElementException();\n return copy.delMax();\n }\n }\n\n /**\n * Unit tests the {@code MaxPQ} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n MaxPQ pq = new MaxPQ();\n while (!StdIn.isEmpty()) {\n String item = StdIn.readString();\n if (!item.equals(\"-\")) pq.insert(item);\n else if (!pq.isEmpty()) StdOut.print(pq.delMax() + \" \");\n }\n StdOut.println(\"(\" + pq.size() + \" left on pq)\");\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.4.15", "code_execution": true, "url": "https://algs4.cs.princeton.edu/24pq/MaxPQ.java", "params": ["< tinyPQ.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Computational number theory. Write a program CubeSum.java that prints out all integers of the form \\(a^3 + b^3\\)\nwhere \\(a\\) and \\(b\\) are integers between 0 and \\(n<\\) in sorted order,\nwithout using excessive space. That is, instead of computing an array of\nthe \\(n^2\\) sums and sorting them, build a minimum-oriented priority\nqueue, initially containing\n\\((0^3, 0, 0), (1^3 + 1^3, 1, 1), (2^3 + 2^3, 2, 2), \\ldots, (n^3 + n^3, n, n)\\).\nThen, while the priority queue is nonempty, remove the smallest item\n\\(i^3 + j^3,\\; i, \\; j)\\), print it, and then, if \n\\(j < n\\), insert the item \\((i^3 + (j+1)^3,\\; i,\\; j+1)\\).\nUse this program to find all distinct integers \\(a, b, c\\), and \\(d\\) between 0 and \n\\(10^6\\) such that \n\\(a^3 + b^3 = c^3 + d^3\\), such as\n\\(1729 = 9^3 + 10^3 = 1^3 + 12^3\\).", "answer": "/******************************************************************************\n * Compilation: javac CubeSum.java\n * Execution: java CubeSum n\n * Dependencies: MinPQ.java\n *\n * Print out integers of the form a^3 + b^3 in sorted order, where\n * 0 <= a <= b <= n.\n *\n * % java CubeSum 12\n * 0 = 0^3 + 0^3\n * 1 = 0^3 + 1^3\n * 2 = 1^3 + 1^3\n * 8 = 0^3 + 2^3\n * 9 = 1^3 + 2^3\n * ...\n * 1729 = 9^3 + 10^3\n * 1729 = 1^3 + 12^3\n * ...\n * 3456 = 12^3 + 12^3\n *\n * Remarks\n * -------\n * - Easily extends to handle sums of the form f(a) + g(b)\n * - Prints out a sum more than once if it can be obtained\n * in more than one way, e.g., 1729 = 9^3 + 10^3 = 1^3 + 12^3\n *\n ******************************************************************************/\n\npublic class CubeSum implements Comparable {\n private final int sum;\n private final int i;\n private final int j;\n\n public CubeSum(int i, int j) {\n this.sum = i*i*i + j*j*j;\n this.i = i;\n this.j = j;\n }\n\n public int compareTo(CubeSum that) {\n if (this.sum < that.sum) return -1;\n if (this.sum > that.sum) return +1;\n return 0;\n }\n\n public String toString() {\n return sum + \" = \" + i + \"^3\" + \" + \" + j + \"^3\";\n }\n\n\n public static void main(String[] args) {\n\n int n = Integer.parseInt(args[0]);\n\n // initialize priority queue\n MinPQ pq = new MinPQ();\n for (int i = 0; i <= n; i++) {\n pq.insert(new CubeSum(i, i));\n }\n\n // find smallest sum, print it out, and update\n while (!pq.isEmpty()) {\n CubeSum s = pq.delMin();\n StdOut.println(s);\n if (s.j < n)\n pq.insert(new CubeSum(s.i, s.j + 1));\n }\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.4.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/24pq/CubeSum.java", "params": ["4", "12"], "dependencies": ["MinPQ.java"]}} {"question": "Interval 1D data type. Write three static comparators for Interval1D.java, one that compares intervals by their left endpoing, one that compares intervals by their right endpoint, and one that compares intervals by their length.", "answer": "/******************************************************************************\n * Compilation: javac Insertion.java\n * Execution: java Insertion < input.txt\n * Dependencies: StdOut.java StdIn.java\n * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt\n * https://algs4.cs.princeton.edu/21elementary/words3.txt\n *\n * Sorts a sequence of strings from standard input using insertion sort.\n *\n * % more tiny.txt\n * S O R T E X A M P L E\n *\n * % java Insertion < tiny.txt\n * A E E L M O P R S T X [ one string per line ]\n *\n * % more words3.txt\n * bed bug dad yes zoo ... all bad yet\n *\n * % java Insertion < words3.txt\n * all bad bed bug dad ... yes yet zoo [ one string per line ]\n *\n ******************************************************************************/\n\nimport java.util.Comparator;\n\n/**\n * The {@code Insertion} class provides static methods for sorting an\n * array using insertion sort.\n *

\n * In the worst case, this implementation makes ~ ½ n2\n * compares and ~ ½ n2 exchanges to sort an array\n * of length n. So, it is not suitable for sorting large arbitrary\n * arrays. More precisely, the number of exchanges is exactly equal to the\n * number of inversions. So, for example, it sorts a partially-sorted array\n * in linear time.\n *

\n * This sorting algorithm is stable.\n * It uses Θ(1) extra memory (not including the input array).\n *

\n * See InsertionPedantic.java\n * for a version that eliminates the compiler warning.\n *

\n * For additional documentation, see Section 2.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Insertion {\n\n // This class should not be instantiated.\n private Insertion() { }\n\n /**\n * Rearranges the array in ascending order, using the natural order.\n * @param a the array to be sorted\n */\n public static void sort(Comparable[] a) {\n int n = a.length;\n for (int i = 1; i < n; i++) {\n for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {\n exch(a, j, j-1);\n }\n assert isSorted(a, 0, i);\n }\n assert isSorted(a);\n }\n\n /**\n * Rearranges the subarray a[lo..hi) in ascending order, using the natural order.\n * @param a the array to be sorted\n * @param lo left endpoint (inclusive)\n * @param hi right endpoint (exclusive)\n */\n public static void sort(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i < hi; i++) {\n for (int j = i; j > lo && less(a[j], a[j-1]); j--) {\n exch(a, j, j-1);\n }\n }\n assert isSorted(a, lo, hi);\n }\n\n /**\n * Rearranges the array in ascending order, using a comparator.\n * @param a the array\n * @param comparator the comparator specifying the order\n */\n public static void sort(Object[] a, Comparator comparator) {\n int n = a.length;\n for (int i = 1; i < n; i++) {\n for (int j = i; j > 0 && less(a[j], a[j-1], comparator); j--) {\n exch(a, j, j-1);\n }\n assert isSorted(a, 0, i, comparator);\n }\n assert isSorted(a, comparator);\n }\n\n /**\n * Rearranges the subarray a[lo..hi) in ascending order, using a comparator.\n * @param a the array\n * @param lo left endpoint (inclusive)\n * @param hi right endpoint (exclusive)\n * @param comparator the comparator specifying the order\n */\n public static void sort(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo + 1; i < hi; i++) {\n for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) {\n exch(a, j, j-1);\n }\n }\n assert isSorted(a, lo, hi, comparator);\n }\n\n\n // return a permutation that gives the elements in a[] in ascending order\n // do not change the original array a[]\n /**\n * Returns a permutation that gives the elements in the array in ascending order.\n * @param a the array\n * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},\n * ..., {@code a[p[n-1]]} are in ascending order\n */\n public static int[] indexSort(Comparable[] a) {\n int n = a.length;\n int[] index = new int[n];\n for (int i = 0; i < n; i++)\n index[i] = i;\n\n for (int i = 1; i < n; i++)\n for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)\n exch(index, j, j-1);\n\n return index;\n }\n\n /***************************************************************************\n * Helper sorting functions.\n ***************************************************************************/\n\n // is v < w ?\n private static boolean less(Comparable v, Comparable w) {\n return v.compareTo(w) < 0;\n }\n\n // is v < w ?\n private static boolean less(Object v, Object w, Comparator comparator) {\n return comparator.compare(v, w) < 0;\n }\n\n // exchange a[i] and a[j]\n private static void exch(Object[] a, int i, int j) {\n Object swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n // exchange a[i] and a[j] (for indirect sort)\n private static void exch(int[] a, int i, int j) {\n int swap = a[i];\n a[i] = a[j];\n a[j] = swap;\n }\n\n /***************************************************************************\n * Check if array is sorted - useful for debugging.\n ***************************************************************************/\n private static boolean isSorted(Comparable[] a) {\n return isSorted(a, 0, a.length);\n }\n\n // is the array a[lo..hi) sorted\n private static boolean isSorted(Comparable[] a, int lo, int hi) {\n for (int i = lo + 1; i < hi; i++)\n if (less(a[i], a[i-1])) return false;\n return true;\n }\n\n private static boolean isSorted(Object[] a, Comparator comparator) {\n return isSorted(a, 0, a.length, comparator);\n }\n\n // is the array a[lo..hi) sorted\n private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {\n for (int i = lo + 1; i < hi; i++)\n if (less(a[i], a[i-1], comparator)) return false;\n return true;\n }\n\n // print array to standard output\n private static void show(Comparable[] a) {\n for (int i = 0; i < a.length; i++) {\n StdOut.println(a[i]);\n }\n }\n\n /**\n * Reads in a sequence of strings from standard input; insertion sorts them;\n * and prints them to standard output in ascending order.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n Insertion.sort(a);\n show(a);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/21elementary/words3.txt", "https://algs4.cs.princeton.edu/21elementary/tiny.txt"], "metadata": {"number": "2.5.27", "code_execution": true, "url": "https://algs4.cs.princeton.edu/25applications/Insertion.java", "params": ["< tiny.txt", "< words3.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Sort files by name. Write a program FileSorter.java that takes the name of a directory as a command line input and prints out all of the files in the current directory, sorted by filename. Hint: use the java.io.File data type.", "answer": "/******************************************************************************\n * Compilation: javac FileSorter.java\n * Execution: java FileSorter directory-name\n * Dependencies: StdOut.java\n *\n * Prints out all of the files in the given directory in\n * sorted order.\n *\n * % java FileSorter .\n *\n ******************************************************************************/\n\nimport java.io.File;\nimport java.util.Arrays;\n\npublic class FileSorter {\n\n public static void main(String[] args) {\n File directory = new File(args[0]); // root directory\n if (!directory.exists()) {\n StdOut.println(args[0] + \" does not exist\");\n return;\n }\n if (!directory.isDirectory()) {\n StdOut.println(args[0] + \" is not a directory\");\n return;\n }\n File[] files = directory.listFiles();\n if (files == null) {\n StdOut.println(\"could not read files\");\n return;\n }\n Arrays.sort(files);\n for (int i = 0; i < files.length; i++)\n StdOut.println(files[i].getName());\n }\n\n}\n", "support_files": [], "metadata": {"number": "2.5.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/25applications/FileSorter.java", "params": ["java FileSorter ."], "dependencies": ["StdOut.java"]}} {"question": "Write a client \nprogram GPA.java that creates a symbol table mapping letter grades to numerical \nscores, as in the table below, then reads from standard input a list of letter \ngrades and computes and prints the GPA (the average of the numerical\nscores of the corresponding grades). A+ A A- B+ B B- C+ C C- D F\n4.33 4.00 3.67 3.33 3.00 2.67 2.33 2.00 1.67 1.00 0.00", "answer": "/******************************************************************************\n * Compilation: javac GPA.java\n * Execution: java GPA < input.txt\n * Dependencies: ST.java\n *\n * Create a symbol table mapping letter grades to numerical\n * scores, then read a list of letter grades from standard input,\n * and print the GPA.\n *\n * % java GPA\n * A- B+ B+ B-\n * GPA = 3.25\n *\n ******************************************************************************/\n\npublic class GPA {\n public static void main(String[] args) {\n\n // create symbol table of grades and values\n ST grades = new ST();\n grades.put(\"A\", 4.00);\n grades.put(\"B\", 3.00);\n grades.put(\"C\", 2.00);\n grades.put(\"D\", 1.00);\n grades.put(\"F\", 0.00);\n grades.put(\"A+\", 4.33);\n grades.put(\"B+\", 3.33);\n grades.put(\"C+\", 2.33);\n grades.put(\"A-\", 3.67);\n grades.put(\"B-\", 2.67);\n\n\n // read grades from standard input and compute gpa\n int n = 0;\n double total = 0.0;\n for (n = 0; !StdIn.isEmpty(); n++) {\n String grade = StdIn.readString();\n double value = grades.get(grade);\n total += value;\n }\n double gpa = total / n;\n StdOut.println(\"GPA = \" + gpa);\n }\n}\n\n\n", "support_files": [], "metadata": {"number": "3.1.1", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/GPA.java", "params": ["< {\n private static final int INIT_SIZE = 8;\n\n private Value[] vals; // symbol table values\n private Key[] keys; // symbol table keys\n private int n = 0; // number of elements in symbol table\n\n public ArrayST() {\n keys = (Key[]) new Object[INIT_SIZE];\n vals = (Value[]) new Object[INIT_SIZE];\n }\n\n // return the number of key-value pairs in the symbol table\n public int size() {\n return n;\n }\n\n // is the symbol table empty?\n public boolean isEmpty() {\n return size() == 0;\n }\n\n // resize the parallel arrays to the given capacity\n private void resize(int capacity) {\n Key[] tempk = (Key[]) new Object[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++)\n tempk[i] = keys[i];\n for (int i = 0; i < n; i++)\n tempv[i] = vals[i];\n keys = tempk;\n vals = tempv;\n }\n\n // insert the key-value pair into the symbol table\n public void put(Key key, Value val) {\n\n // to deal with duplicates\n delete(key);\n\n // double size of arrays if necessary\n if (n >= vals.length) resize(2*n);\n\n // add new key and value at the end of array\n vals[n] = val;\n keys[n] = key;\n n++;\n }\n\n public Value get(Key key) {\n for (int i = 0; i < n; i++)\n if (keys[i].equals(key)) return vals[i];\n return null;\n }\n\n public Iterable keys() {\n Queue queue = new Queue();\n for (int i = 0; i < n; i++)\n queue.enqueue(keys[i]);\n return queue;\n }\n\n // remove given key (and associated value)\n public void delete(Key key) {\n for (int i = 0; i < n; i++) {\n if (key.equals(keys[i])) {\n keys[i] = keys[n-1];\n vals[i] = vals[n-1];\n keys[n-1] = null;\n vals[n-1] = null;\n n--;\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n return;\n }\n }\n }\n\n\n\n\n /***************************************************************************\n * Test routine.\n ***************************************************************************/\n public static void main(String[] args) {\n ArrayST st = new ArrayST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.2", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/ArrayST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement size(), delete(), and keys() for SequentialSearchST.java.", "answer": "/******************************************************************************\n * Compilation: javac SequentialSearchST.java\n * Execution: java SequentialSearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with sequential search in an\n * unordered linked list of key-value pairs.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java SequentialSearchST < tinyST.txt\n * L 11\n * P 10\n * M 9\n * X 7\n * H 5\n * C 4\n * R 3\n * A 8\n * E 12\n * S 0\n *\n ******************************************************************************/\n\n/**\n * The {@code SequentialSearchST} class represents an (unordered)\n * symbol table of generic key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * The class also uses the convention that values cannot be {@code null}. Setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It relies on the {@code equals()} method to test whether two keys\n * are equal. It does not call either the {@code compareTo()} or\n * {@code hashCode()} method.\n *

\n * This implementation uses a singly linked list and\n * sequential search.\n * The put and delete operations take Θ(n).\n * The get and contains operations takes Θ(n)\n * time in the worst case.\n * The size, and is-empty operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For additional documentation, see\n * Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class SequentialSearchST {\n private int n; // number of key-value pairs\n private Node first; // the linked list of key-value pairs\n\n // a helper linked list data type\n private class Node {\n private Key key;\n private Value val;\n private Node next;\n\n public Node(Key key, Value val, Node next) {\n this.key = key;\n this.val = val;\n this.next = next;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public SequentialSearchST() {\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns true if this symbol table contains the specified key.\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key};\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n for (Node x = first; x != null; x = x.next) {\n if (key.equals(x.key))\n return x.val;\n }\n return null;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n if (val == null) {\n delete(key);\n return;\n }\n\n for (Node x = first; x != null; x = x.next) {\n if (key.equals(x.key)) {\n x.val = val;\n return;\n }\n }\n first = new Node(key, val, first);\n n++;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n first = delete(first, key);\n }\n\n // delete key in linked list beginning at Node x\n // warning: function call stack too large if table is large\n private Node delete(Node x, Key key) {\n if (x == null) return null;\n if (key.equals(x.key)) {\n n--;\n return x.next;\n }\n x.next = delete(x.next, key);\n return x;\n }\n\n\n /**\n * Returns all keys in the symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table\n */\n public Iterable keys() {\n Queue queue = new Queue();\n for (Node x = first; x != null; x = x.next)\n queue.enqueue(x.key);\n return queue;\n }\n\n\n /**\n * Unit tests the {@code SequentialSearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n SequentialSearchST st = new SequentialSearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.5", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/SequentialSearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement the delete() method for BinarySearchST.java.", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n\u20131\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.16", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Implement the floor() method for BinarySearchST.java .", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n\u20131\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.17", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Certification. Add assert statements to BinarySearchST.java to check algorithm invariants and data structure integrity after every \ninsertion and deletion. For example, every index i should always be equal to rank(select(i)) and the array should \nalways be in order.", "answer": "/******************************************************************************\n * Compilation: javac BinarySearchST.java\n * Execution: java BinarySearchST\n * Dependencies: StdIn.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt\n *\n * Symbol table implementation with binary search in an ordered array.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BinarySearchST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, and ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses a sorted array.\n * The put and remove operations take Θ(n)\n * time in the worst case.\n * The contains, ceiling, floor,\n * and rank operations take Θ(log n) time in the worst\n * case.\n * The size, is-empty, minimum, maximum,\n * and select operations take Θ(1) time.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API,\n * see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation,\n * see Section 3.1 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n */\npublic class BinarySearchST, Value> {\n private static final int INIT_CAPACITY = 2;\n private Key[] keys;\n private Value[] vals;\n private int n = 0;\n\n /**\n * Initializes an empty symbol table.\n */\n public BinarySearchST() {\n this(INIT_CAPACITY);\n }\n\n /**\n * Initializes an empty symbol table with the specified initial capacity.\n * @param capacity the maximum capacity\n */\n public BinarySearchST(int capacity) {\n keys = (Key[]) new Comparable[capacity];\n vals = (Value[]) new Object[capacity];\n }\n\n // resize the underlying arrays\n private void resize(int capacity) {\n assert capacity >= n;\n Key[] tempk = (Key[]) new Comparable[capacity];\n Value[] tempv = (Value[]) new Object[capacity];\n for (int i = 0; i < n; i++) {\n tempk[i] = keys[i];\n tempv[i] = vals[i];\n }\n vals = tempv;\n keys = tempk;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n *\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return n;\n }\n\n /**\n * Returns true if this symbol table is empty.\n *\n * @return {@code true} if this symbol table is empty;\n * {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key in this symbol table.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to get() is null\");\n if (isEmpty()) return null;\n int i = rank(key);\n if (i < n && keys[i].compareTo(key) == 0) return vals[i];\n return null;\n }\n\n /**\n * Returns the number of keys in this symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n\n int lo = 0, hi = n-1;\n while (lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int cmp = key.compareTo(keys[mid]);\n if (cmp < 0) hi = mid - 1;\n else if (cmp > 0) lo = mid + 1;\n else return mid;\n }\n return lo;\n }\n\n\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"first argument to put() is null\");\n\n if (val == null) {\n delete(key);\n return;\n }\n\n int i = rank(key);\n\n // key is already in table\n if (i < n && keys[i].compareTo(key) == 0) {\n vals[i] = val;\n return;\n }\n\n // insert new key-value pair\n if (n == keys.length) resize(2*keys.length);\n\n for (int j = n; j > i; j--) {\n keys[j] = keys[j-1];\n vals[j] = vals[j-1];\n }\n keys[i] = key;\n vals[i] = val;\n n++;\n\n assert check();\n }\n\n /**\n * Removes the specified key and associated value from this symbol table\n * (if the key is in the symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to delete() is null\");\n if (isEmpty()) return;\n\n // compute rank\n int i = rank(key);\n\n // key not in table\n if (i == n || keys[i].compareTo(key) != 0) {\n return;\n }\n\n for (int j = i; j < n-1; j++) {\n keys[j] = keys[j+1];\n vals[j] = vals[j+1];\n }\n\n n--;\n keys[n] = null; // to avoid loitering\n vals[n] = null;\n\n // resize if 1/4 full\n if (n > 0 && n == keys.length/4) resize(keys.length/2);\n\n assert check();\n }\n\n /**\n * Removes the smallest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(min());\n }\n\n /**\n * Removes the largest key and associated value from this symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow error\");\n delete(max());\n }\n\n\n /***************************************************************************\n * Ordered symbol table methods.\n ***************************************************************************/\n\n /**\n * Returns the smallest key in this symbol table.\n *\n * @return the smallest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n return keys[0];\n }\n\n /**\n * Returns the largest key in this symbol table.\n *\n * @return the largest key in this symbol table\n * @throws NoSuchElementException if this symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n return keys[n-1];\n }\n\n /**\n * Return the kth smallest key in this symbol table.\n *\n * @param k the order statistic\n * @return the {@code k}th smallest key in this symbol table\n * @throws IllegalArgumentException unless {@code k} is between 0 and\n * n\u20131\n */\n public Key select(int k) {\n if (k < 0 || k >= size()) {\n throw new IllegalArgumentException(\"called select() with invalid argument: \" + k);\n }\n return keys[k];\n }\n\n /**\n * Returns the largest key in this symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in this symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n int i = rank(key);\n if (i < n && key.compareTo(keys[i]) == 0) return keys[i];\n if (i == 0) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return keys[i-1];\n }\n\n /**\n * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in this symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n int i = rank(key);\n if (i == n) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return keys[i];\n }\n\n /**\n * Returns the number of keys in this symbol table in the specified range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns all keys in this symbol table as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in this symbol table\n */\n public Iterable keys() {\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in this symbol table in the given range,\n * as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in this symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n if (lo.compareTo(hi) > 0) return queue;\n for (int i = rank(lo); i < rank(hi); i++)\n queue.enqueue(keys[i]);\n if (contains(hi)) queue.enqueue(keys[rank(hi)]);\n return queue;\n }\n\n\n /***************************************************************************\n * Check internal invariants.\n ***************************************************************************/\n\n private boolean check() {\n return isSorted() && rankCheck();\n }\n\n // are the items in the array in ascending order?\n private boolean isSorted() {\n for (int i = 1; i < size(); i++)\n if (keys[i].compareTo(keys[i-1]) < 0) return false;\n return true;\n }\n\n // check that rank(select(i)) = i\n private boolean rankCheck() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (int i = 0; i < size(); i++)\n if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BinarySearchST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BinarySearchST st = new BinarySearchST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/31elementary/tinyST.txt"], "metadata": {"number": "3.1.30", "code_execution": true, "url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java"]}} {"question": "Add to BST.java a method height() that computes the height of the tree. Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).", "answer": "/******************************************************************************\n * Compilation: javac BST.java\n * Execution: java BST\n * Dependencies: StdIn.java StdOut.java Queue.java\n * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt\n *\n * A symbol table implemented with a binary search tree.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses an (unbalanced) binary search tree.\n * The put, contains, remove, minimum,\n * maximum, ceiling, floor, select, and\n * rank operations each take Θ(n) time in the worst\n * case, where n is the number of key-value pairs.\n * The size and is-empty operations take Θ(1) time.\n * The keys method takes Θ(n) time in the worst case.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API, see {@link ST},\n * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation, see\n * Section 3.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BST, Value> {\n private Node root; // root of BST\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated data\n private Node left, right; // left and right subtrees\n private int size; // number of nodes in subtree\n\n public Node(Key key, Value val, int size) {\n this.key = key;\n this.val = val;\n this.size = size;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public BST() {\n }\n\n /**\n * Returns true if this symbol table is empty.\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return size(root);\n }\n\n // return number of key-value pairs in BST rooted at x\n private int size(Node node) {\n if (node == null) return 0;\n else return node.size;\n }\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls get() with a null key\");\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return get(node.left, key);\n else if (cmp > 0) return get(node.right, key);\n else return node.val;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"calls put() with a null key\");\n if (val == null) {\n delete(key);\n return;\n }\n root = put(root, key, val);\n assert check();\n }\n\n private Node put(Node node, Key key, Value val) {\n if (node == null) return new Node(key, val, 1);\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = put(node.left, key, val);\n else if (cmp > 0) node.right = put(node.right, key, val);\n else node.val = val;\n node.size = 1 + size(node.left) + size(node.right);\n return node;\n }\n\n\n /**\n * Removes the smallest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMin(root);\n assert check();\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the largest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMax(root);\n assert check();\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) return node.left;\n node.right = deleteMax(node.right);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls delete() with a null key\");\n root = delete(root, key);\n assert check();\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) return null;\n\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = delete(node.left, key);\n else if (cmp > 0) node.right = delete(node.right, key);\n else {\n if (node.right == null) return node.left;\n if (node.left == null) return node.right;\n Node temp = node;\n node = min(temp.right);\n node.right = deleteMin(temp.right);\n node.left = temp.left;\n }\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n\n /**\n * Returns the smallest key in the symbol table.\n *\n * @return the smallest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"calls min() with empty symbol table\");\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) return node;\n else return min(node.left);\n }\n\n /**\n * Returns the largest key in the symbol table.\n *\n * @return the largest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"calls max() with empty symbol table\");\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) return node;\n else return max(node.right);\n }\n\n /**\n * Returns the largest key in the symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in the symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls floor() with empty symbol table\");\n Node node = floor(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) return floor(node.left, key);\n Node t = floor(node.right, key);\n if (t != null) return t;\n else return node;\n }\n\n public Key floor2(Key key) {\n Key floor = floor2(root, key, null);\n if (floor == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return floor;\n\n }\n\n private Key floor2(Node node, Key key, Key champ) {\n if (node == null) return champ;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return floor2(node.left, key, champ);\n else if (cmp > 0) return floor2(node.right, key, node.key);\n else return node.key;\n }\n\n /**\n * Returns the smallest key in the symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in the symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls ceiling() with empty symbol table\");\n Node node = ceiling(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) {\n Node t = ceiling(node.left, key);\n if (t != null) return t;\n else return node;\n }\n return ceiling(node.right, key);\n }\n\n /**\n * Return the key in the symbol table of a given {@code rank}.\n * This key has the property that there are {@code rank} keys in\n * the symbol table that are smaller. In other words, this key is the\n * ({@code rank}+1)st smallest key in the symbol table.\n *\n * @param rank the order statistic\n * @return the key in the symbol table of given {@code rank}\n * @throws IllegalArgumentException unless {@code rank} is between 0 and\n * n\u20131\n */\n public Key select(int rank) {\n if (rank < 0 || rank >= size()) {\n throw new IllegalArgumentException(\"argument to select() is invalid: \" + rank);\n }\n return select(root, rank);\n }\n\n // Return key in BST rooted at x of given rank.\n // Precondition: rank is in legal range.\n private Key select(Node node, int rank) {\n if (node == null) return null;\n int leftSize = size(node.left);\n if (leftSize > rank) return select(node.left, rank);\n else if (leftSize < rank) return select(node.right, rank - leftSize - 1);\n else return node.key;\n }\n\n /**\n * Return the number of keys in the symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n return rank(key, root);\n }\n\n // Number of keys in the subtree less than key.\n private int rank(Key key, Node node) {\n if (node == null) return 0;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return rank(key, node.left);\n else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right);\n else return size(node.left);\n }\n\n /**\n * Returns all keys in the symbol table in ascending order,\n * as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table in ascending order\n */\n public Iterable keys() {\n if (isEmpty()) return new Queue();\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in the symbol table in the given range\n * in ascending order, as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive) in ascending order\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n keys(root, queue, lo, hi);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key lo, Key hi) {\n if (node == null) return;\n int cmplo = lo.compareTo(node.key);\n int cmphi = hi.compareTo(node.key);\n if (cmplo < 0) keys(node.left, queue, lo, hi);\n if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key);\n if (cmphi > 0) keys(node.right, queue, lo, hi);\n }\n\n /**\n * Returns the number of keys in the symbol table in the given range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns the height of the BST (for debugging).\n *\n * @return the height of the BST (a 1-node tree has height 0)\n */\n public int height() {\n return height(root);\n }\n private int height(Node node) {\n if (node == null) return -1;\n return 1 + Math.max(height(node.left), height(node.right));\n }\n\n /**\n * Returns the keys in the BST in level order (for debugging).\n *\n * @return the keys in the BST in level order traversal\n */\n public Iterable levelOrder() {\n Queue keys = new Queue();\n Queue queue = new Queue();\n queue.enqueue(root);\n while (!queue.isEmpty()) {\n Node node = queue.dequeue();\n if (node == null) continue;\n keys.enqueue(node.key);\n queue.enqueue(node.left);\n queue.enqueue(node.right);\n }\n return keys;\n }\n\n /*************************************************************************\n * Check integrity of BST data structure.\n ***************************************************************************/\n private boolean check() {\n if (!isBST()) StdOut.println(\"Not in symmetric order\");\n if (!isSizeConsistent()) StdOut.println(\"Subtree counts not consistent\");\n if (!isRankConsistent()) StdOut.println(\"Ranks not consistent\");\n return isBST() && isSizeConsistent() && isRankConsistent();\n }\n\n // does this binary tree satisfy symmetric order?\n // Note: this test also ensures that data structure is a binary tree since order is strict\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n // is the tree rooted at x a BST with all keys strictly between min and max\n // (if min or max is null, treat as empty constraint)\n // Credit: elegant solution due to Bob Dondero\n private boolean isBST(Node node, Key min, Key max) {\n if (node == null) return true;\n if (min != null && node.key.compareTo(min) <= 0) return false;\n if (max != null && node.key.compareTo(max) >= 0) return false;\n return isBST(node.left, min, node.key) && isBST(node.right, node.key, max);\n }\n\n // are the size fields correct?\n private boolean isSizeConsistent() { return isSizeConsistent(root); }\n private boolean isSizeConsistent(Node node) {\n if (node == null) return true;\n if (node.size != size(node.left) + size(node.right) + 1) return false;\n return isSizeConsistent(node.left) && isSizeConsistent(node.right);\n }\n\n // check that ranks are consistent\n private boolean isRankConsistent() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (Key key : keys())\n if (key.compareTo(select(rank(key))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BST st = new BST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n\n for (String s : st.levelOrder())\n StdOut.println(s + \" \" + st.get(s));\n\n StdOut.println();\n\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"number": "3.2.6", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java", "Queue.java"]}} {"question": "Give nonrecursive implementations of get() , put() , and keys() for BST.", "answer": "/******************************************************************************\n * Compilation: javac NonrecursiveBST.java\n * Execution: java NonrecursiveBST < input.txt\n * Dependencies: StdOut.java StdIn.java\n *\n * A symbol table implemented with a binary search tree using\n * iteration instead of recursion for put(), get(), and keys().\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java NonrecursiveBST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\npublic class NonrecursiveBST, Value> {\n\n // root of BST\n private Node root;\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated value\n private Node left, right; // left and right subtrees\n\n public Node(Key key, Value val) {\n this.key = key;\n this.val = val;\n }\n }\n\n\n /***************************************************************************\n * Insert key-value pair into symbol table (nonrecursive version).\n ***************************************************************************/\n public void put(Key key, Value val) {\n Node z = new Node(key, val);\n if (root == null) {\n root = z;\n return;\n }\n\n Node parent = null, x = root;\n while (x != null) {\n parent = x;\n int cmp = key.compareTo(x.key);\n if (cmp < 0) x = x.left;\n else if (cmp > 0) x = x.right;\n else {\n x.val = val;\n return;\n }\n }\n int cmp = key.compareTo(parent.key);\n if (cmp < 0) parent.left = z;\n else parent.right = z;\n }\n\n\n /***************************************************************************\n * Search BST for given key, nonrecursive version.\n ***************************************************************************/\n Value get(Key key) {\n Node x = root;\n while (x != null) {\n int cmp = key.compareTo(x.key);\n if (cmp < 0) x = x.left;\n else if (cmp > 0) x = x.right;\n else return x.val;\n }\n return null;\n }\n\n /***************************************************************************\n * Inorder traversal.\n ***************************************************************************/\n public Iterable keys() {\n Stack stack = new Stack();\n Queue queue = new Queue();\n Node x = root;\n while (x != null || !stack.isEmpty()) {\n if (x != null) {\n stack.push(x);\n x = x.left;\n }\n else {\n x = stack.pop();\n queue.enqueue(x.key);\n x = x.right;\n }\n }\n return queue;\n }\n\n\n /***************************************************************************\n * Test client.\n ***************************************************************************/\n public static void main(String[] args) {\n String[] a = StdIn.readAllStrings();\n int n = a.length;\n NonrecursiveBST st = new NonrecursiveBST();\n for (int i = 0; i < n; i++)\n st.put(a[i], i);\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n\n}\n", "support_files": [], "metadata": {"number": "3.2.13", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/NonrecursiveBST.java", "params": ["< tinyST.txt"], "dependencies": ["StdOut.java", "StdIn.java"]}} {"question": "Perfect balance. Write a program PerfectBalance.java that inserts a set of keys into an initially empty BST such that the tree produced is equivalent to binary search, in the sense that the sequence of compares done in the search for any key in the BST is the same as the sequence of compares used by binary search for the same set of keys. Hint: Put the median at the root and recursively build the left and right subtree.", "answer": "/******************************************************************************\n * Compilation: javac PerfectBalance.java\n * Execution: java PerfectBalance < input.txt\n * Dependencies: StdOut.java\n *\n * Read sequence of strings from standard input (no duplicates),\n * and insert into a BST so that BST is perfectly balanced.\n *\n * % java PerfectBalance\n * P E R F C T B I N A R Y S R H\n * N E B A C H F I R R P R T S Y\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\npublic class PerfectBalance {\n\n // precondition: a[] has no duplicates\n private static void perfect(BST bst, String[] a) {\n Arrays.sort(a);\n perfect(bst, a, 0, a.length - 1);\n StdOut.println();\n }\n\n // precondition: a[lo..hi] is sorted\n private static void perfect(BST bst, String[] a, int lo, int hi) {\n if (hi < lo) return;\n int mid = lo + (hi - lo) / 2;\n bst.put(a[mid], mid);\n StdOut.print(a[mid] + \" \");\n perfect(bst, a, lo, mid-1);\n perfect(bst, a, mid+1, hi);\n }\n\n public static void main(String[] args) {\n String[] words = StdIn.readAllStrings();\n BST bst = new BST();\n perfect(bst, words);\n }\n}\n", "support_files": [], "metadata": {"number": "3.2.25", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/PerfectBalance.java", "params": ["<put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses an (unbalanced) binary search tree.\n * The put, contains, remove, minimum,\n * maximum, ceiling, floor, select, and\n * rank operations each take Θ(n) time in the worst\n * case, where n is the number of key-value pairs.\n * The size and is-empty operations take Θ(1) time.\n * The keys method takes Θ(n) time in the worst case.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API, see {@link ST},\n * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation, see\n * Section 3.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BST, Value> {\n private Node root; // root of BST\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated data\n private Node left, right; // left and right subtrees\n private int size; // number of nodes in subtree\n\n public Node(Key key, Value val, int size) {\n this.key = key;\n this.val = val;\n this.size = size;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public BST() {\n }\n\n /**\n * Returns true if this symbol table is empty.\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return size(root);\n }\n\n // return number of key-value pairs in BST rooted at x\n private int size(Node node) {\n if (node == null) return 0;\n else return node.size;\n }\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls get() with a null key\");\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return get(node.left, key);\n else if (cmp > 0) return get(node.right, key);\n else return node.val;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"calls put() with a null key\");\n if (val == null) {\n delete(key);\n return;\n }\n root = put(root, key, val);\n assert check();\n }\n\n private Node put(Node node, Key key, Value val) {\n if (node == null) return new Node(key, val, 1);\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = put(node.left, key, val);\n else if (cmp > 0) node.right = put(node.right, key, val);\n else node.val = val;\n node.size = 1 + size(node.left) + size(node.right);\n return node;\n }\n\n\n /**\n * Removes the smallest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMin(root);\n assert check();\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the largest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMax(root);\n assert check();\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) return node.left;\n node.right = deleteMax(node.right);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls delete() with a null key\");\n root = delete(root, key);\n assert check();\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) return null;\n\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = delete(node.left, key);\n else if (cmp > 0) node.right = delete(node.right, key);\n else {\n if (node.right == null) return node.left;\n if (node.left == null) return node.right;\n Node temp = node;\n node = min(temp.right);\n node.right = deleteMin(temp.right);\n node.left = temp.left;\n }\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n\n /**\n * Returns the smallest key in the symbol table.\n *\n * @return the smallest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"calls min() with empty symbol table\");\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) return node;\n else return min(node.left);\n }\n\n /**\n * Returns the largest key in the symbol table.\n *\n * @return the largest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"calls max() with empty symbol table\");\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) return node;\n else return max(node.right);\n }\n\n /**\n * Returns the largest key in the symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in the symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls floor() with empty symbol table\");\n Node node = floor(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) return floor(node.left, key);\n Node t = floor(node.right, key);\n if (t != null) return t;\n else return node;\n }\n\n public Key floor2(Key key) {\n Key floor = floor2(root, key, null);\n if (floor == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return floor;\n\n }\n\n private Key floor2(Node node, Key key, Key champ) {\n if (node == null) return champ;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return floor2(node.left, key, champ);\n else if (cmp > 0) return floor2(node.right, key, node.key);\n else return node.key;\n }\n\n /**\n * Returns the smallest key in the symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in the symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls ceiling() with empty symbol table\");\n Node node = ceiling(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) {\n Node t = ceiling(node.left, key);\n if (t != null) return t;\n else return node;\n }\n return ceiling(node.right, key);\n }\n\n /**\n * Return the key in the symbol table of a given {@code rank}.\n * This key has the property that there are {@code rank} keys in\n * the symbol table that are smaller. In other words, this key is the\n * ({@code rank}+1)st smallest key in the symbol table.\n *\n * @param rank the order statistic\n * @return the key in the symbol table of given {@code rank}\n * @throws IllegalArgumentException unless {@code rank} is between 0 and\n * n\u20131\n */\n public Key select(int rank) {\n if (rank < 0 || rank >= size()) {\n throw new IllegalArgumentException(\"argument to select() is invalid: \" + rank);\n }\n return select(root, rank);\n }\n\n // Return key in BST rooted at x of given rank.\n // Precondition: rank is in legal range.\n private Key select(Node node, int rank) {\n if (node == null) return null;\n int leftSize = size(node.left);\n if (leftSize > rank) return select(node.left, rank);\n else if (leftSize < rank) return select(node.right, rank - leftSize - 1);\n else return node.key;\n }\n\n /**\n * Return the number of keys in the symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n return rank(key, root);\n }\n\n // Number of keys in the subtree less than key.\n private int rank(Key key, Node node) {\n if (node == null) return 0;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return rank(key, node.left);\n else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right);\n else return size(node.left);\n }\n\n /**\n * Returns all keys in the symbol table in ascending order,\n * as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table in ascending order\n */\n public Iterable keys() {\n if (isEmpty()) return new Queue();\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in the symbol table in the given range\n * in ascending order, as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive) in ascending order\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n keys(root, queue, lo, hi);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key lo, Key hi) {\n if (node == null) return;\n int cmplo = lo.compareTo(node.key);\n int cmphi = hi.compareTo(node.key);\n if (cmplo < 0) keys(node.left, queue, lo, hi);\n if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key);\n if (cmphi > 0) keys(node.right, queue, lo, hi);\n }\n\n /**\n * Returns the number of keys in the symbol table in the given range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns the height of the BST (for debugging).\n *\n * @return the height of the BST (a 1-node tree has height 0)\n */\n public int height() {\n return height(root);\n }\n private int height(Node node) {\n if (node == null) return -1;\n return 1 + Math.max(height(node.left), height(node.right));\n }\n\n /**\n * Returns the keys in the BST in level order (for debugging).\n *\n * @return the keys in the BST in level order traversal\n */\n public Iterable levelOrder() {\n Queue keys = new Queue();\n Queue queue = new Queue();\n queue.enqueue(root);\n while (!queue.isEmpty()) {\n Node node = queue.dequeue();\n if (node == null) continue;\n keys.enqueue(node.key);\n queue.enqueue(node.left);\n queue.enqueue(node.right);\n }\n return keys;\n }\n\n /*************************************************************************\n * Check integrity of BST data structure.\n ***************************************************************************/\n private boolean check() {\n if (!isBST()) StdOut.println(\"Not in symmetric order\");\n if (!isSizeConsistent()) StdOut.println(\"Subtree counts not consistent\");\n if (!isRankConsistent()) StdOut.println(\"Ranks not consistent\");\n return isBST() && isSizeConsistent() && isRankConsistent();\n }\n\n // does this binary tree satisfy symmetric order?\n // Note: this test also ensures that data structure is a binary tree since order is strict\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n // is the tree rooted at x a BST with all keys strictly between min and max\n // (if min or max is null, treat as empty constraint)\n // Credit: elegant solution due to Bob Dondero\n private boolean isBST(Node node, Key min, Key max) {\n if (node == null) return true;\n if (min != null && node.key.compareTo(min) <= 0) return false;\n if (max != null && node.key.compareTo(max) >= 0) return false;\n return isBST(node.left, min, node.key) && isBST(node.right, node.key, max);\n }\n\n // are the size fields correct?\n private boolean isSizeConsistent() { return isSizeConsistent(root); }\n private boolean isSizeConsistent(Node node) {\n if (node == null) return true;\n if (node.size != size(node.left) + size(node.right) + 1) return false;\n return isSizeConsistent(node.left) && isSizeConsistent(node.right);\n }\n\n // check that ranks are consistent\n private boolean isRankConsistent() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (Key key : keys())\n if (key.compareTo(select(rank(key))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BST st = new BST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n\n for (String s : st.levelOrder())\n StdOut.println(s + \" \" + st.get(s));\n\n StdOut.println();\n\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"number": "3.2.32", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java", "Queue.java"]}} {"question": "Select/rank check. Write a method isRankConsistent() in BST.java that checks, for all i from 0 to size() - 1 ,\nwhether i is equal to rank(select(i)) and, for all keys\nin the BST, whether key is equal to select(rank(key)) .", "answer": "/******************************************************************************\n * Compilation: javac BST.java\n * Execution: java BST\n * Dependencies: StdIn.java StdOut.java Queue.java\n * Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt\n *\n * A symbol table implemented with a binary search tree.\n *\n * % more tinyST.txt\n * S E A R C H E X A M P L E\n *\n * % java BST < tinyST.txt\n * A 8\n * C 4\n * E 12\n * H 5\n * L 11\n * M 9\n * P 10\n * R 3\n * S 0\n * X 7\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code BST} class represents an ordered symbol table of generic\n * key-value pairs.\n * It supports the usual put, get, contains,\n * delete, size, and is-empty methods.\n * It also provides ordered methods for finding the minimum,\n * maximum, floor, select, ceiling.\n * It also provides a keys method for iterating over all of the keys.\n * A symbol table implements the associative array abstraction:\n * when associating a value with a key that is already in the symbol table,\n * the convention is to replace the old value with the new value.\n * Unlike {@link java.util.Map}, this class uses the convention that\n * values cannot be {@code null}\u2014setting the\n * value associated with a key to {@code null} is equivalent to deleting the key\n * from the symbol table.\n *

\n * It requires that\n * the key type implements the {@code Comparable} interface and calls the\n * {@code compareTo()} and method to compare two keys. It does not call either\n * {@code equals()} or {@code hashCode()}.\n *

\n * This implementation uses an (unbalanced) binary search tree.\n * The put, contains, remove, minimum,\n * maximum, ceiling, floor, select, and\n * rank operations each take Θ(n) time in the worst\n * case, where n is the number of key-value pairs.\n * The size and is-empty operations take Θ(1) time.\n * The keys method takes Θ(n) time in the worst case.\n * Construction takes Θ(1) time.\n *

\n * For alternative implementations of the symbol table API, see {@link ST},\n * {@link BinarySearchST}, {@link SequentialSearchST}, {@link RedBlackBST},\n * {@link SeparateChainingHashST}, and {@link LinearProbingHashST},\n * For additional documentation, see\n * Section 3.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BST, Value> {\n private Node root; // root of BST\n\n private class Node {\n private Key key; // sorted by key\n private Value val; // associated data\n private Node left, right; // left and right subtrees\n private int size; // number of nodes in subtree\n\n public Node(Key key, Value val, int size) {\n this.key = key;\n this.val = val;\n this.size = size;\n }\n }\n\n /**\n * Initializes an empty symbol table.\n */\n public BST() {\n }\n\n /**\n * Returns true if this symbol table is empty.\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\n */\n public boolean isEmpty() {\n return size() == 0;\n }\n\n /**\n * Returns the number of key-value pairs in this symbol table.\n * @return the number of key-value pairs in this symbol table\n */\n public int size() {\n return size(root);\n }\n\n // return number of key-value pairs in BST rooted at x\n private int size(Node node) {\n if (node == null) return 0;\n else return node.size;\n }\n\n /**\n * Does this symbol table contain the given key?\n *\n * @param key the key\n * @return {@code true} if this symbol table contains {@code key} and\n * {@code false} otherwise\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public boolean contains(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to contains() is null\");\n return get(key) != null;\n }\n\n /**\n * Returns the value associated with the given key.\n *\n * @param key the key\n * @return the value associated with the given key if the key is in the symbol table\n * and {@code null} if the key is not in the symbol table\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Value get(Key key) {\n return get(root, key);\n }\n\n private Value get(Node node, Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls get() with a null key\");\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return get(node.left, key);\n else if (cmp > 0) return get(node.right, key);\n else return node.val;\n }\n\n /**\n * Inserts the specified key-value pair into the symbol table, overwriting the old\n * value with the new value if the symbol table already contains the specified key.\n * Deletes the specified key (and its associated value) from this symbol table\n * if the specified value is {@code null}.\n *\n * @param key the key\n * @param val the value\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void put(Key key, Value val) {\n if (key == null) throw new IllegalArgumentException(\"calls put() with a null key\");\n if (val == null) {\n delete(key);\n return;\n }\n root = put(root, key, val);\n assert check();\n }\n\n private Node put(Node node, Key key, Value val) {\n if (node == null) return new Node(key, val, 1);\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = put(node.left, key, val);\n else if (cmp > 0) node.right = put(node.right, key, val);\n else node.val = val;\n node.size = 1 + size(node.left) + size(node.right);\n return node;\n }\n\n\n /**\n * Removes the smallest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMin() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMin(root);\n assert check();\n }\n\n private Node deleteMin(Node node) {\n if (node.left == null) return node.right;\n node.left = deleteMin(node.left);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the largest key and associated value from the symbol table.\n *\n * @throws NoSuchElementException if the symbol table is empty\n */\n public void deleteMax() {\n if (isEmpty()) throw new NoSuchElementException(\"Symbol table underflow\");\n root = deleteMax(root);\n assert check();\n }\n\n private Node deleteMax(Node node) {\n if (node.right == null) return node.left;\n node.right = deleteMax(node.right);\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n /**\n * Removes the specified key and its associated value from this symbol table\n * (if the key is in this symbol table).\n *\n * @param key the key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public void delete(Key key) {\n if (key == null) throw new IllegalArgumentException(\"calls delete() with a null key\");\n root = delete(root, key);\n assert check();\n }\n\n private Node delete(Node node, Key key) {\n if (node == null) return null;\n\n int cmp = key.compareTo(node.key);\n if (cmp < 0) node.left = delete(node.left, key);\n else if (cmp > 0) node.right = delete(node.right, key);\n else {\n if (node.right == null) return node.left;\n if (node.left == null) return node.right;\n Node temp = node;\n node = min(temp.right);\n node.right = deleteMin(temp.right);\n node.left = temp.left;\n }\n node.size = size(node.left) + size(node.right) + 1;\n return node;\n }\n\n\n /**\n * Returns the smallest key in the symbol table.\n *\n * @return the smallest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key min() {\n if (isEmpty()) throw new NoSuchElementException(\"calls min() with empty symbol table\");\n return min(root).key;\n }\n\n private Node min(Node node) {\n if (node.left == null) return node;\n else return min(node.left);\n }\n\n /**\n * Returns the largest key in the symbol table.\n *\n * @return the largest key in the symbol table\n * @throws NoSuchElementException if the symbol table is empty\n */\n public Key max() {\n if (isEmpty()) throw new NoSuchElementException(\"calls max() with empty symbol table\");\n return max(root).key;\n }\n\n private Node max(Node node) {\n if (node.right == null) return node;\n else return max(node.right);\n }\n\n /**\n * Returns the largest key in the symbol table less than or equal to {@code key}.\n *\n * @param key the key\n * @return the largest key in the symbol table less than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key floor(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to floor() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls floor() with empty symbol table\");\n Node node = floor(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return node.key;\n }\n\n private Node floor(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) return floor(node.left, key);\n Node t = floor(node.right, key);\n if (t != null) return t;\n else return node;\n }\n\n public Key floor2(Key key) {\n Key floor = floor2(root, key, null);\n if (floor == null) throw new NoSuchElementException(\"argument to floor() is too small\");\n else return floor;\n\n }\n\n private Key floor2(Node node, Key key, Key champ) {\n if (node == null) return champ;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return floor2(node.left, key, champ);\n else if (cmp > 0) return floor2(node.right, key, node.key);\n else return node.key;\n }\n\n /**\n * Returns the smallest key in the symbol table greater than or equal to {@code key}.\n *\n * @param key the key\n * @return the smallest key in the symbol table greater than or equal to {@code key}\n * @throws NoSuchElementException if there is no such key\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public Key ceiling(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to ceiling() is null\");\n if (isEmpty()) throw new NoSuchElementException(\"calls ceiling() with empty symbol table\");\n Node node = ceiling(root, key);\n if (node == null) throw new NoSuchElementException(\"argument to ceiling() is too large\");\n else return node.key;\n }\n\n private Node ceiling(Node node, Key key) {\n if (node == null) return null;\n int cmp = key.compareTo(node.key);\n if (cmp == 0) return node;\n if (cmp < 0) {\n Node t = ceiling(node.left, key);\n if (t != null) return t;\n else return node;\n }\n return ceiling(node.right, key);\n }\n\n /**\n * Return the key in the symbol table of a given {@code rank}.\n * This key has the property that there are {@code rank} keys in\n * the symbol table that are smaller. In other words, this key is the\n * ({@code rank}+1)st smallest key in the symbol table.\n *\n * @param rank the order statistic\n * @return the key in the symbol table of given {@code rank}\n * @throws IllegalArgumentException unless {@code rank} is between 0 and\n * n\u20131\n */\n public Key select(int rank) {\n if (rank < 0 || rank >= size()) {\n throw new IllegalArgumentException(\"argument to select() is invalid: \" + rank);\n }\n return select(root, rank);\n }\n\n // Return key in BST rooted at x of given rank.\n // Precondition: rank is in legal range.\n private Key select(Node node, int rank) {\n if (node == null) return null;\n int leftSize = size(node.left);\n if (leftSize > rank) return select(node.left, rank);\n else if (leftSize < rank) return select(node.right, rank - leftSize - 1);\n else return node.key;\n }\n\n /**\n * Return the number of keys in the symbol table strictly less than {@code key}.\n *\n * @param key the key\n * @return the number of keys in the symbol table strictly less than {@code key}\n * @throws IllegalArgumentException if {@code key} is {@code null}\n */\n public int rank(Key key) {\n if (key == null) throw new IllegalArgumentException(\"argument to rank() is null\");\n return rank(key, root);\n }\n\n // Number of keys in the subtree less than key.\n private int rank(Key key, Node node) {\n if (node == null) return 0;\n int cmp = key.compareTo(node.key);\n if (cmp < 0) return rank(key, node.left);\n else if (cmp > 0) return 1 + size(node.left) + rank(key, node.right);\n else return size(node.left);\n }\n\n /**\n * Returns all keys in the symbol table in ascending order,\n * as an {@code Iterable}.\n * To iterate over all of the keys in the symbol table named {@code st},\n * use the foreach notation: {@code for (Key key : st.keys())}.\n *\n * @return all keys in the symbol table in ascending order\n */\n public Iterable keys() {\n if (isEmpty()) return new Queue();\n return keys(min(), max());\n }\n\n /**\n * Returns all keys in the symbol table in the given range\n * in ascending order, as an {@code Iterable}.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return all keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive) in ascending order\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public Iterable keys(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to keys() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to keys() is null\");\n\n Queue queue = new Queue();\n keys(root, queue, lo, hi);\n return queue;\n }\n\n private void keys(Node node, Queue queue, Key lo, Key hi) {\n if (node == null) return;\n int cmplo = lo.compareTo(node.key);\n int cmphi = hi.compareTo(node.key);\n if (cmplo < 0) keys(node.left, queue, lo, hi);\n if (cmplo <= 0 && cmphi >= 0) queue.enqueue(node.key);\n if (cmphi > 0) keys(node.right, queue, lo, hi);\n }\n\n /**\n * Returns the number of keys in the symbol table in the given range.\n *\n * @param lo minimum endpoint\n * @param hi maximum endpoint\n * @return the number of keys in the symbol table between {@code lo}\n * (inclusive) and {@code hi} (inclusive)\n * @throws IllegalArgumentException if either {@code lo} or {@code hi}\n * is {@code null}\n */\n public int size(Key lo, Key hi) {\n if (lo == null) throw new IllegalArgumentException(\"first argument to size() is null\");\n if (hi == null) throw new IllegalArgumentException(\"second argument to size() is null\");\n\n if (lo.compareTo(hi) > 0) return 0;\n if (contains(hi)) return rank(hi) - rank(lo) + 1;\n else return rank(hi) - rank(lo);\n }\n\n /**\n * Returns the height of the BST (for debugging).\n *\n * @return the height of the BST (a 1-node tree has height 0)\n */\n public int height() {\n return height(root);\n }\n private int height(Node node) {\n if (node == null) return -1;\n return 1 + Math.max(height(node.left), height(node.right));\n }\n\n /**\n * Returns the keys in the BST in level order (for debugging).\n *\n * @return the keys in the BST in level order traversal\n */\n public Iterable levelOrder() {\n Queue keys = new Queue();\n Queue queue = new Queue();\n queue.enqueue(root);\n while (!queue.isEmpty()) {\n Node node = queue.dequeue();\n if (node == null) continue;\n keys.enqueue(node.key);\n queue.enqueue(node.left);\n queue.enqueue(node.right);\n }\n return keys;\n }\n\n /*************************************************************************\n * Check integrity of BST data structure.\n ***************************************************************************/\n private boolean check() {\n if (!isBST()) StdOut.println(\"Not in symmetric order\");\n if (!isSizeConsistent()) StdOut.println(\"Subtree counts not consistent\");\n if (!isRankConsistent()) StdOut.println(\"Ranks not consistent\");\n return isBST() && isSizeConsistent() && isRankConsistent();\n }\n\n // does this binary tree satisfy symmetric order?\n // Note: this test also ensures that data structure is a binary tree since order is strict\n private boolean isBST() {\n return isBST(root, null, null);\n }\n\n // is the tree rooted at x a BST with all keys strictly between min and max\n // (if min or max is null, treat as empty constraint)\n // Credit: elegant solution due to Bob Dondero\n private boolean isBST(Node node, Key min, Key max) {\n if (node == null) return true;\n if (min != null && node.key.compareTo(min) <= 0) return false;\n if (max != null && node.key.compareTo(max) >= 0) return false;\n return isBST(node.left, min, node.key) && isBST(node.right, node.key, max);\n }\n\n // are the size fields correct?\n private boolean isSizeConsistent() { return isSizeConsistent(root); }\n private boolean isSizeConsistent(Node node) {\n if (node == null) return true;\n if (node.size != size(node.left) + size(node.right) + 1) return false;\n return isSizeConsistent(node.left) && isSizeConsistent(node.right);\n }\n\n // check that ranks are consistent\n private boolean isRankConsistent() {\n for (int i = 0; i < size(); i++)\n if (i != rank(select(i))) return false;\n for (Key key : keys())\n if (key.compareTo(select(rank(key))) != 0) return false;\n return true;\n }\n\n\n /**\n * Unit tests the {@code BST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n BST st = new BST();\n for (int i = 0; !StdIn.isEmpty(); i++) {\n String key = StdIn.readString();\n st.put(key, i);\n }\n\n for (String s : st.levelOrder())\n StdOut.println(s + \" \" + st.get(s));\n\n StdOut.println();\n\n for (String s : st.keys())\n StdOut.println(s + \" \" + st.get(s));\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/32bst/tinyST.txt"], "metadata": {"number": "3.2.33", "code_execution": true, "url": "https://algs4.cs.princeton.edu/32bst/BST.java", "params": ["< tinyST.txt"], "dependencies": ["StdIn.java", "StdOut.java", "Queue.java"]}} {"question": "Create a copy constructor for Graph.java that takes as input a graph G and creates and initializes a new copy of the graph. Any changes a client makes to G should not affect the newly created graph. ", "answer": "/******************************************************************************\n * Compilation: javac Graph.java\n * Execution: java Graph input.txt\n * Dependencies: Bag.java Stack.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt\n * https://algs4.cs.princeton.edu/41graph/mediumG.txt\n * https://algs4.cs.princeton.edu/41graph/largeG.txt\n *\n * A graph, implemented using an array of sets.\n * Parallel edges and self-loops allowed.\n *\n * % java Graph tinyG.txt\n * 13 vertices, 13 edges\n * 0: 6 2 1 5\n * 1: 0\n * 2: 0\n * 3: 5 4\n * 4: 5 6 3\n * 5: 3 4 0\n * 6: 0 4\n * 7: 8\n * 8: 7\n * 9: 11 10 12\n * 10: 9\n * 11: 9 12\n * 12: 11 9\n *\n * % java Graph mediumG.txt\n * 250 vertices, 1273 edges\n * 0: 225 222 211 209 204 202 191 176 163 160 149 114 97 80 68 59 58 49 44 24 15\n * 1: 220 203 200 194 189 164 150 130 107 72\n * 2: 141 110 108 86 79 51 42 18 14\n * ...\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code Graph} class represents an undirected graph of vertices\n * named 0 through V \u2013 1.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the vertices adjacent with a given vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the vertices returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty graph with V vertices takes\n * Θ(V) time; constructing a graph with E edges\n * and V vertices takes Θ(E + V) time.\n *

\n * For additional documentation, see\n * Section 4.1\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Graph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty graph with {@code V} vertices and 0 edges.\n * param V the number of vertices\n *\n * @param V number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public Graph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a graph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices, with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n * @throws IllegalArgumentException if the input stream is in the wrong format\n */\n public Graph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Graph must be non-negative\");\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"number of edges in a Graph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n addEdge(v, w);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in Graph constructor\", e);\n }\n }\n\n\n /**\n * Initializes a new graph that is a deep copy of {@code graph}.\n *\n * @param graph the graph to copy\n * @throws IllegalArgumentException if {@code graph} is {@code null}\n */\n public Graph(Graph graph) {\n this.V = graph.V();\n this.E = graph.E();\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n\n // update adjacency lists\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n for (int v = 0; v < graph.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (int w : graph.adj[v]) {\n reverse.push(w);\n }\n for (int w : reverse) {\n adj[v].add(w);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this graph.\n *\n * @return the number of vertices in this graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this graph.\n *\n * @return the number of edges in this graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge v-w to this graph.\n *\n * @param v one vertex in the edge\n * @param w the other vertex in the edge\n * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V}\n */\n public void addEdge(int v, int w) {\n validateVertex(v);\n validateVertex(w);\n E++;\n adj[v].add(w);\n adj[w].add(v);\n }\n\n\n /**\n * Returns the vertices adjacent with vertex {@code v}.\n *\n * @param v the vertex\n * @return the vertices adjacent with vertex {@code v}, as an iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n\n /**\n * Returns a string representation of this graph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" vertices, \" + E + \" edges \" + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (int w : adj[v]) {\n s.append(w + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n int selfLoops = 0;\n for (int v = 0; v < V; v++) {\n for (int w : adj[v]) {\n if (v < w) {\n s.append(v + \" -- \" + w + NEWLINE);\n }\n else if (v == w) {\n // include only one copy of each self loop (self loops will be consecutive)\n if (selfLoops % 2 == 0) {\n s.append(v + \" -- \" + w + NEWLINE);\n }\n selfLoops++;\n }\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code Graph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Graph graph = new Graph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/41graph/mediumG.txt", "https://algs4.cs.princeton.edu/41graph/largeG.txt", "https://algs4.cs.princeton.edu/41graph/tinyG.txt"], "metadata": {"number": "4.1.3", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/Graph.java", "params": ["mediumG.txt", "tinyG.txt"], "dependencies": ["Bag.java", "Stack.java", "In.java", "StdOut.java"]}} {"question": "Add a distTo() method to BreadthFirstPaths.java, which returns the number of edges on the shortest path from the source to a given vertex. A distTo() query should run in constant time.", "answer": "/******************************************************************************\n * Compilation: javac BreadthFirstPaths.java\n * Execution: java BreadthFirstPaths G s\n * Dependencies: Graph.java Queue.java Stack.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/41graph/tinyCG.txt\n * https://algs4.cs.princeton.edu/41graph/tinyG.txt\n * https://algs4.cs.princeton.edu/41graph/mediumG.txt\n * https://algs4.cs.princeton.edu/41graph/largeG.txt\n *\n * Run breadth first search on an undirected graph.\n * Runs in O(E + V) time.\n *\n * % java Graph tinyCG.txt\n * 6 8\n * 0: 2 1 5\n * 1: 0 2\n * 2: 0 1 3 4\n * 3: 5 4 2\n * 4: 3 2\n * 5: 3 0\n *\n * % java BreadthFirstPaths tinyCG.txt 0\n * 0 to 0 (0): 0\n * 0 to 1 (1): 0-1\n * 0 to 2 (1): 0-2\n * 0 to 3 (2): 0-2-3\n * 0 to 4 (2): 0-2-4\n * 0 to 5 (1): 0-5\n *\n * % java BreadthFirstPaths largeG.txt 0\n * 0 to 0 (0): 0\n * 0 to 1 (418): 0-932942-474885-82707-879889-971961-...\n * 0 to 2 (323): 0-460790-53370-594358-780059-287921-...\n * 0 to 3 (168): 0-713461-75230-953125-568284-350405-...\n * 0 to 4 (144): 0-460790-53370-310931-440226-380102-...\n * 0 to 5 (566): 0-932942-474885-82707-879889-971961-...\n * 0 to 6 (349): 0-932942-474885-82707-879889-971961-...\n *\n ******************************************************************************/\n\n\n/**\n * The {@code BreadthFirstPaths} class represents a data type for finding\n * shortest paths (number of edges) from a source vertex s\n * (or a set of source vertices)\n * to every other vertex in an undirected graph.\n *

\n * This implementation uses breadth-first search.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and E\n * is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the graph).\n *

\n * For additional documentation,\n * see Section 4.1\n * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BreadthFirstPaths {\n private static final int INFINITY = Integer.MAX_VALUE;\n private boolean[] marked; // marked[v] = is there an s-v path\n private int[] edgeTo; // edgeTo[v] = previous edge on shortest s-v path\n private int[] distTo; // distTo[v] = number of edges shortest s-v path\n\n /**\n * Computes the shortest path between the source vertex {@code s}\n * and every other vertex in the undirected graph {@code graph}.\n * @param graph the graph\n * @param s the source vertex\n * @throws IllegalArgumentException unless {@code 0 <= s < V}\n */\n public BreadthFirstPaths(Graph graph, int s) {\n marked = new boolean[graph.V()];\n distTo = new int[graph.V()];\n edgeTo = new int[graph.V()];\n validateVertex(s);\n bfs(graph, s);\n\n assert check(graph, s);\n }\n\n /**\n * Computes the shortest path between any one of the source vertices in {@code sources}\n * and every other vertex in {@code graph}.\n * @param graph the graph\n * @param sources the source vertices\n * @throws IllegalArgumentException if {@code sources} is {@code null}\n * @throws IllegalArgumentException if {@code sources} contains no vertices\n * @throws IllegalArgumentException unless {@code 0 <= s < V} for each vertex\n * {@code s} in {@code sources}\n */\n public BreadthFirstPaths(Graph graph, Iterable sources) {\n marked = new boolean[graph.V()];\n distTo = new int[graph.V()];\n edgeTo = new int[graph.V()];\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = INFINITY;\n validateVertices(sources);\n bfs(graph, sources);\n }\n\n\n // breadth-first search from a single source\n private void bfs(Graph graph, int s) {\n Queue q = new Queue();\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = INFINITY;\n distTo[s] = 0;\n marked[s] = true;\n q.enqueue(s);\n\n while (!q.isEmpty()) {\n int v = q.dequeue();\n for (int w : graph.adj(v)) {\n if (!marked[w]) {\n edgeTo[w] = v;\n distTo[w] = distTo[v] + 1;\n marked[w] = true;\n q.enqueue(w);\n }\n }\n }\n }\n\n // breadth-first search from multiple sources\n private void bfs(Graph graph, Iterable sources) {\n Queue q = new Queue();\n for (int s : sources) {\n marked[s] = true;\n distTo[s] = 0;\n q.enqueue(s);\n }\n while (!q.isEmpty()) {\n int v = q.dequeue();\n for (int w : graph.adj(v)) {\n if (!marked[w]) {\n edgeTo[w] = v;\n distTo[w] = distTo[v] + 1;\n marked[w] = true;\n q.enqueue(w);\n }\n }\n }\n }\n\n /**\n * Is there a path between the source vertex {@code s} (or sources) and vertex {@code v}?\n * @param v the vertex\n * @return {@code true} if there is a path, and {@code false} otherwise\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public boolean hasPathTo(int v) {\n validateVertex(v);\n return marked[v];\n }\n\n /**\n * Returns the number of edges in a shortest path between the source vertex {@code s}\n * (or sources) and vertex {@code v}?\n * @param v the vertex\n * @return the number of edges in such a shortest path\n * (or {@code Integer.MAX_VALUE} if there is no such path)\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int distTo(int v) {\n validateVertex(v);\n return distTo[v];\n }\n\n /**\n * Returns a shortest path between the source vertex {@code s} (or sources)\n * and {@code v}, or {@code null} if no such path.\n * @param v the vertex\n * @return the sequence of vertices on a shortest path, as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable pathTo(int v) {\n validateVertex(v);\n if (!hasPathTo(v)) return null;\n Stack path = new Stack();\n int x;\n for (x = v; distTo[x] != 0; x = edgeTo[x])\n path.push(x);\n path.push(x);\n return path;\n }\n\n\n // check optimality conditions for single source\n private boolean check(Graph graph, int s) {\n\n // check that the distance of s = 0\n if (distTo[s] != 0) {\n StdOut.println(\"distance of source \" + s + \" to itself = \" + distTo[s]);\n return false;\n }\n\n // check that for each edge v-w dist[w] <= dist[v] + 1\n // provided v is reachable from s\n for (int v = 0; v < graph.V(); v++) {\n for (int w : graph.adj(v)) {\n if (hasPathTo(v) != hasPathTo(w)) {\n StdOut.println(\"edge \" + v + \"-\" + w);\n StdOut.println(\"hasPathTo(\" + v + \") = \" + hasPathTo(v));\n StdOut.println(\"hasPathTo(\" + w + \") = \" + hasPathTo(w));\n return false;\n }\n if (hasPathTo(v) && (distTo[w] > distTo[v] + 1)) {\n StdOut.println(\"edge \" + v + \"-\" + w);\n StdOut.println(\"distTo[\" + v + \"] = \" + distTo[v]);\n StdOut.println(\"distTo[\" + w + \"] = \" + distTo[w]);\n return false;\n }\n }\n }\n\n // check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1\n // provided v is reachable from s\n for (int w = 0; w < graph.V(); w++) {\n if (!hasPathTo(w) || w == s) continue;\n int v = edgeTo[w];\n if (distTo[w] != distTo[v] + 1) {\n StdOut.println(\"shortest path edge \" + v + \"-\" + w);\n StdOut.println(\"distTo[\" + v + \"] = \" + distTo[v]);\n StdOut.println(\"distTo[\" + w + \"] = \" + distTo[w]);\n return false;\n }\n }\n\n return true;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = marked.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n // throw an IllegalArgumentException if vertices is null, has zero vertices,\n // or has a vertex not between 0 and V-1\n private void validateVertices(Iterable vertices) {\n if (vertices == null) {\n throw new IllegalArgumentException(\"argument is null\");\n }\n int vertexCount = 0;\n for (Integer v : vertices) {\n vertexCount++;\n if (v == null) {\n throw new IllegalArgumentException(\"vertex is null\");\n }\n validateVertex(v);\n }\n if (vertexCount == 0) {\n throw new IllegalArgumentException(\"zero vertices\");\n }\n }\n\n /**\n * Unit tests the {@code BreadthFirstPaths} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Graph graph = new Graph(in);\n // StdOut.println(graph);\n\n int s = Integer.parseInt(args[1]);\n BreadthFirstPaths bfs = new BreadthFirstPaths(graph, s);\n\n for (int v = 0; v < graph.V(); v++) {\n if (bfs.hasPathTo(v)) {\n StdOut.printf(\"%d to %d (%d): \", s, v, bfs.distTo(v));\n for (int x : bfs.pathTo(v)) {\n if (x == s) StdOut.print(x);\n else StdOut.print(\"-\" + x);\n }\n StdOut.println();\n }\n\n else {\n StdOut.printf(\"%d to %d (-): not connected\", s, v);\n }\n\n }\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/41graph/largeG.txt", "https://algs4.cs.princeton.edu/41graph/mediumG.txt", "https://algs4.cs.princeton.edu/41graph/tinyG.txt", "https://algs4.cs.princeton.edu/41graph/tinyCG.txt"], "metadata": {"number": "4.1.13", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/BreadthFirstPaths.java", "params": ["tinyCG.txt 0", "mediumG.txt 0", "tinyG.txt 0"], "dependencies": ["Graph.java", "Queue.java", "Stack.java", "StdOut.java"]}} {"question": "Write a program BaconHistogram.java that prints a histogram of Kevin Bacon numbers, indicating how many performers from movies.txt have a Bacon number of 0, 1, 2, 3, ... . Include a category for those who have an infinite number (not connected to Kevin Bacon).", "answer": "/******************************************************************************\n * Compilation: javac BaconHistogram.java\n * Execution: java BaconHistogram input.txt delimiter actor\n * Dependencies: SymbolGraph.java Graph.java In.java BreadthFirstPaths.java\n * Data files: https://algs4.cs.princeton.edu/41graph/movies.txt\n *\n * Reads in a data file containing movie records (a movie followed by a list\n * of actors appearing in that movie), and runs breadth first search to\n * find the shortest distance from the source (Kevin Bacon) to each other\n * actor and movie. After computing the Kevin Bacon numbers, the programs\n * prints a histogram of the number of actors with each Kevin Bacon number.\n *\n *\n * % java BaconHistogram movies.txt \"/\" \"Bacon, Kevin\"\n * 0 1\n * 1 1324\n * 2 70717\n * 3 40862\n * 4 1591\n * 5 125\n * Inf 0\n *\n * Remark: hard to identify actors with infinite bacon numbers because\n * we can't tell whether an unreachable vertex is an actor or movie.\n *\n ******************************************************************************/\n\npublic class BaconHistogram {\n public static void main(String[] args) {\n String filename = args[0];\n String delimiter = args[1];\n String source = args[2];\n\n SymbolGraph sg = new SymbolGraph(filename, delimiter);\n Graph G = sg.graph();\n if (!sg.contains(source)) {\n StdOut.println(source + \" not in database.\");\n return;\n }\n\n // run breadth-first search from s\n int s = sg.indexOf(source);\n BreadthFirstPaths bfs = new BreadthFirstPaths(G, s);\n\n\n // compute histogram of Kevin Bacon numbers - 100 for infinity\n int MAX_BACON = 100;\n int[] hist = new int[MAX_BACON + 1];\n for (int v = 0; v < G.V(); v++) {\n int bacon = Math.min(MAX_BACON, bfs.distTo(v));\n hist[bacon]++;\n\n // to print actors and movies with large bacon numbers\n if (bacon/2 >= 7 && bacon < MAX_BACON)\n StdOut.printf(\"%d %s\", bacon/2, sg.nameOf(v));\n }\n\n // print out histogram - even indices are actors\n for (int i = 0; i < MAX_BACON; i += 2) {\n if (hist[i] == 0) break;\n StdOut.printf(\"%3d %8d\", i/2, hist[i]);\n }\n StdOut.printf(\"Inf %8d\", hist[MAX_BACON]);\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/41graph/movies.txt"], "metadata": {"number": "4.1.23", "code_execution": true, "url": "https://algs4.cs.princeton.edu/41graph/BaconHistogram.java", "params": ["movies.txt \"/\" \"Bacon, Kevin\""], "dependencies": ["SymbolGraph.java", "Graph.java", "In.java", "BreadthFirstPaths.java"]}} {"question": "Create a copy constructor for Digraph that takes as input a digraph G and creates and initializes a new copy of the digraph. Any changes a client makes to G should not affect the newly created digraph. ", "answer": "/******************************************************************************\n * Compilation: javac Digraph.java\n * Execution: java Digraph filename.txt\n * Dependencies: Bag.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/42digraph/tinyDG.txt\n * https://algs4.cs.princeton.edu/42digraph/mediumDG.txt\n * https://algs4.cs.princeton.edu/42digraph/largeDG.txt\n *\n * A graph, implemented using an array of lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java Digraph tinyDG.txt\n * 13 vertices, 22 edges\n * 0: 5 1\n * 1:\n * 2: 0 3\n * 3: 5 2\n * 4: 3 2\n * 5: 4\n * 6: 9 4 8 0\n * 7: 6 9\n * 8: 6\n * 9: 11 10\n * 10: 12\n * 11: 4 12\n * 12: 9\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code Digraph} class represents a directed graph of vertices\n * named 0 through V - 1.\n * It supports the following two primary operations: add an edge to the digraph,\n * iterate over all of the vertices adjacent from a given vertex.\n * It also provides\n * methods for returning the indegree or outdegree of a vertex,\n * the number of vertices V in the digraph,\n * the number of edges E in the digraph, and the reverse digraph.\n * Parallel edges and self-loops are permitted.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * The reverse() method takes Θ(E + V) time\n * and space; all other instance methods take Θ(1) time. (Though, iterating over\n * the vertices returned by {@link #adj(int)} takes time proportional\n * to the outdegree of the vertex.)\n * Constructing an empty digraph with V vertices takes\n * Θ(V) time; constructing a digraph with E edges\n * and V vertices takes Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\n\npublic class Digraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V; // number of vertices in this digraph\n private int E; // number of edges in this digraph\n private Bag[] adj; // adj[v] = adjacency list for vertex v\n private int[] indegree; // indegree[v] = indegree of vertex v\n\n /**\n * Initializes an empty digraph with V vertices.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public Digraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n this.V = V;\n this.E = 0;\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a digraph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices, with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n * @throws IllegalArgumentException if the input stream is in the wrong format\n */\n public Digraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Digraph must be non-negative\");\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"number of edges in a Digraph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n addEdge(v, w);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in Digraph constructor\", e);\n }\n }\n\n /**\n * Initializes a new digraph that is a deep copy of the specified digraph.\n *\n * @param digraph the digraph to copy\n * @throws IllegalArgumentException if {@code digraph} is {@code null}\n */\n public Digraph(Digraph digraph) {\n if (digraph == null) throw new IllegalArgumentException(\"argument is null\");\n\n this.V = digraph.V();\n this.E = digraph.E();\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n\n // update indegrees\n indegree = new int[V];\n for (int v = 0; v < V; v++)\n this.indegree[v] = digraph.indegree(v);\n\n // update adjacency lists\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n for (int v = 0; v < digraph.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (int w : digraph.adj[v]) {\n reverse.push(w);\n }\n for (int w : reverse) {\n adj[v].add(w);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this digraph.\n *\n * @return the number of vertices in this digraph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this digraph.\n *\n * @return the number of edges in this digraph\n */\n public int E() {\n return E;\n }\n\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the directed edge v\u2192w to this digraph.\n *\n * @param v the tail vertex\n * @param w the head vertex\n * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V}\n */\n public void addEdge(int v, int w) {\n validateVertex(v);\n validateVertex(w);\n adj[v].add(w);\n indegree[w]++;\n E++;\n }\n\n /**\n * Returns the vertices adjacent from vertex {@code v} in this digraph.\n *\n * @param v the vertex\n * @return the vertices adjacent from vertex {@code v} in this digraph, as an iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the number of directed edges incident from vertex {@code v}.\n * This is known as the outdegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the outdegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int outdegree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns the number of directed edges incident to vertex {@code v}.\n * This is known as the indegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the indegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int indegree(int v) {\n validateVertex(v);\n return indegree[v];\n }\n\n /**\n * Returns the reverse of the digraph.\n *\n * @return the reverse of the digraph\n */\n public Digraph reverse() {\n Digraph reverse = new Digraph(V);\n for (int v = 0; v < V; v++) {\n for (int w : adj(v)) {\n reverse.addEdge(w, v);\n }\n }\n return reverse;\n }\n\n /**\n * Returns a string representation of the graph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" vertices, \" + E + \" edges \" + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(String.format(\"%d: \", v));\n for (int w : adj[v]) {\n s.append(String.format(\"%d \", w));\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this digraph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the digraph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this digraph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"digraph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal]\" + NEWLINE);\n for (int v = 0; v < V; v++) {\n for (int w : adj[v]) {\n s.append(v + \" -> \" + w + NEWLINE);\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code Digraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n Digraph graph = new Digraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/42digraph/largeDG.txt", "https://algs4.cs.princeton.edu/42digraph/tinyDG.txt", "https://algs4.cs.princeton.edu/42digraph/mediumDG.txt"], "metadata": {"number": "4.2.3", "code_execution": true, "url": "https://algs4.cs.princeton.edu/42digraph/Digraph.java", "params": ["tinyDG.txt", "mediumDG.txt"], "dependencies": ["Bag.java", "In.java", "StdOut.java"]}} {"question": "Implement the constructor for EdgeWeightedGraph.java that reads an edge-weighted graph from an input stream.", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedGraph.java\n * Execution: java EdgeWeightedGraph filename.txt\n * Dependencies: Bag.java Edge.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * An edge-weighted undirected graph, implemented using adjacency lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java EdgeWeightedGraph tinyEWG.txt\n * 8 16\n * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000\n * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000\n * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000\n * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000\n * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000\n * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000\n * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000\n * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedGraph} class represents an edge-weighted\n * graph of vertices named 0 through V \u2013 1, where each\n * undirected edge is of type {@link Edge} and has a real-valued weight.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the edges incident with a vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty edge-weighted graph with V vertices takes\n * Θ(V) time; constructing an edge-weighted graph with\n * E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedGraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedGraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a random edge-weighted graph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedGraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(0, 100);\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted graph from an input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedGraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n\n try {\n V = in.readInt();\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedGraph constructor\", e);\n }\n\n }\n\n /**\n * Initializes a new edge-weighted graph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted graph to copy\n */\n public EdgeWeightedGraph(EdgeWeightedGraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (Edge e : G.adj[v]) {\n reverse.push(e);\n }\n for (Edge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n\n /**\n * Returns the number of vertices in this edge-weighted graph.\n *\n * @return the number of vertices in this edge-weighted graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted graph.\n *\n * @return the number of edges in this edge-weighted graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge {@code e} to this edge-weighted graph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1}\n */\n public void addEdge(Edge e) {\n int v = e.either();\n int w = e.other(v);\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n adj[w].add(e);\n E++;\n }\n\n /**\n * Returns the edges incident with vertex {@code v}.\n *\n * @param v the vertex\n * @return the edges incident with vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns all edges in this edge-weighted graph.\n * To iterate over the edges in this edge-weighted graph, use foreach notation:\n * {@code for (Edge e : G.edges())}.\n *\n * @return all edges in this edge-weighted graph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n int selfLoops = 0;\n for (Edge e : adj(v)) {\n if (e.other(v) > v) {\n list.add(e);\n }\n // add only one copy of each self loop (self loops will be consecutive)\n else if (e.other(v) == v) {\n if (selfLoops % 2 == 0) list.add(e);\n selfLoops++;\n }\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of the edge-weighted graph.\n * This method takes time proportional to E + V.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (Edge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (Edge e : edges()) {\n int v = e.either();\n int w = e.other(v);\n s.append(v + \" --\" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedGraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.9", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java", "params": ["mediumEWG.txt", "tinyEWG.txt"], "dependencies": ["Bag.java", "Edge.java", "In.java", "StdOut.java"]}} {"question": "Implement toString() for EdgeWeightedGraph.java.", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedGraph.java\n * Execution: java EdgeWeightedGraph filename.txt\n * Dependencies: Bag.java Edge.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * An edge-weighted undirected graph, implemented using adjacency lists.\n * Parallel edges and self-loops are permitted.\n *\n * % java EdgeWeightedGraph tinyEWG.txt\n * 8 16\n * 0: 6-0 0.58000 0-2 0.26000 0-4 0.38000 0-7 0.16000\n * 1: 1-3 0.29000 1-2 0.36000 1-7 0.19000 1-5 0.32000\n * 2: 6-2 0.40000 2-7 0.34000 1-2 0.36000 0-2 0.26000 2-3 0.17000\n * 3: 3-6 0.52000 1-3 0.29000 2-3 0.17000\n * 4: 6-4 0.93000 0-4 0.38000 4-7 0.37000 4-5 0.35000\n * 5: 1-5 0.32000 5-7 0.28000 4-5 0.35000\n * 6: 6-4 0.93000 6-0 0.58000 3-6 0.52000 6-2 0.40000\n * 7: 2-7 0.34000 1-7 0.19000 0-7 0.16000 5-7 0.28000 4-7 0.37000\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedGraph} class represents an edge-weighted\n * graph of vertices named 0 through V \u2013 1, where each\n * undirected edge is of type {@link Edge} and has a real-valued weight.\n * It supports the following two primary operations: add an edge to the graph,\n * iterate over all of the edges incident with a vertex. It also provides\n * methods for returning the degree of a vertex, the number of vertices\n * V in the graph, and the number of edges E in the graph.\n * Parallel edges and self-loops are permitted.\n * By convention, a self-loop v-v appears in the\n * adjacency list of v twice and contributes two to the degree\n * of v.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the degree of the vertex.)\n * Constructing an empty edge-weighted graph with V vertices takes\n * Θ(V) time; constructing an edge-weighted graph with\n * E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedGraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V;\n private int E;\n private Bag[] adj;\n\n /**\n * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedGraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices must be non-negative\");\n this.V = V;\n this.E = 0;\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n }\n\n /**\n * Initializes a random edge-weighted graph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedGraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(0, 100);\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted graph from an input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedGraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n\n try {\n V = in.readInt();\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n Edge e = new Edge(v, w, weight);\n addEdge(e);\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedGraph constructor\", e);\n }\n\n }\n\n /**\n * Initializes a new edge-weighted graph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted graph to copy\n */\n public EdgeWeightedGraph(EdgeWeightedGraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (Edge e : G.adj[v]) {\n reverse.push(e);\n }\n for (Edge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n\n /**\n * Returns the number of vertices in this edge-weighted graph.\n *\n * @return the number of vertices in this edge-weighted graph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted graph.\n *\n * @return the number of edges in this edge-weighted graph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the undirected edge {@code e} to this edge-weighted graph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless both endpoints are between {@code 0} and {@code V-1}\n */\n public void addEdge(Edge e) {\n int v = e.either();\n int w = e.other(v);\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n adj[w].add(e);\n E++;\n }\n\n /**\n * Returns the edges incident with vertex {@code v}.\n *\n * @param v the vertex\n * @return the edges incident with vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the degree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the degree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int degree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns all edges in this edge-weighted graph.\n * To iterate over the edges in this edge-weighted graph, use foreach notation:\n * {@code for (Edge e : G.edges())}.\n *\n * @return all edges in this edge-weighted graph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n int selfLoops = 0;\n for (Edge e : adj(v)) {\n if (e.other(v) > v) {\n list.add(e);\n }\n // add only one copy of each self loop (self loops will be consecutive)\n else if (e.other(v) == v) {\n if (selfLoops % 2 == 0) list.add(e);\n selfLoops++;\n }\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of the edge-weighted graph.\n * This method takes time proportional to E + V.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (Edge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted graph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the graph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted graph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"graph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (Edge e : edges()) {\n int v = e.either();\n int w = e.other(v);\n s.append(v + \" --\" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedGraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n StdOut.println(graph);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.17", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java", "params": ["mediumEWG.txt", "tinyEWG.txt"], "dependencies": ["Bag.java", "Edge.java", "In.java", "StdOut.java"]}} {"question": "Provide an implementation of edges() for PrimMST.java .", "answer": "/******************************************************************************\n * Compilation: javac PrimMST.java\n * Execution: java PrimMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java\n * IndexMinPQ.java UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Prim's algorithm.\n *\n * % java PrimMST tinyEWG.txt\n * 1-7 0.19000\n * 0-2 0.26000\n * 2-3 0.17000\n * 4-5 0.35000\n * 5-7 0.28000\n * 6-2 0.40000\n * 0-7 0.16000\n * 1.81000\n *\n * % java PrimMST mediumEWG.txt\n * 1-72 0.06506\n * 2-86 0.05980\n * 3-67 0.09725\n * 4-55 0.06425\n * 5-102 0.03834\n * 6-129 0.05363\n * 7-157 0.00516\n * ...\n * 10.46351\n *\n * % java PrimMST largeEWG.txt\n * ...\n * 647.66307\n *\n ******************************************************************************/\n\n/**\n * The {@code PrimMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Prim's algorithm with an indexed\n * binary heap.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of\n * vertices and E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class PrimMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex\n private double[] distTo; // distTo[v] = weight of shortest such edge\n private boolean[] marked; // marked[v] = true if v on tree, false otherwise\n private IndexMinPQ pq;\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public PrimMST(EdgeWeightedGraph graph) {\n edgeTo = new Edge[graph.V()];\n distTo = new double[graph.V()];\n marked = new boolean[graph.V()];\n pq = new IndexMinPQ(graph.V());\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = Double.POSITIVE_INFINITY;\n\n for (int v = 0; v < graph.V(); v++) // run from each vertex to find\n if (!marked[v]) prim(graph, v); // minimum spanning forest\n\n // check optimality conditions\n assert check(graph);\n }\n\n // run Prim's algorithm in graph, starting from vertex s\n private void prim(EdgeWeightedGraph graph, int s) {\n distTo[s] = 0.0;\n pq.insert(s, distTo[s]);\n while (!pq.isEmpty()) {\n int v = pq.delMin();\n scan(graph, v);\n }\n }\n\n // scan vertex v\n private void scan(EdgeWeightedGraph graph, int v) {\n marked[v] = true;\n for (Edge e : graph.adj(v)) {\n int w = e.other(v);\n if (marked[w]) continue; // v-w is obsolete edge\n if (e.weight() < distTo[w]) {\n distTo[w] = e.weight();\n edgeTo[w] = e;\n if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);\n else pq.insert(w, distTo[w]);\n }\n }\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n Queue mst = new Queue();\n for (int v = 0; v < edgeTo.length; v++) {\n Edge e = edgeTo[v];\n if (e != null) {\n mst.enqueue(e);\n }\n }\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n double weight = 0.0;\n for (Edge e : edges())\n weight += e.weight();\n return weight;\n }\n\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : edges()) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code PrimMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n PrimMST mst = new PrimMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.21", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/PrimMST.java", "params": ["tinyEWG.txt", "mediumEWG.txt"], "dependencies": ["EdgeWeightedGraph.java", "Edge.java", "Queue.java"]}} {"question": "Minimum spanning forest. Develop versions of Prim's algorithms that compute the minimum spanning forest of an edge-weighted graph that is not necessarily connected. ", "answer": "/******************************************************************************\n * Compilation: javac PrimMST.java\n * Execution: java PrimMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java\n * IndexMinPQ.java UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Prim's algorithm.\n *\n * % java PrimMST tinyEWG.txt\n * 1-7 0.19000\n * 0-2 0.26000\n * 2-3 0.17000\n * 4-5 0.35000\n * 5-7 0.28000\n * 6-2 0.40000\n * 0-7 0.16000\n * 1.81000\n *\n * % java PrimMST mediumEWG.txt\n * 1-72 0.06506\n * 2-86 0.05980\n * 3-67 0.09725\n * 4-55 0.06425\n * 5-102 0.03834\n * 6-129 0.05363\n * 7-157 0.00516\n * ...\n * 10.46351\n *\n * % java PrimMST largeEWG.txt\n * ...\n * 647.66307\n *\n ******************************************************************************/\n\n/**\n * The {@code PrimMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Prim's algorithm with an indexed\n * binary heap.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of\n * vertices and E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link KruskalMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class PrimMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex\n private double[] distTo; // distTo[v] = weight of shortest such edge\n private boolean[] marked; // marked[v] = true if v on tree, false otherwise\n private IndexMinPQ pq;\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public PrimMST(EdgeWeightedGraph graph) {\n edgeTo = new Edge[graph.V()];\n distTo = new double[graph.V()];\n marked = new boolean[graph.V()];\n pq = new IndexMinPQ(graph.V());\n for (int v = 0; v < graph.V(); v++)\n distTo[v] = Double.POSITIVE_INFINITY;\n\n for (int v = 0; v < graph.V(); v++) // run from each vertex to find\n if (!marked[v]) prim(graph, v); // minimum spanning forest\n\n // check optimality conditions\n assert check(graph);\n }\n\n // run Prim's algorithm in graph, starting from vertex s\n private void prim(EdgeWeightedGraph graph, int s) {\n distTo[s] = 0.0;\n pq.insert(s, distTo[s]);\n while (!pq.isEmpty()) {\n int v = pq.delMin();\n scan(graph, v);\n }\n }\n\n // scan vertex v\n private void scan(EdgeWeightedGraph graph, int v) {\n marked[v] = true;\n for (Edge e : graph.adj(v)) {\n int w = e.other(v);\n if (marked[w]) continue; // v-w is obsolete edge\n if (e.weight() < distTo[w]) {\n distTo[w] = e.weight();\n edgeTo[w] = e;\n if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);\n else pq.insert(w, distTo[w]);\n }\n }\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n Queue mst = new Queue();\n for (int v = 0; v < edgeTo.length; v++) {\n Edge e = edgeTo[v];\n if (e != null) {\n mst.enqueue(e);\n }\n }\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n double weight = 0.0;\n for (Edge e : edges())\n weight += e.weight();\n return weight;\n }\n\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : edges()) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code PrimMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n PrimMST mst = new PrimMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/PrimMST.java", "params": ["tinyEWG.txt", "mediumEWG.txt"], "dependencies": ["EdgeWeightedGraph.java", "Edge.java", "Queue.java"]}} {"question": "Minimum spanning forest. Develop versions of Kruskal's algorithms that compute \nthe minimum spanning forest of an edge-weighted graph that\nis not necessarily connected.", "answer": "/******************************************************************************\n * Compilation: javac KruskalMST.java\n * Execution: java KruskalMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Kruskal's algorithm.\n *\n * % java KruskalMST tinyEWG.txt\n * 0-7 0.16000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-2 0.26000\n * 5-7 0.28000\n * 4-5 0.35000\n * 6-2 0.40000\n * 1.81000\n *\n * % java KruskalMST mediumEWG.txt\n * 168-231 0.00268\n * 151-208 0.00391\n * 7-157 0.00516\n * 122-205 0.00647\n * 8-152 0.00702\n * 156-219 0.00745\n * 28-198 0.00775\n * 38-126 0.00845\n * 10-123 0.00886\n * ...\n * 10.46351\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\n/**\n * The {@code KruskalMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Kruskal's algorithm and the\n * union-find data type.\n * The constructor takes Θ(E log E) time in\n * the worst case.\n * Each instance method takes Θ(1) time.\n * It uses Θ(E) extra space (not including the graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class KruskalMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private double weight; // weight of MST\n private Queue mst = new Queue(); // edges in MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public KruskalMST(EdgeWeightedGraph graph) {\n\n // create array of edges, sorted by weight\n Edge[] edges = new Edge[graph.E()];\n int t = 0;\n for (Edge e: graph.edges()) {\n edges[t++] = e;\n }\n Arrays.sort(edges);\n\n // run greedy algorithm\n UF uf = new UF(graph.V());\n for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) {\n Edge e = edges[i];\n int v = e.either();\n int w = e.other(v);\n\n // v-w does not create a cycle\n if (uf.find(v) != uf.find(w)) {\n uf.union(v, w); // merge v and w components\n mst.enqueue(e); // add edge e to mst\n weight += e.weight();\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check total weight\n double total = 0.0;\n for (Edge e : edges()) {\n total += e.weight();\n }\n if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", total, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n\n /**\n * Unit tests the {@code KruskalMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph G = new EdgeWeightedGraph(in);\n KruskalMST mst = new KruskalMST(G);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.22", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/KruskalMST.java", "params": ["mediumEWG.txt", "tinyEWG.txt"], "dependencies": ["EdgeWeightedGraph.java", "Edge.java", "Queue.java", "MinPQ.java"]}} {"question": "Certification. Write a method check() that uses the following cut optimality conditions to verify that a proposed set of edges is in fact an MST: A set of edges is an MST if it is a spanning tree and every edge is a minimum-weight edge in the cut defined by removing that edge from the tree. What is the order of growth of the running time of your method? ", "answer": "/******************************************************************************\n * Compilation: javac KruskalMST.java\n * Execution: java KruskalMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Kruskal's algorithm.\n *\n * % java KruskalMST tinyEWG.txt\n * 0-7 0.16000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-2 0.26000\n * 5-7 0.28000\n * 4-5 0.35000\n * 6-2 0.40000\n * 1.81000\n *\n * % java KruskalMST mediumEWG.txt\n * 168-231 0.00268\n * 151-208 0.00391\n * 7-157 0.00516\n * 122-205 0.00647\n * 8-152 0.00702\n * 156-219 0.00745\n * 28-198 0.00775\n * 38-126 0.00845\n * 10-123 0.00886\n * ...\n * 10.46351\n *\n ******************************************************************************/\n\nimport java.util.Arrays;\n\n/**\n * The {@code KruskalMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Kruskal's algorithm and the\n * union-find data type.\n * The constructor takes Θ(E log E) time in\n * the worst case.\n * Each instance method takes Θ(1) time.\n * It uses Θ(E) extra space (not including the graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link BoruvkaMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class KruskalMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private double weight; // weight of MST\n private Queue mst = new Queue(); // edges in MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public KruskalMST(EdgeWeightedGraph graph) {\n\n // create array of edges, sorted by weight\n Edge[] edges = new Edge[graph.E()];\n int t = 0;\n for (Edge e: graph.edges()) {\n edges[t++] = e;\n }\n Arrays.sort(edges);\n\n // run greedy algorithm\n UF uf = new UF(graph.V());\n for (int i = 0; i < graph.E() && mst.size() < graph.V() - 1; i++) {\n Edge e = edges[i];\n int v = e.either();\n int w = e.other(v);\n\n // v-w does not create a cycle\n if (uf.find(v) != uf.find(w)) {\n uf.union(v, w); // merge v and w components\n mst.enqueue(e); // add edge e to mst\n weight += e.weight();\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check total weight\n double total = 0.0;\n for (Edge e : edges()) {\n total += e.weight();\n }\n if (Math.abs(total - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", total, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n\n /**\n * Unit tests the {@code KruskalMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph G = new EdgeWeightedGraph(in);\n KruskalMST mst = new KruskalMST(G);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.33", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/KruskalMST.java", "params": ["mediumEWG.txt", "tinyEWG.txt"], "dependencies": ["EdgeWeightedGraph.java", "Edge.java", "Queue.java", "MinPQ.java"]}} {"question": "Boruvka's algorithm. Develop an implementation BoruvkaMST.java of Boruvka's algorithm: Build an MST by adding edges to a growing forest of trees, as in Kruskal's algorithm, but in stages. At each stage, find the minimum-weight edge that connects each tree to a different one, then add all such edges to the MST. Assume that the edge weights are all different, to avoid cycles. Hint: Maintain in a vertex-indexed array to identify the edge that connects each component to its nearest neighbor, and use the union-find data structure. Remark. There are a most log V phases since number of trees decreases by at least a factor of 2 in each phase. Attractive because it is efficient and can be run in parallel. ", "answer": "/******************************************************************************\n * Compilation: javac BoruvkaMST.java\n * Execution: java BoruvkaMST filename.txt\n * Dependencies: EdgeWeightedGraph.java Edge.java Bag.java\n * UF.java In.java StdOut.java\n * Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt\n * https://algs4.cs.princeton.edu/43mst/mediumEWG.txt\n * https://algs4.cs.princeton.edu/43mst/largeEWG.txt\n *\n * Compute a minimum spanning forest using Boruvka's algorithm.\n *\n * % java BoruvkaMST tinyEWG.txt\n * 0-2 0.26000\n * 6-2 0.40000\n * 5-7 0.28000\n * 4-5 0.35000\n * 2-3 0.17000\n * 1-7 0.19000\n * 0-7 0.16000\n * 1.81000\n *\n ******************************************************************************/\n\n/**\n * The {@code BoruvkaMST} class represents a data type for computing a\n * minimum spanning tree in an edge-weighted graph.\n * The edge weights can be positive, zero, or negative and need not\n * be distinct. If the graph is not connected, it computes a minimum\n * spanning forest, which is the union of minimum spanning trees\n * in each connected component. The {@code weight()} method returns the\n * weight of a minimum spanning tree and the {@code edges()} method\n * returns its edges.\n *

\n * This implementation uses Boruvka's algorithm and the union-find\n * data type.\n * The constructor takes Θ(E log V) time in\n * the worst case, where V is the number of vertices and\n * E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted graph).\n *

\n * This {@code weight()} method correctly computes the weight of the MST\n * if all arithmetic performed is without floating-point rounding error\n * or arithmetic overflow.\n * This is the case if all edge weights are non-negative integers\n * and the weight of the MST does not exceed 252.\n *

\n * For additional documentation,\n * see Section 4.3 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n * For alternate implementations, see {@link LazyPrimMST}, {@link PrimMST},\n * and {@link KruskalMST}.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class BoruvkaMST {\n private static final double FLOATING_POINT_EPSILON = 1.0E-12;\n\n private Bag mst = new Bag(); // edges in MST\n private double weight; // weight of MST\n\n /**\n * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n * @param graph the edge-weighted graph\n */\n public BoruvkaMST(EdgeWeightedGraph graph) {\n UF uf = new UF(graph.V());\n\n // repeat at most log V times or until we have V-1 edges\n for (int t = 1; t < graph.V() && mst.size() < graph.V() - 1; t = t + t) {\n\n // foreach tree in forest, find closest edge\n // if edge weights are equal, ties are broken in favor of first edge in graph.edges()\n Edge[] closest = new Edge[graph.V()];\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n int i = uf.find(v), j = uf.find(w);\n if (i == j) continue; // same tree\n if (closest[i] == null || less(e, closest[i])) closest[i] = e;\n if (closest[j] == null || less(e, closest[j])) closest[j] = e;\n }\n\n // add newly discovered edges to MST\n for (int i = 0; i < graph.V(); i++) {\n Edge e = closest[i];\n if (e != null) {\n int v = e.either(), w = e.other(v);\n // don't add the same edge twice\n if (uf.find(v) != uf.find(w)) {\n mst.add(e);\n weight += e.weight();\n uf.union(v, w);\n }\n }\n }\n }\n\n // check optimality conditions\n assert check(graph);\n }\n\n /**\n * Returns the edges in a minimum spanning tree (or forest).\n * @return the edges in a minimum spanning tree (or forest) as\n * an iterable of edges\n */\n public Iterable edges() {\n return mst;\n }\n\n\n /**\n * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n * @return the sum of the edge weights in a minimum spanning tree (or forest)\n */\n public double weight() {\n return weight;\n }\n\n // is the weight of edge e strictly less than that of edge f?\n private static boolean less(Edge e, Edge f) {\n return e.compareTo(f) < 0;\n }\n\n // check optimality conditions (takes time proportional to E V lg* V)\n private boolean check(EdgeWeightedGraph graph) {\n\n // check weight\n double totalWeight = 0.0;\n for (Edge e : edges()) {\n totalWeight += e.weight();\n }\n if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\", totalWeight, weight());\n return false;\n }\n\n // check that it is acyclic\n UF uf = new UF(graph.V());\n for (Edge e : edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) == uf.find(w)) {\n System.err.println(\"Not a forest\");\n return false;\n }\n uf.union(v, w);\n }\n\n // check that it is a spanning forest\n for (Edge e : graph.edges()) {\n int v = e.either(), w = e.other(v);\n if (uf.find(v) != uf.find(w)) {\n System.err.println(\"Not a spanning forest\");\n return false;\n }\n }\n\n // check that it is a minimal spanning forest (cut optimality conditions)\n for (Edge e : edges()) {\n\n // all edges in MST except e\n uf = new UF(graph.V());\n for (Edge f : mst) {\n int x = f.either(), y = f.other(x);\n if (f != e) uf.union(x, y);\n }\n\n // check that e is min weight edge in crossing cut\n for (Edge f : graph.edges()) {\n int x = f.either(), y = f.other(x);\n if (uf.find(x) != uf.find(y)) {\n if (f.weight() < e.weight()) {\n System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n return false;\n }\n }\n }\n\n }\n\n return true;\n }\n\n /**\n * Unit tests the {@code BoruvkaMST} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedGraph graph = new EdgeWeightedGraph(in);\n BoruvkaMST mst = new BoruvkaMST(graph);\n for (Edge e : mst.edges()) {\n StdOut.println(e);\n }\n StdOut.printf(\"%.5f\", mst.weight());\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/43mst/mediumEWG.txt", "https://algs4.cs.princeton.edu/43mst/tinyEWG.txt", "https://algs4.cs.princeton.edu/43mst/largeEWG.txt"], "metadata": {"number": "4.3.43", "code_execution": true, "url": "https://algs4.cs.princeton.edu/43mst/BoruvkaMST.java", "params": ["mediumEWG.txt", "tinyEWG.txt"], "dependencies": ["EdgeWeightedGraph.java", "Edge.java", "Bag.java"]}} {"question": "Provide an implementation of toString() for EdgeWeightedDigraph.java. ", "answer": "/******************************************************************************\n * Compilation: javac EdgeWeightedDigraph.java\n * Execution: java EdgeWeightedDigraph digraph.txt\n * Dependencies: Bag.java DirectedEdge.java\n * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt\n * https://algs4.cs.princeton.edu/44sp/mediumEWD.txt\n * https://algs4.cs.princeton.edu/44sp/largeEWD.txt\n *\n * An edge-weighted digraph, implemented using adjacency lists.\n *\n ******************************************************************************/\n\nimport java.util.NoSuchElementException;\n\n/**\n * The {@code EdgeWeightedDigraph} class represents an edge-weighted\n * digraph of vertices named 0 through V - 1, where each\n * directed edge is of type {@link DirectedEdge} and has a real-valued weight.\n * It supports the following two primary operations: add a directed edge\n * to the digraph and iterate over all edges incident from a given vertex.\n * It also provides methods for returning the indegree or outdegree of a\n * vertex, the number of vertices V in the digraph, and\n * the number of edges E in the digraph.\n * Parallel edges and self-loops are permitted.\n *

\n * This implementation uses an adjacency-lists representation, which\n * is a vertex-indexed array of {@link Bag} objects.\n * It uses Θ(E + V) space, where E is\n * the number of edges and V is the number of vertices.\n * All instance methods take Θ(1) time. (Though, iterating over\n * the edges returned by {@link #adj(int)} takes time proportional\n * to the outdegree of the vertex.)\n * Constructing an empty edge-weighted digraph with V vertices\n * takes Θ(V) time; constructing an edge-weighted digraph\n * with E edges and V vertices takes\n * Θ(E + V) time.\n *

\n * For additional documentation,\n * see Section 4.4 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class EdgeWeightedDigraph {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n\n private final int V; // number of vertices in this digraph\n private int E; // number of edges in this digraph\n private Bag[] adj; // adj[v] = adjacency list for vertex v\n private int[] indegree; // indegree[v] = indegree of vertex v\n\n /**\n * Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges.\n *\n * @param V the number of vertices\n * @throws IllegalArgumentException if {@code V < 0}\n */\n public EdgeWeightedDigraph(int V) {\n if (V < 0) throw new IllegalArgumentException(\"Number of vertices in a Digraph must be non-negative\");\n this.V = V;\n this.E = 0;\n this.indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++)\n adj[v] = new Bag();\n }\n\n /**\n * Initializes a random edge-weighted digraph with {@code V} vertices and E edges.\n *\n * @param V the number of vertices\n * @param E the number of edges\n * @throws IllegalArgumentException if {@code V < 0}\n * @throws IllegalArgumentException if {@code E < 0}\n */\n public EdgeWeightedDigraph(int V, int E) {\n this(V);\n if (E < 0) throw new IllegalArgumentException(\"Number of edges in a Digraph must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = StdRandom.uniformInt(V);\n int w = StdRandom.uniformInt(V);\n double weight = 0.01 * StdRandom.uniformInt(100);\n DirectedEdge e = new DirectedEdge(v, w, weight);\n addEdge(e);\n }\n }\n\n /**\n * Initializes an edge-weighted digraph from the specified input stream.\n * The format is the number of vertices V,\n * followed by the number of edges E,\n * followed by E pairs of vertices and edge weights,\n * with each entry separated by whitespace.\n *\n * @param in the input stream\n * @throws IllegalArgumentException if {@code in} is {@code null}\n * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range\n * @throws IllegalArgumentException if the number of vertices or edges is negative\n */\n public EdgeWeightedDigraph(In in) {\n if (in == null) throw new IllegalArgumentException(\"argument is null\");\n try {\n this.V = in.readInt();\n if (V < 0) throw new IllegalArgumentException(\"number of vertices in a Digraph must be non-negative\");\n indegree = new int[V];\n adj = (Bag[]) new Bag[V];\n for (int v = 0; v < V; v++) {\n adj[v] = new Bag();\n }\n\n int E = in.readInt();\n if (E < 0) throw new IllegalArgumentException(\"Number of edges must be non-negative\");\n for (int i = 0; i < E; i++) {\n int v = in.readInt();\n int w = in.readInt();\n validateVertex(v);\n validateVertex(w);\n double weight = in.readDouble();\n addEdge(new DirectedEdge(v, w, weight));\n }\n }\n catch (NoSuchElementException e) {\n throw new IllegalArgumentException(\"invalid input format in EdgeWeightedDigraph constructor\", e);\n }\n }\n\n /**\n * Initializes a new edge-weighted digraph that is a deep copy of {@code G}.\n *\n * @param G the edge-weighted digraph to copy\n */\n public EdgeWeightedDigraph(EdgeWeightedDigraph G) {\n this(G.V());\n this.E = G.E();\n for (int v = 0; v < G.V(); v++)\n this.indegree[v] = G.indegree(v);\n for (int v = 0; v < G.V(); v++) {\n // reverse so that adjacency list is in same order as original\n Stack reverse = new Stack();\n for (DirectedEdge e : G.adj[v]) {\n reverse.push(e);\n }\n for (DirectedEdge e : reverse) {\n adj[v].add(e);\n }\n }\n }\n\n /**\n * Returns the number of vertices in this edge-weighted digraph.\n *\n * @return the number of vertices in this edge-weighted digraph\n */\n public int V() {\n return V;\n }\n\n /**\n * Returns the number of edges in this edge-weighted digraph.\n *\n * @return the number of edges in this edge-weighted digraph\n */\n public int E() {\n return E;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Adds the directed edge {@code e} to this edge-weighted digraph.\n *\n * @param e the edge\n * @throws IllegalArgumentException unless endpoints of edge are between {@code 0}\n * and {@code V-1}\n */\n public void addEdge(DirectedEdge e) {\n int v = e.from();\n int w = e.to();\n validateVertex(v);\n validateVertex(w);\n adj[v].add(e);\n indegree[w]++;\n E++;\n }\n\n\n /**\n * Returns the directed edges incident from vertex {@code v}.\n *\n * @param v the vertex\n * @return the directed edges incident from vertex {@code v} as an Iterable\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable adj(int v) {\n validateVertex(v);\n return adj[v];\n }\n\n /**\n * Returns the number of directed edges incident from vertex {@code v}.\n * This is known as the outdegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the outdegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int outdegree(int v) {\n validateVertex(v);\n return adj[v].size();\n }\n\n /**\n * Returns the number of directed edges incident to vertex {@code v}.\n * This is known as the indegree of vertex {@code v}.\n *\n * @param v the vertex\n * @return the indegree of vertex {@code v}\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int indegree(int v) {\n validateVertex(v);\n return indegree[v];\n }\n\n /**\n * Returns all directed edges in this edge-weighted digraph.\n * To iterate over the edges in this edge-weighted digraph, use foreach notation:\n * {@code for (DirectedEdge e : G.edges())}.\n *\n * @return all edges in this edge-weighted digraph, as an iterable\n */\n public Iterable edges() {\n Bag list = new Bag();\n for (int v = 0; v < V; v++) {\n for (DirectedEdge e : adj(v)) {\n list.add(e);\n }\n }\n return list;\n }\n\n /**\n * Returns a string representation of this edge-weighted digraph.\n *\n * @return the number of vertices V, followed by the number of edges E,\n * followed by the V adjacency lists of edges\n */\n public String toString() {\n StringBuilder s = new StringBuilder();\n s.append(V + \" \" + E + NEWLINE);\n for (int v = 0; v < V; v++) {\n s.append(v + \": \");\n for (DirectedEdge e : adj[v]) {\n s.append(e + \" \");\n }\n s.append(NEWLINE);\n }\n return s.toString();\n }\n\n /**\n * Returns a string representation of this edge-weighted digraph in DOT format,\n * suitable for visualization with Graphviz.\n *\n * To visualize the graph, install Graphviz (e.g., \"brew install graphviz\").\n * Then use one of the graph visualization tools\n * - dot (hierarchical or layer drawing)\n * - neato (spring model)\n * - fdp (force-directed placement)\n * - sfdp (scalable force-directed placement)\n * - twopi (radial layout)\n *\n * For example, the following commands will create graph drawings in SVG\n * and PDF formats\n * - dot input.dot -Tsvg -o output.svg\n * - dot input.dot -Tpdf -o output.pdf\n *\n * To change the digraph attributes (e.g., vertex and edge shapes, arrows, colors)\n * in the DOT format, see https://graphviz.org/doc/info/lang.html\n *\n * @return a string representation of this edge-weighted digraph in DOT format\n */\n public String toDot() {\n StringBuilder s = new StringBuilder();\n s.append(\"digraph {\" + NEWLINE);\n s.append(\"node[shape=circle, style=filled, fixedsize=true, width=0.3, fontsize=\\\"10pt\\\"]\" + NEWLINE);\n s.append(\"edge[arrowhead=normal, fontsize=\\\"9pt\\\"]\" + NEWLINE);\n for (int v = 0; v < V; v++) {\n for (DirectedEdge e : adj[v]) {\n int w = e.to();\n s.append(v + \" -> \" + w + \" [label=\\\"\" + e.weight() + \"\\\"]\" + NEWLINE);\n }\n }\n s.append(\"}\" + NEWLINE);\n return s.toString();\n }\n\n /**\n * Unit tests the {@code EdgeWeightedDigraph} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);\n StdOut.println(G);\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/44sp/largeEWD.txt", "https://algs4.cs.princeton.edu/44sp/tinyEWD.txt", "https://algs4.cs.princeton.edu/44sp/mediumEWD.txt"], "metadata": {"number": "4.4.2", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/EdgeWeightedDigraph.java", "params": ["tinyEWD.txt", "mediumEWD.txt"], "dependencies": ["Bag.java", "DirectedEdge.java"]}} {"question": "Adapt the Topological classes from Section 4.2 to use the EdgeweightedDigraph and DirectedEdge APIs of this section, thus implementing Topological.java.", "answer": "/******************************************************************************\n * Compilation: javac Topological.java\n * Execution: java Topological filename.txt delimiter\n * Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java\n * EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.java\n * SymbolDigraph.java\n * Data files: https://algs4.cs.princeton.edu/42digraph/jobs.txt\n *\n * Compute topological ordering of a DAG or edge-weighted DAG.\n * Runs in O(E + V) time.\n *\n * % java Topological jobs.txt \"/\"\n * Calculus\n * Linear Algebra\n * Introduction to CS\n * Advanced Programming\n * Algorithms\n * Theoretical CS\n * Artificial Intelligence\n * Robotics\n * Machine Learning\n * Neural Networks\n * Databases\n * Scientific Computing\n * Computational Biology\n *\n ******************************************************************************/\n\n/**\n * The {@code Topological} class represents a data type for\n * determining a topological order of a directed acyclic graph (DAG).\n * A digraph has a topological order if and only if it is a DAG.\n * The hasOrder operation determines whether the digraph has\n * a topological order, and if so, the order operation\n * returns one.\n *

\n * This implementation uses depth-first search.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and E\n * is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the digraph).\n *

\n * See {@link DirectedCycle}, {@link DirectedCycleX}, and\n * {@link EdgeWeightedDirectedCycle} for computing a directed cycle\n * if the digraph is not a DAG.\n * See {@link TopologicalX} for a nonrecursive, queue-based algorithm\n * for computing a topological order of a DAG.\n *

\n * For additional documentation,\n * see Section 4.2 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class Topological {\n private Iterable order; // topological order\n private int[] rank; // rank[v] = rank of vertex v in order\n\n /**\n * Determines whether the {@code digraph} has a topological order and, if so,\n * finds such a topological order.\n * @param digraph the digraph\n */\n public Topological(Digraph digraph) {\n DirectedCycle finder = new DirectedCycle(digraph);\n if (!finder.hasCycle()) {\n DepthFirstOrder dfs = new DepthFirstOrder(digraph);\n order = dfs.reversePost();\n rank = new int[digraph.V()];\n int i = 0;\n for (int v : order)\n rank[v] = i++;\n }\n }\n\n /**\n * Determines whether the edge-weighted digraph {@code digraph} has a topological\n * order and, if so, finds such an order.\n * @param digraph the edge-weighted digraph\n */\n public Topological(EdgeWeightedDigraph digraph) {\n EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(digraph);\n if (!finder.hasCycle()) {\n DepthFirstOrder dfs = new DepthFirstOrder(digraph);\n order = dfs.reversePost();\n }\n }\n\n /**\n * Returns a topological order if the digraph has a topological order,\n * and {@code null} otherwise.\n * @return a topological order of the vertices (as an iterable) if the\n * digraph has a topological order (or equivalently, if the digraph is a DAG),\n * and {@code null} otherwise\n */\n public Iterable order() {\n return order;\n }\n\n /**\n * Does the digraph have a topological order?\n * @return {@code true} if the digraph has a topological order (or equivalently,\n * if the digraph is a DAG), and {@code false} otherwise\n */\n public boolean hasOrder() {\n return order != null;\n }\n\n /**\n * Does the digraph have a topological order?\n * @return {@code true} if the digraph has a topological order (or equivalently,\n * if the digraph is a DAG), and {@code false} otherwise\n * @deprecated Replaced by {@link #hasOrder()}.\n */\n @Deprecated\n public boolean isDAG() {\n return hasOrder();\n }\n\n /**\n * The rank of vertex {@code v} in the topological order;\n * -1 if the digraph is not a DAG\n *\n * @param v the vertex\n * @return the position of vertex {@code v} in a topological order\n * of the digraph; -1 if the digraph is not a DAG\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public int rank(int v) {\n validateVertex(v);\n if (hasOrder()) return rank[v];\n else return -1;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = rank.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Unit tests the {@code Topological} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n String filename = args[0];\n String delimiter = args[1];\n SymbolDigraph sg = new SymbolDigraph(filename, delimiter);\n Topological topological = new Topological(sg.digraph());\n for (int v : topological.order()) {\n StdOut.println(sg.nameOf(v));\n }\n }\n\n}\n", "support_files": ["https://algs4.cs.princeton.edu/42digraph/jobs.txt"], "metadata": {"number": "4.4.12", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/Topological.java", "params": ["jobs.txt \"/\""], "dependencies": ["Digraph.java", "DepthFirstOrder.java", "DirectedCycle.java"]}} {"question": "Longest paths in DAGs. Develop an implementation AcyclicLP.java that can solve the longest-paths problem in edge-weighted DAGs.", "answer": "/******************************************************************************\n * Compilation: javac AcyclicLP.java\n * Execution: java AcyclicP V E\n * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java\n * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt\n *\n * Computes longest paths in an edge-weighted acyclic digraph.\n *\n * Remark: should probably check that graph is a DAG before running\n *\n * % java AcyclicLP tinyEWDAG.txt 5\n * 5 to 0 (2.44) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->0 0.38\n * 5 to 1 (0.32) 5->1 0.32\n * 5 to 2 (2.77) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37 7->2 0.34\n * 5 to 3 (0.61) 5->1 0.32 1->3 0.29\n * 5 to 4 (2.06) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93\n * 5 to 5 (0.00)\n * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52\n * 5 to 7 (2.43) 5->1 0.32 1->3 0.29 3->6 0.52 6->4 0.93 4->7 0.37\n *\n ******************************************************************************/\n\n/**\n * The {@code AcyclicLP} class represents a data type for solving the\n * single-source longest paths problem in edge-weighted directed\n * acyclic graphs (DAGs). The edge weights can be positive, negative, or zero.\n *

\n * This implementation uses a topological-sort based algorithm.\n * The constructor takes Θ(V + E) time in the\n * worst case, where V is the number of vertices and\n * E is the number of edges.\n * Each instance method takes Θ(1) time.\n * It uses Θ(V) extra space (not including the\n * edge-weighted digraph).\n *

\n * This correctly computes longest paths if all arithmetic performed is\n * without floating-point rounding error or arithmetic overflow.\n * This is the case if all edge weights are integers and if none of the\n * intermediate results exceeds 252. Since all intermediate\n * results are sums of edge weights, they are bounded by V C,\n * where V is the number of vertices and C is the maximum\n * absolute value of any edge weight.\n *

\n * For additional documentation,\n * see Section 4.4 of\n * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n *\n * @author Robert Sedgewick\n * @author Kevin Wayne\n */\npublic class AcyclicLP {\n private double[] distTo; // distTo[v] = distance of longest s->v path\n private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on longest s->v path\n\n /**\n * Computes a longest paths tree from {@code s} to every other vertex in\n * the directed acyclic graph {@code digraph}.\n * @param digraph the acyclic digraph\n * @param s the source vertex\n * @throws IllegalArgumentException if the digraph is not acyclic\n * @throws IllegalArgumentException unless {@code 0 <= s < V}\n */\n public AcyclicLP(EdgeWeightedDigraph digraph, int s) {\n distTo = new double[digraph.V()];\n edgeTo = new DirectedEdge[digraph.V()];\n\n validateVertex(s);\n\n for (int v = 0; v < digraph.V(); v++)\n distTo[v] = Double.NEGATIVE_INFINITY;\n distTo[s] = 0.0;\n\n // relax vertices in topological order\n Topological topological = new Topological(digraph);\n if (!topological.hasOrder())\n throw new IllegalArgumentException(\"Digraph is not acyclic.\");\n for (int v : topological.order()) {\n for (DirectedEdge e : digraph.adj(v))\n relax(e);\n }\n }\n\n // relax edge e, but update if you find a *longer* path\n private void relax(DirectedEdge e) {\n int v = e.from(), w = e.to();\n if (distTo[w] < distTo[v] + e.weight()) {\n distTo[w] = distTo[v] + e.weight();\n edgeTo[w] = e;\n }\n }\n\n /**\n * Returns the length of a longest path from the source vertex {@code s} to vertex {@code v}.\n * @param v the destination vertex\n * @return the length of a longest path from the source vertex {@code s} to vertex {@code v};\n * {@code Double.NEGATIVE_INFINITY} if no such path\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public double distTo(int v) {\n validateVertex(v);\n return distTo[v];\n }\n\n /**\n * Is there a path from the source vertex {@code s} to vertex {@code v}?\n * @param v the destination vertex\n * @return {@code true} if there is a path from the source vertex\n * {@code s} to vertex {@code v}, and {@code false} otherwise\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public boolean hasPathTo(int v) {\n validateVertex(v);\n return distTo[v] > Double.NEGATIVE_INFINITY;\n }\n\n /**\n * Returns a longest path from the source vertex {@code s} to vertex {@code v}.\n * @param v the destination vertex\n * @return a longest path from the source vertex {@code s} to vertex {@code v}\n * as an iterable of edges, and {@code null} if no such path\n * @throws IllegalArgumentException unless {@code 0 <= v < V}\n */\n public Iterable pathTo(int v) {\n validateVertex(v);\n if (!hasPathTo(v)) return null;\n Stack path = new Stack();\n for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {\n path.push(e);\n }\n return path;\n }\n\n // throw an IllegalArgumentException unless {@code 0 <= v < V}\n private void validateVertex(int v) {\n int V = distTo.length;\n if (v < 0 || v >= V)\n throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n }\n\n /**\n * Unit tests the {@code AcyclicLP} data type.\n *\n * @param args the command-line arguments\n */\n public static void main(String[] args) {\n In in = new In(args[0]);\n int s = Integer.parseInt(args[1]);\n EdgeWeightedDigraph digraph = new EdgeWeightedDigraph(in);\n\n AcyclicLP lp = new AcyclicLP(digraph, s);\n\n for (int v = 0; v < digraph.V(); v++) {\n if (lp.hasPathTo(v)) {\n StdOut.printf(\"%d to %d (%.2f) \", s, v, lp.distTo(v));\n for (DirectedEdge e : lp.pathTo(v)) {\n StdOut.print(e + \" \");\n }\n StdOut.println();\n }\n else {\n StdOut.printf(\"%d to %d no path\", s, v);\n }\n }\n }\n}\n", "support_files": ["https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt"], "metadata": {"number": "4.4.28", "code_execution": true, "url": "https://algs4.cs.princeton.edu/44sp/AcyclicLP.java", "params": ["tinyEWDAG.txt 5"], "dependencies": ["EdgeWeightedDigraph.java", "DirectedEdge.java", "Topological.java"]}} {"question":"Give the value of each of the following expressions:\na. ( 0 + 15 ) / 2\nb. 2.0e-6 * 100000000.1\nc. true && false || true && true","answer":"1.1.1\na) 7\nb) 200.0000002\nc) true","support_files":[],"metadata":{"number":"1.1.1","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Give the type and value of each of the following expressions:\na. (1 + 2.236)/2\nb. 1 + 2 + 3 + 4.0\nc. 4.1 >= 4\nd. 1 + 2 + \"3\"","answer":"1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String","support_files":[],"metadata":{"number":"1.1.2","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"What (if anything) is wrong with each of the following statements?\na. if (a > b) then c = 0;\nb. if a > b { c = 0; }\nc. if (a > b) c = 0;\nd. if (a > b) c = 0 else b = 0;","answer":"1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause","support_files":[],"metadata":{"number":"1.1.4","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"What does the following program print?\nint f = 0; \nint g = 1; \nfor (int i = 0; i <= 15; i++) \n{\n StdOut.println(f);\n f = f + g;\n g = f - g; \n}","answer":"1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610","support_files":[],"metadata":{"number":"1.1.6","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Give the value printed by each of the following code fragments:\na. double t = 9.0;\n while (Math.abs(t - 9.0/t) > .001)\n t = (9.0/t + t) / 2.0;\n StdOut.printf(\"%.5f\\n\", t);\nb. int sum = 0;\n for (int i = 1; i < 1000; i++)\n for (int j = 0; j < i; j++)\n sum++;\n StdOut.println(sum);\nc. int sum = 0;\n for (int i = 1; i < 1000; i *= 2)\n for (int j = 0; j < N; j++)\n sum++;\n StdOut.println(sum);","answer":"1.1.7\na) 3.00009\nb) 499500\nc) 10000","support_files":[],"metadata":{"number":"1.1.7","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"What do each of the following print?\na. System.out.println('b');\nb. System.out.println('b' + 'c');\nc. System.out.println((char) ('a' + 4));\nExplain each outcome.","answer":"1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it","support_files":[],"metadata":{"number":"1.1.8","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"What is wrong with the following code fragment?\nint[] a; \nfor (int i = 0; i < 10; i++)\n a[i] = i * i;","answer":"1.1.10\nThe array was not initialized and will generate a compile-time error.","support_files":[],"metadata":{"number":"1.1.10","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"What does the following code fragment print?\nint[] a = new int[10]; \nfor (int i = 0; i < 10; i++)\n a[i] = 9 - i; \nfor (int i = 0; i < 10; i++)\n a[i] = a[a[i]]; \nfor (int i = 0; i < 10; i++)\n System.out.println(i);","answer":"1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0","support_files":[],"metadata":{"number":"1.1.12","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Give the value of exR1(6):\npublic static String exR1(int n) \n{\n if (n <= 0) return \"\";\n return exR1(n-3) + n + exR1(n-2) + n; \n}","answer":"1.1.16\n\n311361142246","support_files":[],"metadata":{"number":"1.1.16","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Criticize the following recursive function:\npublic static String exR2(int n) \n{\n String s = exR2(n-3) + n + exR2(n-2) + n;\n if (n <= 0) return \"\";\n return s; \n}","answer":"1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.","support_files":[],"metadata":{"number":"1.1.17","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Consider the following recursive function:\npublic static int mystery(int a, int b) \n{\n if (b == 0) return 0;\n if (b % 2 == 0) return mystery(a+a, b/2);\n return mystery(a+a, b/2) + a; \n}\nWhat are the values of mystery(2, 25) and mystery(3, 11)? Given positive integers a and b, describe what value mystery(a, b) computes. Answer the same question, but replace + with * and replace return 0 with return 1.","answer":"1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b","support_files":[],"metadata":{"number":"1.1.18","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Run the following program on your computer:\npublic class Fibonacci \n{\n public static long F(int N)\n {\n if (N == 0) return 0;\n if (N == 1) return 1;\n return F(N-1) + F(N-2);\n }\n public static void main(String[] args)\n {\n for (int N = 0; N < 100; N++)\n StdOut.println(N + \" \" + F(N));\n } \n}\nWhat is the largest value of N for which this program takes less 1 hour to compute the value of F(N)? Develop a better implementation of F(N) that saves computed values in an array.","answer":"1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.","support_files":[],"metadata":{"number":"1.1.19","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Use mathematical induction to prove that Euclid’s algorithm computes the greatest common divisor of any pair of nonnegative integers p and q.","answer":"1.1.25\n\nFor all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b.\n\nProving that gcd(a, b) = gcd(b, a % b)\n\ngcd(20,5) = gcd(5,0)\n\ngcd(20,5) is 5\ngcd(5,0) is also 5\n\nhttp://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege\n\nhttps://www.whitman.edu/mathematics/higher_math_online/section03.03.html","support_files":[],"metadata":{"number":"1.1.25","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Exercise","code_execution":false}} {"question":"Binomial distribution. Estimate the number of recursive calls that would be used by the code\npublic static double binomial(int N, int k, double p) \n{\n if ((N == 0) || (k < 0)) return 1.0;\n return (1.0 - p)*binomial(N-1, k) + p*binomial(N-1, k-1); \n}\nto compute binomial(100, 50). Develop a better implementation that is based on saving computed values in an array.","answer":"1.1.27 - Binomial distribution\n\nFor binomial(100, 50, 0.25) the estimate is around 5 billion calls.","support_files":[],"metadata":{"number":"1.1.27","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Creative Problem","code_execution":false}} {"question":"Filtering. Which of the following require saving all the values from standard input (in an array, say), and which could be implemented as a filter using only a fixed number of variables and arrays of fixed size (not dependent on N)? For each, the input comes from standard input and consists of N real numbers between 0 and 1.\n- Print the maximum and minimum numbers.\n- Print the median of the numbers.\n- Print the k th smallest value, for k less than 100.\n- Print the sum of the squares of the numbers.\n- Print the average of the N numbers.\n- Print the percentage of numbers greater than the average.\n- Print the N numbers in increasing order.\n- Print the N numbers in random order.","answer":"1.1.34 - Filtering\n\nPrint the maximum and minimum numbers -> Could be implemented as a filter\nPrint the median of the numbers -> Requires saving all values\nPrint the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K\nPrint the sum of the squares of the numbers -> Could be implemented as a filter\nPrint the average of the N numbers -> Could be implemented as a filter\nPrint the percentage of numbers greater than the average -> Requires saving all values\nPrint the N numbers in increasing order -> Requires saving all values\nPrint the N numbers in random order -> Requires saving all values\n\nThanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/175","support_files":[],"metadata":{"number":"1.1.34","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Creative Problem","code_execution":false}} {"question":"Dice simulation. The following code computes the exact probability distribution for the sum of two dice:\nint SIDES = 6; \ndouble[] dist = new double[2*SIDES+1]; \nfor (int i = 1; i <= SIDES; i++)\n for (int j = 1; j <= SIDES; j++)\n dist[i+j] += 1.0;\nfor (int k = 2; k <= 2*SIDES; k++)\n dist[k] /= 36.0; \nThe value dist[i] is the probability that the dice sum to k. Run experiments to validate this calculation simulating N dice throws, keeping track of the frequencies of occurrence of each value when you compute the sum of two random integers between 1 and 6. How large does N have to be before your empirical results match the exact results to three decimal places?","answer":"1.1.35 - Dice simulation\n\nN has to be 6.000.000 before my empirical results match the exact results to three decimal places.","support_files":[],"metadata":{"number":"1.1.35","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Experiment","code_execution":false}} {"question":"Binary search versus brute-force search. Write a program BruteForceSearch that uses the brute-force search method given on page 48 and compare its running time on your computer with that of BinarySearch for largeW.txt and largeT.txt.","answer":"1.1.38 - Binary search versus brute-force search\n\nlargeW.txt results:\n\nBruteforce: 760274\nDuration: 9705800 nanoseconds.\nBinarySearch: 760274\nDuration: 112000 nanoseconds.\n\nlargeT.txt results:\n\nBruteforce: 7328283\nDuration: 1325191800 nanoseconds.\nBinarySearch: 7328279\nDuration: 158600 nanoseconds.\n\nFor testing:\nhttps://algs4.cs.princeton.edu/11model/tinyW.txt\nhttps://algs4.cs.princeton.edu/11model/tinyT.txt\nhttps://algs4.cs.princeton.edu/11model/largeW.txt\nhttps://algs4.cs.princeton.edu/11model/largeT.txt","support_files":[],"metadata":{"number":"1.1.38","chapter":1,"chapter_title":"Fundamentals","section":1.1,"section_title":"Basic Programming Model","type":"Experiment","code_execution":false}} {"question":"Write a Point2D client that takes an integer value N from the command line, generates N random points in the unit square, and computes the distance separating the closest pair of points.","answer":"1.1.1\na) 7\nb) 200.0000002\nc) true","support_files":[],"metadata":{"number":"1.2.1","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"Write an Interval1D client that takes an int value N as command-line argument, reads N intervals (each defined by a pair of double values) from standard input, and prints all pairs that intersect.","answer":"1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String","support_files":[],"metadata":{"number":"1.2.2","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"What does the following code fragment print?\nString string1 = \"hello\"; \nString string2 = string1; \nstring1 = \"world\"; \nStdOut.println(string1); \nStdOut.println(string2);","answer":"1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause","support_files":[],"metadata":{"number":"1.2.4","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"A string s is a circular rotation of a string t if it matches when the characters are circularly shifted by any number of positions; e.g., ACTGACG is a circular shift of TGACGAC, and vice versa. Detecting this condition is important in the study of genomic sequences. Write a program that checks whether two given strings s and t are circular shifts of one another. Hint: The solution is a one-liner with indexOf(), length(), and string concatenation.","answer":"1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610","support_files":[],"metadata":{"number":"1.2.6","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"What does the following recursive function return?\npublic static String mystery(String s) \n{\n int N = s.length();\n if (N <= 1) return s;\n String a = s.substring(0, N/2);\n String b = s.substring(N/2, N);\n return mystery(b) + mystery(a); \n}","answer":"1.1.7\na) 3.00009\nb) 499500\nc) 10000","support_files":[],"metadata":{"number":"1.2.7","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"Suppose that a[] and b[] are each integer arrays consisting of millions of integers. What does the follow code do? Is it reasonably efficient?\nint[] t = a; a = b; b = t;","answer":"1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it","support_files":[],"metadata":{"number":"1.2.8","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"Develop a class VisualCounter that allows both increment and decrement operations. Take two arguments N and max in the constructor, where N specifies the maximum number of operations and max specifies the maximum absolute value for the counter. As a side effect, create a plot showing the value of the counter each time its tally changes.","answer":"1.1.10\nThe array was not initialized and will generate a compile-time error.","support_files":[],"metadata":{"number":"1.2.10","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"Add a method dayOfTheWeek() to SmartDate that returns a String value Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday, giving the appropriate day of the week for the date. You may assume that the date is in the 21st century.","answer":"1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0","support_files":[],"metadata":{"number":"1.2.12","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Exercise","code_execution":false}} {"question":"Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division.\npublic class Rational \nRational(int numerator, int denominator) \nRational plus(Rational b) // sum of this number and b\nRational minus(Rational b) // difference of this number and b\nRational times(Rational b) // product of this number and b\nRational divides(Rational b) // quotient of this number and b\nboolean equals(Rational that) // is this number equal to that ?\nString toString() // string representation\nYou do not have to worry about testing for overflow (see Exercise 1.2.17), but use as instance variables two long values that represent the numerator and denominator to limit the possibility of overflow. Use Euclid’s algorithm (see page 4) to ensure that the numerator and denominator never have any common factors. Include a test client that exercises all of your methods.","answer":"1.1.16\n\n311361142246","support_files":[],"metadata":{"number":"1.2.16","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Creative Problem","code_execution":false}} {"question":"Robust implementation of rational numbers. Use assertions to develop an implementation of Rational (see Exercise 1.2.16) that is immune to overflow.","answer":"1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.","support_files":[],"metadata":{"number":"1.2.17","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Creative Problem","code_execution":false}} {"question":"Variance for accumulator. Validate that the following code, which adds the methods var() and stddev() to Accumulator, computes both the mean and variance of the numbers presented as arguments to addDataValue():\npublic class Accumulator \n{\n private double m;\n private double s;\n private int N;\n public void addDataValue(double x)\n {\n N++;\n s = s + 1.0 * (N-1) / N * (x - m) * (x - m);\n m = m + (x - m) / N;\n }\n public double mean()\n { return m; }\n public double var()\n { return s/(N - 1); }\n public double stddev()\n { return Math.sqrt(this.var()); }\n}\nThis implementation is less susceptible to roundoff error than the straightforward implementation based on saving the sum of the squares of the numbers.","answer":"1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b","support_files":[],"metadata":{"number":"1.2.18","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Creative Problem","code_execution":false}} {"question":"Parsing. Develop the parse constructors for your Date and Transaction implementations of Exercise 1.2.13 that take a single String argument to specify the initialization values, using the formats given in the table below.\n| type | format | example |\n|-------------|--------------------------------------------|------------------------|\n| Date | integers separated by slashes | 5/22/1939 |\n| Transaction | customer, date, and amount, separated by whitespace | Turing 5/22/1939 11.99 |","answer":"1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.","support_files":[],"metadata":{"number":"1.2.19","chapter":1,"chapter_title":"Fundamentals","section":1.2,"section_title":"Data Abstraction","type":"Creative Problem","code_execution":false}} {"question":"Add a method isFull() to FixedCapacityStackOfStrings.","answer":"1.1.1\na) 7\nb) 200.0000002\nc) true","support_files":[],"metadata":{"number":"1.3.1","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Give the output printed by java Stack for the input\nit was - the best - of times - - - it was - the - -","answer":"1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String","support_files":[],"metadata":{"number":"1.3.2","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).","answer":"1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause","support_files":[],"metadata":{"number":"1.3.4","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"What does the following code fragment do to the queue q?\nStack stack = new Stack(); \nwhile (!q.isEmpty())\n stack.push(q.dequeue()); \nwhile (!stack.isEmpty())\n q.enqueue(stack.pop());","answer":"1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610","support_files":[],"metadata":{"number":"1.3.6","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Add a method peek() to Stack that returns the most recently inserted item on the stack (without popping it).","answer":"1.1.7\na) 3.00009\nb) 499500\nc) 10000","support_files":[],"metadata":{"number":"1.3.7","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Give the contents and size of the array for DoublingStackOfStrings with the input\nit was - the best - of times - - - it was - the - -","answer":"1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it","support_files":[],"metadata":{"number":"1.3.8","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Write a filter InfixToPostfix that converts an arithmetic expression from infix to postfix.","answer":"1.1.10\nThe array was not initialized and will generate a compile-time error.","support_files":[],"metadata":{"number":"1.3.10","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Write an iterable Stack client that has a static method copy() that takes a stack of strings as argument and returns a copy of the stack. Note: This ability is a prime example of the value of having an iterator, because it allows development of such functionality without changing the basic API.","answer":"1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0","support_files":[],"metadata":{"number":"1.3.12","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Using readInts() on page 126 as a model, write a static method readDates() for Date that reads dates from standard input in the format specified in the table on page 119 and returns an array containing them.","answer":"1.1.16\n\n311361142246","support_files":[],"metadata":{"number":"1.3.16","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Do Exercise 1.3.16 for Transaction.","answer":"1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.","support_files":[],"metadata":{"number":"1.3.17","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment?\nx.next = x.next.next;","answer":"1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b","support_files":[],"metadata":{"number":"1.3.18","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Give a code fragment that removes the last node in a linked list whose first node is first.","answer":"1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.","support_files":[],"metadata":{"number":"1.3.19","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Write a method insertAfter() that takes two linked-list Node arguments and inserts the second after the first on its list (and does nothing if either argument is null).","answer":"1.1.25\n\nFor all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b.\n\nProving that gcd(a, b) = gcd(b, a % b)\n\ngcd(20,5) = gcd(5,0)\n\ngcd(20,5) is 5\ngcd(5,0) is also 5\n\nhttp://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege\n\nhttps://www.whitman.edu/mathematics/higher_math_online/section03.03.html","support_files":[],"metadata":{"number":"1.3.25","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Write a method max() that takes a reference to the first node in a linked list as argument and returns the value of the maximum key in the list. Assume that all keys are positive integers, and return 0 if the list is empty.","answer":"1.1.27 - Binomial distribution\n\nFor binomial(100, 50, 0.25) the estimate is around 5 billion calls.","support_files":[],"metadata":{"number":"1.3.27","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Exercise","code_execution":false}} {"question":"Random bag. A random bag stores a collection of items and supports the following API:\npublic class RandomBag implements Iterable \nRandomBag() // create an empty random bag\nboolean isEmpty() // is the bag empty?\nint size() // number of items in the bag\nvoid add(Item item) // add an item\nWrite a class RandomBag that implements this API. Note that this API is the same as for Bag, except for the adjective random, which indicates that the iteration should provide the items in random order (all N! permutations equally likely, for each iterator). Hint: Put the items in an array and randomize their order in the iterator’s constructor.","answer":"1.1.34 - Filtering\n\nPrint the maximum and minimum numbers -> Could be implemented as a filter\nPrint the median of the numbers -> Requires saving all values\nPrint the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K\nPrint the sum of the squares of the numbers -> Could be implemented as a filter\nPrint the average of the N numbers -> Could be implemented as a filter\nPrint the percentage of numbers greater than the average -> Requires saving all values\nPrint the N numbers in increasing order -> Requires saving all values\nPrint the N numbers in random order -> Requires saving all values\n\nThanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/175","support_files":[],"metadata":{"number":"1.3.34","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Creative Problem","code_execution":false}} {"question":"Random queue. A random queue stores a collection of items and supports the following API:\npublic class RandomQueue\nRandomQueue() // create an empty random queue\nboolean isEmpty() // is the queue empty?\nvoid enqueue(Item item) // add an item\nItem dequeue() // remove and return a random item (sample without replacement)\nItem sample() // return a random item, but do not remove (sample with replacement)\nWrite a class RandomQueue that implements this API. Hint: Use an array representation (with resizing). To remove an item, swap one at a random position (indexed 0 through N-1) with the one at the last position (index N-1). Then delete and return the last object, as in ResizingArrayStack. Write a client that deals bridge hands (13 cards each) using RandomQueue.","answer":"1.1.35 - Dice simulation\n\nN has to be 6.000.000 before my empirical results match the exact results to three decimal places.","support_files":[],"metadata":{"number":"1.3.35","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Creative Problem","code_execution":false}} {"question":"Delete kth element. Implement a class that supports the following API:\npublic class GeneralizedQueue\nGeneralizedQueue() // create an empty queue\nboolean isEmpty() // is the queue empty?\nvoid insert(Item x) // add an item\nItem delete(int k) // delete and return the kth least recently inserted item\nFirst, develop an implementation that uses an array implementation, and then develop one that uses a linked-list implementation. Note: the algorithms and data structures that we introduce in Chapter 3 make it possible to develop an implementation that can guarantee that both insert() and delete() take time proportional to the logarithm of the number of items in the queue—see Exercise 3.5.27.","answer":"1.1.38 - Binary search versus brute-force search\n\nlargeW.txt results:\n\nBruteforce: 760274\nDuration: 9705800 nanoseconds.\nBinarySearch: 760274\nDuration: 112000 nanoseconds.\n\nlargeT.txt results:\n\nBruteforce: 7328283\nDuration: 1325191800 nanoseconds.\nBinarySearch: 7328279\nDuration: 158600 nanoseconds.\n\nFor testing:\nhttps://algs4.cs.princeton.edu/11model/tinyW.txt\nhttps://algs4.cs.princeton.edu/11model/tinyT.txt\nhttps://algs4.cs.princeton.edu/11model/largeW.txt\nhttps://algs4.cs.princeton.edu/11model/largeT.txt","support_files":[],"metadata":{"number":"1.3.38","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Creative Problem","code_execution":false}} {"question":"Forbidden triple for stack generability. Prove that a permutation can be generated by a stack (as in the previous question) if and only if it has no forbidden triple (a, b, c) such that a < b < c with c first, a second, and b third (possibly with other intervening integers between c and a and between a and b).","answer":"1.3.46 - Forbidden triple for stack generability\nSuppose that there is a forbidden triple (a,b,c). Item \"c\" is popped before \"a\" and \"b\", but \"a\" and \"b\" are pushed before \"c\".\nThus, when \"c\" is pushed, both \"a\" and \"b\" are on the stack. Therefore, \"a\" cannot be popped before \"b\".\n\nWhen pushing items in the order 0, 1, ..., N-1, all items are above smaller items on the stack because they are pushed after smaller items.\nIf a < b, \"a\" cannot be above \"b\" on the stack. Therefore, a permutation would not exist when a forbidden triple exists.","support_files":[],"metadata":{"number":"1.3.46","chapter":1,"chapter_title":"Fundamentals","section":1.3,"section_title":"Bags, Queues, and Stacks","type":"Creative Problem","code_execution":false}} {"question":"Show that the number of different triples that can be chosen from N items is precisely N(N-1)(N-2)/6. Hint: Use mathematical induction.","answer":"1.1.1\na) 7\nb) 200.0000002\nc) true","support_files":[],"metadata":{"number":"1.4.1","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.","answer":"1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String","support_files":[],"metadata":{"number":"1.4.2","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Develop a table like the one on page 181 for TwoSum.","answer":"1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause","support_files":[],"metadata":{"number":"1.4.4","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Give the order of growth (as a function of N) of the running times of each of the following code fragments:\na. int sum = 0;\n for (int n = N; n > 0; n /= 2)\n for(int i = 0; i < n; i++)\n sum++;\nb. int sum = 0;\n for (int i = 1; i < N; i *= 2)\n for (int j = 0; j < i; j++)\n sum++;\nc. int sum = 0;\n for (int i = 1; i < N; i *= 2)\n for (int j = 0; j < N; j++)\n sum++;","answer":"1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610","support_files":[],"metadata":{"number":"1.4.6","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Analyze ThreeSum under a cost model that counts arithmetic operations (and comparisons) involving the input numbers.","answer":"1.1.7\na) 3.00009\nb) 499500\nc) 10000","support_files":[],"metadata":{"number":"1.4.7","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Write a program to determine the number pairs of values in an input file that are equal. If your first try is quadratic, think again and use Arrays.sort() to develop a linearithmic solution.","answer":"1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it","support_files":[],"metadata":{"number":"1.4.8","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Modify binary search so that it always returns the element with the smallest index that matches the search element (and still guarantees logarithmic running time).","answer":"1.1.10\nThe array was not initialized and will generate a compile-time error.","support_files":[],"metadata":{"number":"1.4.10","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Write a program that, given two sorted arrays of N int values, prints all elements that appear in both arrays, in sorted order. The running time of your program should be proportional to N in the worst case.","answer":"1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0","support_files":[],"metadata":{"number":"1.4.12","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Exercise","code_execution":false}} {"question":"Closest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a closest pair: two values whose difference is no greater than the difference of any other pair (in absolute value). The running time of your program should be linearithmic in the worst case.","answer":"1.1.16\n\n311361142246","support_files":[],"metadata":{"number":"1.4.16","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Farthest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a farthest pair: two values whose difference is no smaller than the difference of any other pair (in absolute value). The running time of your program should be linear in the worst case.","answer":"1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.","support_files":[],"metadata":{"number":"1.4.17","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Local minimum of an array. Write a program that, given an array a[] of N distinct integers, finds a local minimum: an index i such that a[i-1] < a[i] < a[i+1]. Your program should use ~2lg N compares in the worst case.","answer":"1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b","support_files":[],"metadata":{"number":"1.4.18","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Local minimum of a matrix. Given an N-by-N array a[] of N^2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: a pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1]. The running time of your program should be proportional to N in the worst case.","answer":"1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.","support_files":[],"metadata":{"number":"1.4.19","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Throwing two eggs from a building. Consider the previous question, but now suppose you only have two eggs, and your cost model is the number of throws. Devise a strategy to determine F such that the number of throws is at most 2√N, then find a way to reduce the cost to ~c√F. This is analogous to a situation where search hits (egg intact) are much cheaper than misses (egg broken).","answer":"1.1.25\n\nFor all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b.\n\nProving that gcd(a, b) = gcd(b, a % b)\n\ngcd(20,5) = gcd(5,0)\n\ngcd(20,5) is 5\ngcd(5,0) is also 5\n\nhttp://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege\n\nhttps://www.whitman.edu/mathematics/higher_math_online/section03.03.html","support_files":[],"metadata":{"number":"1.4.25","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Queue with two stacks. Implement a queue with two stacks so that each queue operation takes a constant amortized number of stack operations. Hint: If you push elements onto a stack and then pop them all, they appear in reverse order. If you repeat this process, they’re now back in order.","answer":"1.1.27 - Binomial distribution\n\nFor binomial(100, 50, 0.25) the estimate is around 5 billion calls.","support_files":[],"metadata":{"number":"1.4.27","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Hot or cold. Your goal is to guess a secret integer between 1 and N. You repeatedly guess integers between 1 and N. After each guess you learn if your guess equals the secret integer (and the game stops). Otherwise, you learn if the guess is hotter (closer to) or colder (farther from) the secret number than your previous guess. Design an algorithm that finds the secret number in at most ~2 lg N guesses. Then design an algorithm that finds the secret number in at most ~ 1 lg N guesses.","answer":"1.1.34 - Filtering\n\nPrint the maximum and minimum numbers -> Could be implemented as a filter\nPrint the median of the numbers -> Requires saving all values\nPrint the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K\nPrint the sum of the squares of the numbers -> Could be implemented as a filter\nPrint the average of the N numbers -> Could be implemented as a filter\nPrint the percentage of numbers greater than the average -> Requires saving all values\nPrint the N numbers in increasing order -> Requires saving all values\nPrint the N numbers in random order -> Requires saving all values\n\nThanks to imyuewu (https://github.com/imyuewu) for suggesting a correction for the Kth smallest value case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/175","support_files":[],"metadata":{"number":"1.4.34","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Time costs for pushdown stacks. Justify the entries in the table below, which shows typical time costs for various pushdown stack implementations, using a cost model that counts both data references (references to data pushed onto the stack, either an array reference or a reference to an object’s instance variable) and objects created.\n| data structure | item type | cost to push N int values | |\n|------------------|-----------|---------------------------|----------------|\n| | | data references | objects created |\n| linked list | int | 2N | N |\n| | Integer | 3N | 2N |\n| resizing array | int | ~5N | lg N |\n| | Integer | ~5N | ~N |","answer":"1.1.35 - Dice simulation\n\nN has to be 6.000.000 before my empirical results match the exact results to three decimal places.","support_files":[],"metadata":{"number":"1.4.35","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Creative Problem","code_execution":false}} {"question":"Naive 3-sum implementation. Run experiments to evaluate the following implementation of the inner loop of ThreeSum:\nfor (int i = 0; i < N; i++)\n for (int j = 0; j < N; j++)\n for (int k = 0; k < N; k++)\n if (i < j && j < k)\n if (a[i] + a[j] + a[k] == 0)\n cnt++;\nDo so by developing a version of DoublingTest that computes the ratio of the running times of this program and ThreeSum.","answer":"1.1.38 - Binary search versus brute-force search\n\nlargeW.txt results:\n\nBruteforce: 760274\nDuration: 9705800 nanoseconds.\nBinarySearch: 760274\nDuration: 112000 nanoseconds.\n\nlargeT.txt results:\n\nBruteforce: 7328283\nDuration: 1325191800 nanoseconds.\nBinarySearch: 7328279\nDuration: 158600 nanoseconds.\n\nFor testing:\nhttps://algs4.cs.princeton.edu/11model/tinyW.txt\nhttps://algs4.cs.princeton.edu/11model/tinyT.txt\nhttps://algs4.cs.princeton.edu/11model/largeW.txt\nhttps://algs4.cs.princeton.edu/11model/largeT.txt","support_files":[],"metadata":{"number":"1.4.38","chapter":1,"chapter_title":"Fundamentals","section":1.4,"section_title":"Analysis of Algorithms","type":"Experiment","code_execution":false}} {"question":"Show the contents of the id[] array and the number of times the array is accessed for each input pair when you use quick-find for the sequence 9-0 3-4 5-8 7-2 2-1 5-7 0-3 4-2.","answer":"1.1.1\na) 7\nb) 200.0000002\nc) true","support_files":[],"metadata":{"number":"1.5.1","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Do Exercise 1.5.1, but use quick-union (page 224). In addition, draw the forest of trees represented by the id[] array after each input pair is processed.","answer":"1.1.2\na) 1.618 -> double\nb) 10.0 -> double\nc) true -> boolean\nd) 33 -> String","support_files":[],"metadata":{"number":"1.5.2","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Show the contents of the sz[] and id[] arrays and the number of array accesses for each input pair corresponding to the weighted quick-union examples in the text (both the reference input and the worst-case input).","answer":"1.1.4\na) No such keyword as \"then\" in Java language\nb) Missing Parentheses on if conditional\nc) Nothing wrong\nd) Missing semicolon after the \"then\" clause","support_files":[],"metadata":{"number":"1.5.4","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Repeat Exercise 1.5.5 for weighted quick-union.","answer":"1.1.6\n\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n610","support_files":[],"metadata":{"number":"1.5.6","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Develop classes QuickUnionUF and QuickFindUF that implement quick-union and quick-find, respectively.","answer":"1.1.7\na) 3.00009\nb) 499500\nc) 10000","support_files":[],"metadata":{"number":"1.5.7","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Give a counterexample that shows why this intuitive implementation of union() for quick-find is not correct:\npublic void union(int p, int q) \n{ \n if (connected(p, q)) return;\n // Rename p’s component to q’s name.\n for (int i = 0; i < id.length; i++)\n if (id[i] == id[p]) id[i] = id[q];\n count--; \n}","answer":"1.1.8\na) b -> converts the char \"b\" to String and prints it\nb) 197 -> sums the char codes of \"b\" and \"c\", converts to String and prints it\nc) e -> sums the char code of \"a\" with 4, converts it to char and prints it","support_files":[],"metadata":{"number":"1.5.8","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"In the weighted quick-union algorithm, suppose that we set id[find(p)] to q instead of to id[find(q)]. Would the resulting algorithm be correct?","answer":"1.1.10\nThe array was not initialized and will generate a compile-time error.","support_files":[],"metadata":{"number":"1.5.10","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Exercise","code_execution":false}} {"question":"Quick-union with path compression. Modify quick-union (page 224) to include path compression, by adding a loop to union() that links every site on the paths from p and q to the roots of their trees to the root of the new tree. Give a sequence of input pairs that causes this method to produce a path of length 4. Note: The amortized cost per operation for this algorithm is known to be logarithmic.","answer":"1.1.12\n\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0","support_files":[],"metadata":{"number":"1.5.12","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Creative Problem","code_execution":false}} {"question":"Amortized costs plots. Instrument your implementations from Exercise 1.5.7 to make amortized costs plots like those in the text.","answer":"1.1.16\n\n311361142246","support_files":[],"metadata":{"number":"1.5.16","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Creative Problem","code_execution":false}} {"question":"Random connections. Develop a UF client ErdosRenyi that takes an integer value N from the command line, generates random pairs of integers between 0 and N-1, calling connected() to determine if they are connected and then union() if not (as in our development client), looping until all sites are connected, and printing the number of connections generated. Package your program as a static method count() that takes N as argument and returns the number of connections and a main() that takes N from the command line, calls count(), and prints the returned value.","answer":"1.1.17\nThe function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.","support_files":[],"metadata":{"number":"1.5.17","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Creative Problem","code_execution":false}} {"question":"Random grid generator. Write a program RandomGrid that takes an int value N from the command line, generates all the connections in an N-by-N grid, puts them in random order, randomly orients them (so that p q and q p are equally likely to occur), and prints the result to standard output. To randomly order the connections, use a RandomBag (see Exercise 1.3.34 on page 167). To encapsulate p and q in a single object, use the Connection nested class shown below. Package your program as two static methods: generate(), which takes N as argument and returns an array of connections, and main(), which takes N from the command line, calls generate(), and iterates through the returned array to print the connections.\nprivate class Connection \n{\n int p;\n int q;\n public Connection(int p, int q)\n { this.p = p; this.q = q; } \n}","answer":"1.1.18\n\nmystery(2,25) is equal to 50\nmystery(3,11) is equal to 33\nmystery(a,b) computes a * b\n\nmystery2(2,25) is equal to 33554432\nmystery2(3,11) is equal to 177147\nmystery2(a,b) computes a^b","support_files":[],"metadata":{"number":"1.5.18","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Creative Problem","code_execution":false}} {"question":"Animation. Write a RandomGrid client (see Exercise 1.5.18) that uses UnionFind as in our development client to check connectivity and uses StdDraw to draw the connections as they are processed.","answer":"1.1.19\n\nThe largest value of N that takes less than 1 hour to compute is 51.","support_files":[],"metadata":{"number":"1.5.19","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Creative Problem","code_execution":false}} {"question":"Doubling test for random grids. Develop a performance-testing client that takes an int value T from the command line and performs T trials of the following experiment: Use your client from Exercise 1.5.18 to generate the connections in an N-by-N square grid, randomly oriented and in random order, then use UnionFind to determine connectivity as in our development client, looping until all sites are connected. For each N, print the value of N, the average number of connections processed, and the ratio of the running time to the previous. Use your program to validate the hypotheses in the text that the running times for quick-find and quick-union are quadratic and weighted quick-union is near-linear. Note: As N doubles, the number of sites in the grid increases by a factor of 4, so expect a doubling factor of 16 for quadratic and 4 for linear.","answer":"1.1.25\n\nFor all N E NaturalNumbers and for all nonnegative integers a <= N and b <= N, the Euclidean algorithm computes the greatest common divisor of a and b.\n\nProving that gcd(a, b) = gcd(b, a % b)\n\ngcd(20,5) = gcd(5,0)\n\ngcd(20,5) is 5\ngcd(5,0) is also 5\n\nhttp://math.stackexchange.com/questions/1274515/prove-that-euclids-algorithm-computes-the-gcd-of-any-pair-of-nonnegative-intege\n\nhttps://www.whitman.edu/mathematics/higher_math_online/section03.03.html","support_files":[],"metadata":{"number":"1.5.25","chapter":1,"chapter_title":"Fundamentals","section":1.5,"section_title":"Case Study: Union-Find","type":"Experiment","code_execution":false}} {"question":"Show, in the style of the example trace with Algorithm 2.1, how selection sort sorts the array E A S Y Q U E S T I O N.","answer":"2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.1.1","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"What is the maximum number of exchanges involving any particular element during selection sort? What is the average number of exchanges involving an element?","answer":"2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/","support_files":[],"metadata":{"number":"2.1.2","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Give an example of an array of N items that maximizes the number of times the test a[j] < a[min] fails (and, therefore, min gets updated) during the operation of selection sort (Algorithm 2.1).","answer":"2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76","support_files":[],"metadata":{"number":"2.1.3","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the example trace with Algorithm 2.2, how insertion sort sorts the array E A S Y Q U E S T I O N.","answer":"2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.1.4","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"For each of the two conditions in the inner for loop in insertion sort (Algorithm 2.2), describe an array of N items where that condition is always false when the loop terminates.","answer":"2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G","support_files":[],"metadata":{"number":"2.1.5","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Which method runs faster for an array with all keys identical, selection sort or insertion sort?","answer":"2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.","support_files":[],"metadata":{"number":"2.1.6","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Which method runs faster for an array in reverse order, selection sort or insertion sort?","answer":"2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211","support_files":[],"metadata":{"number":"2.1.7","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Suppose that we use insertion sort on a randomly ordered array where elements have only one of three values. Is the running time linear, quadratic, or something in between?","answer":"2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.","support_files":[],"metadata":{"number":"2.1.8","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the example trace with Algorithm 2.3, how shellsort sorts the array E A S Y S H E L L S O R T Q U E S T I O N.","answer":"2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y","support_files":[],"metadata":{"number":"2.1.9","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Why not use selection sort for h-sorting in shellsort?","answer":"2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254","support_files":[],"metadata":{"number":"2.1.10","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Exercise","code_execution":false}} {"question":"Deck sort. Explain how you would put a deck of cards in order by suit (in the order spades, hearts, clubs, diamonds) and by rank within each suit, with the restriction that the cards must be laid out face down in a row, and the only allowed operations are to check the values of two cards and to exchange two cards (keeping them face down).","answer":"2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198","support_files":[],"metadata":{"number":"2.1.13","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Creative Problem","code_execution":false}} {"question":"Dequeue sort. Explain how you would sort a deck of cards, with the restriction that the only allowed operations are to look at the values of the top two cards, to exchange the top two cards, and to move the top card to the bottom of the deck.","answer":"2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards","support_files":[],"metadata":{"number":"2.1.14","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Creative Problem","code_execution":false}} {"question":"Expensive exchange. A clerk at a shipping company is charged with the task of rearranging a number of large crates in order of the time they are to be shipped out. Thus, the cost of compares is very low (just look at the labels) relative to the cost of exchanges (move the crates). The warehouse is nearly full—there is extra space sufficient to hold any one of the crates, but not two. What sorting method should the clerk use?","answer":"2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.","support_files":[],"metadata":{"number":"2.1.15","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Creative Problem","code_execution":false}} {"question":"Shellsort best case. What is the best case for shellsort? Justify your answer.","answer":"2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/","support_files":[],"metadata":{"number":"2.1.20","chapter":2,"chapter_title":"Sorting","section":2.1,"section_title":"Elementary Sorts","type":"Creative Problem","code_execution":false}} {"question":"Give a trace, in the style of the trace given at the beginning of this section, showing how the keys A E Q S U Y E I N O S T are merged with the abstract in-place merge() method.","answer":"2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.2.1","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Give traces, in the style of the trace given with Algorithm 2.4, showing how the keys E A S Y Q U E S T I O N are sorted with top-down mergesort.","answer":"2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/","support_files":[],"metadata":{"number":"2.2.2","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Answer Exercise 2.2.2 for bottom-up mergesort.","answer":"2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76","support_files":[],"metadata":{"number":"2.2.3","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Does the abstract in-place merge produce proper output if and only if the two input subarrays are in sorted order? Prove your answer, or provide a counterexample.","answer":"2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.2.4","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Give the sequence of subarray sizes in the merges performed by both the top-down and the bottom-up mergesort algorithms, for N = 39.","answer":"2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G","support_files":[],"metadata":{"number":"2.2.5","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Write a program to compute the exact value of the number of array accesses used by top-down mergesort and by bottom-up mergesort. Use your program to plot the values for N from 1 to 512, and to compare the exact values with the upper bound 6N lg N.","answer":"2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.","support_files":[],"metadata":{"number":"2.2.6","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Show that the number of compares used by mergesort is monotonically increasing (C(N+1) > C(N) for all N > 0).","answer":"2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211","support_files":[],"metadata":{"number":"2.2.7","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Suppose that Algorithm 2.4 is modified to skip the call on merge() whenever a[mid] <= a[mid+1]. Prove that the number of compares used to mergesort a sorted array is linear.","answer":"2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.","support_files":[],"metadata":{"number":"2.2.8","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Use of a static array like aux[] is inadvisable in library software because multiple clients might use the class concurrently. Give an implementation of Merge that does not use a static array. Do not make aux[] local to merge() (see the Q&A for this section). Hint: Pass the auxiliary array as an argument to the recursive sort().","answer":"2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y","support_files":[],"metadata":{"number":"2.2.9","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Exercise","code_execution":false}} {"question":"Faster merge. Implement a version of merge() that copies the second half of a[] to aux[] in decreasing order and then does the merge back to a[]. This change allows you to remove the code to test that each of the halves has been exhausted from the inner loop. Note: The resulting sort is not stable (see page 341).","answer":"2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254","support_files":[],"metadata":{"number":"2.2.10","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Creative Problem","code_execution":false}} {"question":"Lower bound for average case. Prove that the expected number of compares used by any compare-based sorting algorithm must be at least ~N lg N (assuming that all possible orderings of the input are equally likely). Hint: The expected number of compares is at least the external path length of the compare tree (the sum of the lengths of the paths from the root to all leaves), which is minimized when it is balanced.","answer":"2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198","support_files":[],"metadata":{"number":"2.2.13","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Creative Problem","code_execution":false}} {"question":"Merging sorted queues. Develop a static method that takes two queues of sorted items as arguments and returns a queue that results from merging the queues into sorted order.","answer":"2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards","support_files":[],"metadata":{"number":"2.2.14","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Creative Problem","code_execution":false}} {"question":"Bottom-up queue mergesort. Develop a bottom-up mergesort implementation based on the following approach: Given N items, create N queues, each containing one of the items. Create a queue of the N queues. Then repeatedly apply the merging operation of Exercise 2.2.14 to the first two queues and reinsert the merged queue at the end. Repeat until the queue of queues contains only one queue.","answer":"2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.","support_files":[],"metadata":{"number":"2.2.15","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Creative Problem","code_execution":false}} {"question":"Indirect sort. Develop and implement a version of mergesort that does not rearrange the array, but returns an int[] array perm such that perm[i] is the index of the ith smallest entry in the array.","answer":"2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/","support_files":[],"metadata":{"number":"2.2.20","chapter":2,"chapter_title":"Sorting","section":2.2,"section_title":"Mergesort","type":"Creative Problem","code_execution":false}} {"question":"Show, in the style of the trace given with partition(), how that method partitions the array E A S Y Q U E S T I O N.","answer":"2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.3.1","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the quicksort trace given in this section, how quicksort sorts the array E A S Y Q U E S T I O N (for the purposes of this exercise, ignore the initial shuffle).","answer":"2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/","support_files":[],"metadata":{"number":"2.3.2","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"What is the maximum number of times during the execution of Quick.sort() that the largest item can be exchanged, for an array of length N?","answer":"2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76","support_files":[],"metadata":{"number":"2.3.3","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Suppose that the initial random shuffle is omitted. Give six arrays of ten elements for which Quick.sort() uses the worst-case number of compares.","answer":"2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.3.4","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Give a code fragment that sorts an array that is known to consist of items having just two distinct keys.","answer":"2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G","support_files":[],"metadata":{"number":"2.3.5","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Write a program to compute the exact value of CN, and compare the exact value with the approximation 2N ln N, for N = 100, 1,000, and 10,000.","answer":"2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.","support_files":[],"metadata":{"number":"2.3.6","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Find the expected number of subarrays of size 0, 1, and 2 when quicksort is used to sort an array of N items with distinct keys. If you are mathematically inclined, do the math; if not, run some experiments to develop hypotheses.","answer":"2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211","support_files":[],"metadata":{"number":"2.3.7","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"About how many compares will Quick.sort() make when sorting an array of N items that are all equal?","answer":"2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.","support_files":[],"metadata":{"number":"2.3.8","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Explain what happens when Quick.sort() is run on an array having items with just two distinct keys, and then explain what happens when it is run on an array having just three distinct keys.","answer":"2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y","support_files":[],"metadata":{"number":"2.3.9","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Chebyshev’s inequality says that the probability that a random variable is more than k standard deviations away from the mean is less than 1/k^2. For N = 1 million, use Chebyshev’s inequality to bound the probability that the number of compares used by quicksort is more than 100 billion (.1 N^2).","answer":"2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254","support_files":[],"metadata":{"number":"2.3.10","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"What is the recursive depth of quicksort, in the best, worst, and average cases? This is the size of the stack that the system needs to keep track of the recursive calls. See Exercise 2.3.20 for a way to guarantee that the recursive depth is logarithmic in the worst case.","answer":"2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198","support_files":[],"metadata":{"number":"2.3.13","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Prove that when running quicksort on an array with N distinct items, the probability of comparing the ith and jth largest items is 2/(j - i). Then use this result to prove Proposition K.","answer":"2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards","support_files":[],"metadata":{"number":"2.3.14","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Exercise","code_execution":false}} {"question":"Nuts and bolts. (G. J. E. Rawlins) You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger, but it is not possible to directly compare two nuts or two bolts. Give an efficient method for solving the problem.","answer":"2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.","support_files":[],"metadata":{"number":"2.3.15","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Creative Problem","code_execution":false}} {"question":"Nonrecursive quicksort. Implement a nonrecursive version of quicksort based on a main loop where a subarray is popped from a stack to be partitioned, and the resulting subarrays are pushed onto the stack. Note: Push the larger of the subarrays onto the stack first, which guarantees that the stack will have at most lg N entries.","answer":"2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/","support_files":[],"metadata":{"number":"2.3.20","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Creative Problem","code_execution":false}} {"question":"Java system sort. Add to your implementation from Exercise 2.3.22 code to use the Tukey ninther to compute the partitioning item—choose three sets of three items, take the median of each, then use the median of the three medians as the partitioning item. Also, add a cutoff to insertion sort for small subarrays.","answer":"2.1.23 - Deck sort\n\nThey separate all cards by suit, making the swaps in order to keep cards in the same suit next to each other (dividing the row in 4 areas).\nThen, in each suit, they sort the cards by rank using selection sort.\nIn the second step (once suits are sorted), some of them move the unsorted smaller ranks near to the front while searching for the next smallest rank.","support_files":[],"metadata":{"number":"2.3.23","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Creative Problem","code_execution":false}} {"question":"Samplesort. (W. Frazer and A. McKellar) Implement a quicksort based on using a sample of size 2k - 1. First, sort the sample, then arrange to have the recursive routine partition on the median of the sample and to move the two halves of the rest of the sample to each subarray, such that they can be used in the subarrays, without having to be sorted again. This algorithm is called samplesort.","answer":"2.1.24 - Insertion sort with sentinel\n\nFor 100000 random doubles\n Insertion Sort default is 1.1 times faster than Insertion Sort with a sentinel\n\nInsertion Sort default is slightly faster than Insertion Sort with a sentinel.","support_files":[],"metadata":{"number":"2.3.24","chapter":2,"chapter_title":"Sorting","section":2.3,"section_title":"Quicksort","type":"Creative Problem","code_execution":false}} {"question":"Suppose that the sequence P R I O * R * * I * T * Y * * * Q U E * * * U * E (where a letter means insert and an asterisk means remove the maximum) is applied to an initially empty priority queue. Give the sequence of letters returned by the remove the maximum operations.","answer":"2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.4.1","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Criticize the following idea: To implement find the maximum in constant time, why not use a stack or a queue, but keep track of the maximum value inserted so far, then return that value for find the maximum?","answer":"2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/","support_files":[],"metadata":{"number":"2.4.2","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Provide priority-queue implementations that support insert and remove the maximum, one for each of the following underlying data structures: unordered array, ordered array, unordered linked list, and linked list. Give a table of the worst-case bounds for each operation for each of your four implementations.","answer":"2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76","support_files":[],"metadata":{"number":"2.4.3","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Is an array that is sorted in decreasing order a max-oriented heap?","answer":"2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.4.4","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Give the heap that results when the keys E A S Y Q U E S T I O N are inserted in that order into an initially empty max-oriented heap.","answer":"2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G","support_files":[],"metadata":{"number":"2.4.5","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Using the conventions of Exercise 2.4.1, give the sequence of heaps produced when the operations P R I O * R * * I * T * Y * * * Q U E * * * U * E are performed on an initially empty max-oriented heap.","answer":"2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.","support_files":[],"metadata":{"number":"2.4.6","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"The largest item in a heap must appear in position 1, and the second largest must be in position 2 or position 3. Give the list of positions in a heap of size 31 where the kth largest (i) can appear, and (ii) cannot appear, for k=2, 3, 4 (assuming the values to be distinct).","answer":"2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211","support_files":[],"metadata":{"number":"2.4.7","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Answer the previous exercise for the kth smallest item.","answer":"2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.","support_files":[],"metadata":{"number":"2.4.8","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Draw all of the different heaps that can be made from the five keys A B C D E, then draw all of the different heaps that can be made from the five keys A A A B B.","answer":"2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y","support_files":[],"metadata":{"number":"2.4.9","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Suppose that we wish to avoid wasting one position in a heap-ordered array pq[], putting the largest value in pq[0], its children in pq[1] and pq[2], and so forth, proceeding in level order. Where are the parents and children of pq[k]?","answer":"2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254","support_files":[],"metadata":{"number":"2.4.10","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Describe a way to avoid the j < N test in sink().","answer":"2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198","support_files":[],"metadata":{"number":"2.4.13","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"What is the minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys? Give a heap of size 15 for which the minimum is achieved. Answer the same questions for two and three successive remove the maximum operations.","answer":"2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards","support_files":[],"metadata":{"number":"2.4.14","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.","answer":"2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.","support_files":[],"metadata":{"number":"2.4.15","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Prove that sink-based heap construction uses fewer than 2N compares and fewer than N exchanges.","answer":"2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/","support_files":[],"metadata":{"number":"2.4.20","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Exercise","code_execution":false}} {"question":"Multiway heaps. Considering the cost of compares only, and assuming that it takes t compares to find the largest of t items, find the value of t that minimizes the coefficient of N lg N in the compare count when a t-ary heap is used in heapsort. First, assume a straightforward generalization of sink(); then, assume that Floyd’s method can save one compare in the inner loop.","answer":"2.1.23 - Deck sort\n\nThey separate all cards by suit, making the swaps in order to keep cards in the same suit next to each other (dividing the row in 4 areas).\nThen, in each suit, they sort the cards by rank using selection sort.\nIn the second step (once suits are sorted), some of them move the unsorted smaller ranks near to the front while searching for the next smallest rank.","support_files":[],"metadata":{"number":"2.4.23","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Priority queue with explicit links. Implement a priority queue using a heap-ordered binary tree, but use a triply linked structure instead of an array. You will need three links per node: two to traverse down the tree and one to traverse up the tree. Your implementation should guarantee logarithmic running time per operation, even if no maximum priority-queue size is known ahead of time.","answer":"2.1.24 - Insertion sort with sentinel\n\nFor 100000 random doubles\n Insertion Sort default is 1.1 times faster than Insertion Sort with a sentinel\n\nInsertion Sort default is slightly faster than Insertion Sort with a sentinel.","support_files":[],"metadata":{"number":"2.4.24","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Computational number theory. Write a program CubeSum.java that prints out all integers of the form a^3 + b^3 where a and b are integers between 0 and N in sorted order, without using excessive space. That is, instead of computing an array of the N^2 sums and sorting them, build a minimum-oriented priority queue, initially containing (0^3, 0, 0), (1^3, 1, 0), (2^3, 2, 0), . . . , (N^3, N, 0). Then, while the priority queue is nonempty, remove the smallest item(i^3 + j^3, i, j), print it, and then, if j < N, insert the item (i^3 + (j+1)^3, i, j+1). Use this program to find all distinct integers a, b, c, and d between 0 and 10^6 such that a^3 + b^3 = c^3 + d^3.","answer":"2.1.25 - Insertion sort without exchanges\n\nFor 100000 random doubles\n Insertion Sort default is 0.7 times faster than Insertion Sort without exchanges\n\nInsertion Sort without exchanges is faster than Insertion Sort default.","support_files":[],"metadata":{"number":"2.4.25","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Heap without exchanges. Because the exch() primitive is used in the sink() and swim() operations, the items are loaded and stored twice as often as necessary. Give more efficient implementations that avoid this inefficiency, a la insertion sort (see Exercise 2.1.25).","answer":"2.1.26 - Primitive types\n\nFor 100000 random doubles\n Insertion Sort with primitives is 2.0 times faster than Insertion Sort with objects\n\nInsertion Sort with primitives is faster than Insertion Sor with objects.","support_files":[],"metadata":{"number":"2.4.26","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Find the minimum. Add a min() method to MaxPQ. Your implementation should use constant time and constant extra space.","answer":"2.1.27 - Shellsort is subquadratic\n\nFor a total of 11 experiments with 128, 256, ..., 262,144 values\n\nShell Sort is 343.0 times faster than Selection Sort\nShell Sort is 338.8 times faster than Insertion Sort","support_files":[],"metadata":{"number":"2.4.27","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Selection filter. Write a TopM client that reads points (x, y, z) from standard input, takes a value M from the command line, and prints the M points that are closest to the origin in Euclidean distance. Estimate the running time of your client for N = 10^8 and M = 10^4.","answer":"2.1.28 - Equal keys\n\nFrom the book we know that:\nProposition A. Selection sort uses ~(N^2 / 2) compares and N exchanges to sort an array of length N.\nProposition B. Insertion sort uses ~(N^2 / 4) compares and ~(N^2 / 4) exchanges to sort a randomly ordered array of\nlength N with distinct keys, on the average. The worst case is ~(N^2 / 2) compares and ~(N^2 / 2) exchanges and the best\ncase is N - 1 compares and 0 exchanges.\n\nThus the running time of selection sort is bound by O(N^2 / 2) and insertion sort averages on O(N^2 / 2)\n(this is because ~(N^2 / 4) compares + ~(N^2 / 4) exchanges = ~(N^2 / 4)).\n\nFor arrays with 2 key values (assuming value 1 and value 2) of equal probability:\n* Selection sort: it still needs to scan N - K elements to sort the Kth element.\n So its asymptotic running time remains the same O(N^2 / 2).\n* Insertion sort: when sorting the (K + 1)th element, there are already K / 2 ones and K / 2 twos sorted.\n Thus the (random variable) expected value of the running time for sorting the (K + 1)th element is:\n 0.5 * 1 + 0.5 * K\n Thus the total running time for K = 0, 1, 2, ..., N is:\n 0.5 * N + ((N + 1) * N / 2) * 0.5 = 3N/4 + (N ^ 2) / 4 ~= O(N^2 / 4)\n Comparing O(N^2 / 4) against O(N^2 / 2) we can make the hypothesis that the running time of insertion sort with\n 2 key values is half of that for random values.\n\nHypothesis: \n1- Selection sort will take the same time for both arrays with different values and arrays with only 2 possible values.\n2- Insertion sort will take half the same for arrays with only 2 possible values than for arrays with different values.\n\nValidation:\n\nSelection Sort\nFor an array of size 128: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 256: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 512: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 1024: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 2048: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 4096: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 8192: \nTime for an array with any values: 0.1\nTime for an array with 2 values: 0.1\n\nFor an array of size 16384: \nTime for an array with any values: 0.2\nTime for an array with 2 values: 0.2\n\nFor an array of size 32768: \nTime for an array with any values: 1.0\nTime for an array with 2 values: 0.7\n\nFor an array of size 65536: \nTime for an array with any values: 4.4\nTime for an array with 2 values: 3.0\n\nFor an array of size 131072: \nTime for an array with any values: 20.9\nTime for an array with 2 values: 11.7\n\nInsertion Sort\nFor an array of size 128: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 256: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 512: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 1024: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 2048: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 4096: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 8192: \nTime for an array with any values: 0.1\nTime for an array with 2 values: 0.0\n\nFor an array of size 16384: \nTime for an array with any values: 0.2\nTime for an array with 2 values: 0.1\n\nFor an array of size 32768: \nTime for an array with any values: 1.0\nTime for an array with 2 values: 0.4\n\nFor an array of size 65536: \nTime for an array with any values: 4.3\nTime for an array with 2 values: 1.5\n\nFor an array of size 131072: \nTime for an array with any values: 18.9\nTime for an array with 2 values: 6.3\n\n--------\nResult:\n1- Selection sort is faster for arrays with only 2 possible values than for arrays with different values.\n2- Insertion sort is a lot faster (about a third of the time) for arrays with only 2 possible values than for arrays with different values.\n\nAlso, insertion sort is faster than selection sort for sorting arrays with only 2 possible values.\n\nThanks to faame (https://github.com/faame) for improving the analysis.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/216","support_files":[],"metadata":{"number":"2.4.28","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Min/max priority queue. Design a data type that supports the following operations: insert, delete the maximum, and delete the minimum (all in logarithmic time); and find the maximum and find the minimum (both in constant time). Hint: Use two heaps.","answer":"2.1.29 - Shellsort increments\n\nSedgewicks's sequence is faster than the 3N + 1 sequence.\n\nExperiments:\n\nFor an array of size 32768: \n3N + 1 sequence: 0.0 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 65536: \n3N + 1 sequence: 0.0 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 131072: \n3N + 1 sequence: 0.1 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 262144: \n3N + 1 sequence: 0.1 \nSedgewicks's sequence: 0.1 \n\nFor an array of size 524288: \n3N + 1 sequence: 0.3 \nSedgewicks's sequence: 0.3 \n\nFor an array of size 1048576: \n3N + 1 sequence: 1.0 \nSedgewicks's sequence: 0.7 \n\nFor an array of size 2097152: \n3N + 1 sequence: 2.5 \nSedgewicks's sequence: 1.8 \n\nFor an array of size 4194304: \n3N + 1 sequence: 7.2 \nSedgewicks's sequence: 4.5 \n\nFor an array of size 8388608: \n3N + 1 sequence: 18.4 \nSedgewicks's sequence: 11.2 \n\nFor an array of size 16777216: \n3N + 1 sequence: 46.0 \nSedgewicks's sequence: 26.6","support_files":[],"metadata":{"number":"2.4.29","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Dynamic median-finding. Design a data type that supports insert in logarithmic time, find the median in constant time, and delete the median in logarithmic time. Hint: Use a min-heap and a max-heap.","answer":"2.1.30 - Geometric increments\n\nBest 1 tValue: 2.10\nBest 1 sequence:\n1 2 4 9 19 40 85 180 378 794 1667 3502 7355 15447 32439 68122 143056 300419 630880\n\nBest 2 tValue: 2.40\nBest 2 sequence:\n1 2 5 13 33 79 191 458 1100 2641 6340 15216 36520 87648 210357 504857\n\nBest 3 tValue: 2.20\nBest 3 sequence:\n1 2 4 10 23 51 113 249 548 1207 2655 5843 12855 28281 62218 136880 301136 662499","support_files":[],"metadata":{"number":"2.4.30","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Fast insert. Develop a compare-based implementation of the MinPQ API such that insert uses ~log log N compares and delete the minimum uses ~2 log N compares. Hint: Use binary search on parent pointers to find the ancestor in swim().","answer":"2.1.31 - Doubling test\n\nSelection sort and insertion sort are quadratic for random inputs.\n\n N Predicted Time Time Ratio\n\nSelection sort\n 2000 0.0 0.0 0.6\n 4000 0.0 0.0 2.3\n 8000 0.1 0.1 3.8\n 16000 0.2 0.3 4.7\n 32000 1.0 1.2 4.9\n 64000 4.9 5.1 4.1\n128000 20.3 20.6 4.1\n256000 82.2 124.6 6.1\n\nInsertion sort\n 2000 0.0 0.0 2.4\n 4000 0.1 0.0 0.9\n 8000 0.1 0.1 4.1\n 16000 0.2 0.3 4.3\n 32000 1.1 1.1 4.3\n 64000 4.6 4.9 4.3\n128000 19.6 22.8 4.7\n256000 91.3 125.7 5.5\n\nHypothesis: Shell sort is sub quadratic for random inputs. It's worse case (with the 3N + 1 increment sequence) is N ^ 3/2.\n\nShell sort\n 2000 0.0 0.0 0.5\n 4000 0.0 0.0 1.0\n 8000 0.0 0.0 2.0\n 16000 0.0 0.0 1.0\n 32000 0.0 0.0 2.0\n 64000 0.0 0.0 2.5\n128000 0.1 0.1 2.5\n256000 0.1 0.1 2.4\n512000 0.3 0.3 2.8\n1024000 1.0 1.0 2.8\n2048000 2.7 2.4 2.5\n4096000 6.8 6.4 2.7\n8192000 18.1 18.7 2.9\n16384000 52.7 44.4 2.4\n32768000 125.3 123.6 2.8\n65536000 348.7 304.6 2.5\n\nHypothesis validated.","support_files":[],"metadata":{"number":"2.4.31","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Index priority-queue implementation (additional operations). Add minIndex(), change(), and delete() to your implementation of Exercise 2.4.33.","answer":"2.1.34 - Corner cases\n\nAs expected:\nFor ordered arrays insertion sort runs in linear time, and is faster than selection sort.\nFor reverse ordered arrays insertion sort runs much slower because it has to swap all values until the beginning of the array.\nFor same keys, just like with ordered arrays, insertion sort runs in linear time.\nFor 2 distinct values, insertion sort has to do less swaps, running faster than selection sort.\nFor size 1 and size 0 arrays all sorts run fast.\nShell sort is faster than selection sort and insertion sort in all cases. \n\n Sort Type Array Length Time\nORDERED ARRAY\n SELECTION 10000 0.05\n INSERTION 10000 0.00\n SHELL 10000 0.00\n SELECTION 20000 0.18\n INSERTION 20000 0.00\n SHELL 20000 0.00\n SELECTION 40000 0.81\n INSERTION 40000 0.00\n SHELL 40000 0.00\n SELECTION 80000 2.99\n INSERTION 80000 0.00\n SHELL 80000 0.00\n SELECTION 160000 12.04\n INSERTION 160000 0.00\n SHELL 160000 0.00\n\n\nREVERSE ORDERED ARRAY\n SELECTION 10000 0.10\n INSERTION 10000 0.25\n SHELL 10000 0.00\n SELECTION 20000 0.33\n INSERTION 20000 0.62\n SHELL 20000 0.00\n SELECTION 40000 1.15\n INSERTION 40000 2.45\n SHELL 40000 0.00\n SELECTION 80000 4.85\n INSERTION 80000 10.65\n SHELL 80000 0.01\n SELECTION 160000 17.66\n INSERTION 160000 42.76\n SHELL 160000 0.01\n\n\nSAME KEYS ARRAY\n SELECTION 10000 0.09\n INSERTION 10000 0.00\n SHELL 10000 0.00\n SELECTION 20000 0.29\n INSERTION 20000 0.00\n SHELL 20000 0.00\n SELECTION 40000 1.16\n INSERTION 40000 0.00\n SHELL 40000 0.00\n SELECTION 80000 4.64\n INSERTION 80000 0.00\n SHELL 80000 0.00\n SELECTION 160000 17.01\n INSERTION 160000 0.00\n SHELL 160000 0.00\n\n\nTWO VALUES ARRAY\n SELECTION 10000 0.07\n INSERTION 10000 0.04\n SHELL 10000 0.00\n SELECTION 20000 0.29\n INSERTION 20000 0.17\n SHELL 20000 0.00\n SELECTION 40000 1.07\n INSERTION 40000 0.65\n SHELL 40000 0.00\n SELECTION 80000 4.68\n INSERTION 80000 2.66\n SHELL 80000 0.00\n SELECTION 160000 18.59\n INSERTION 160000 10.46\n SHELL 160000 0.00\n\n\nSIZE 1 ARRAY\n SELECTION 1 0.00\n INSERTION 1 0.00\n SHELL 1 0.00\n\n\nSIZE 0 ARRAY\n SELECTION 0 0.00\n INSERTION 0 0.00\n SHELL 0 0.00","support_files":[],"metadata":{"number":"2.4.34","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Sampling from a discrete probability distribution. Write a class Sample with a constructor that takes an array p[] of double values as argument and supports the following two operations: random()—return an index i with probability p[i]/T (where T is the sum of the numbers in p[])—and change(i, v)—change the value of p[i] to v. Hint: Use a complete binary tree where each node has implied weight p[i]. Store in each node the cumulative weight of all the nodes in its subtree. To generate a random index, pick a random number between 0 and T and use the cumulative weights to determine which branch of the subtree to explore. When updating p[i], change all of the weights of the nodes on the path from the root to i. Avoid explicit pointers, as we do for heaps.","answer":"2.1.35 - Nonuniform distributions\n\nHypotheses:\nSelection sort will run with the same speed in all distributions.\nInsertion sort will run faster than selection sort for Gaussian and Discrete distributions, but with a similar speed for Poisson and Geometric distributions.\nShell sort will run faster than selection sort and insertion sort for all distributions.\n\nAfter testing the hypotheses:\nSelection sort ran faster for Gaussian and Discrete distributions than for Poisson and Geometric distributions.\nInsertion sort ran faster than selection sort for all distributions.\nShell sort ran faster than selection sort and insertion sort for all distributions.\n\n Sort Type Array Length Time\nGAUSSIAN DISTRIBUTION\n SELECTION 10000 0.13\n INSERTION 10000 0.10\n SHELL 10000 0.01\n SELECTION 20000 0.49\n INSERTION 20000 0.38\n SHELL 20000 0.01\n SELECTION 40000 2.04\n INSERTION 40000 1.86\n SHELL 40000 0.01\n SELECTION 80000 8.53\n INSERTION 80000 8.37\n SHELL 80000 0.02\n SELECTION 160000 39.54\n INSERTION 160000 35.89\n SHELL 160000 0.06\n\n\nPOISSON DISTRIBUTION\n SELECTION 10000 0.28\n INSERTION 10000 0.16\n SHELL 10000 0.00\n SELECTION 20000 1.24\n INSERTION 20000 0.59\n SHELL 20000 0.00\n SELECTION 40000 4.67\n INSERTION 40000 2.44\n SHELL 40000 0.00\n SELECTION 80000 19.11\n INSERTION 80000 9.71\n SHELL 80000 0.01\n SELECTION 160000 67.54\n INSERTION 160000 39.29\n SHELL 160000 0.01\n\n\nGEOMETRIC DISTRIBUTION\n SELECTION 10000 0.26\n INSERTION 10000 0.16\n SHELL 10000 0.00\n SELECTION 20000 1.06\n INSERTION 20000 0.63\n SHELL 20000 0.00\n SELECTION 40000 4.33\n INSERTION 40000 1.41\n SHELL 40000 0.00\n SELECTION 80000 15.51\n INSERTION 80000 5.32\n SHELL 80000 0.01\n SELECTION 160000 69.14\n INSERTION 160000 20.67\n SHELL 160000 0.02\n\n\nDISCRETE DISTRIBUTION\n SELECTION 10000 0.09\n INSERTION 10000 0.06\n SHELL 10000 0.00\n SELECTION 20000 0.35\n INSERTION 20000 0.22\n SHELL 20000 0.00\n SELECTION 40000 1.37\n INSERTION 40000 0.88\n SHELL 40000 0.00\n SELECTION 80000 5.58\n INSERTION 80000 3.47\n SHELL 80000 0.00\n SELECTION 160000 22.31\n INSERTION 160000 14.13\n SHELL 160000 0.00","support_files":[],"metadata":{"number":"2.4.35","chapter":2,"chapter_title":"Sorting","section":2.4,"section_title":"Priority Queues","type":"Creative Problem","code_execution":false}} {"question":"Consider the following implementation of the compareTo() method for String. How does the third line help with efficiency?\npublic int compareTo(String that) \n{\n if (this == that) return 0; // this line\n int n = Math.min(this.length(), that.length());\n for (int i = 0; i < n; i++)\n {\n if (this.charAt(i) < that.charAt(i)) return -1;\n else if (this.charAt(i) > that.charAt(i)) return +1;\n }\n return this.length() - that.length(); \n}","answer":"2.1.1\n\t\ta[]\ni min 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 1 E A S Y Q U E S T I O N\n1 1 A E S Y Q U E S T I O N\n2 6 A E S Y Q U E S T I O N\n3 9 A E E Y Q U S S T I O N\n4 11 A E E I Q U S S T Y O N\n5 10 A E E I N U S S T Y O Q\n6 11 A E E I N O S S T Y U Q\n7 7 A E E I N O Q S T Y U S\n8 11 A E E I N O Q S T Y U S\n9 11 A E E I N O Q S S Y U T\n10 10 A E E I N O Q S S T U Y\n11 11 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.5.1","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Write a program that reads a list of words from standard input and prints all two-word compound words in the list. For example, if after, thought, and afterthought are in the list, then afterthought is a compound word.","answer":"2.1.2\nThe maximum number of exchanges involving any particular item during selection sort is N - 1.\nThis happens when the first item has the highest value in the unsorted array and the other values are sorted.\nFor example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times.\nThe average number of exchanges involving an item is exactly 2, because there are exactly N exchanges and N items (and each exchange involves two items).\n\nReference: https://algs4.cs.princeton.edu/21elementary/","support_files":[],"metadata":{"number":"2.5.2","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Criticize the following implementation of a class intended to represent account balances. Why is compareTo() a flawed implementation of the Comparable interface?\npublic class Balance implements Comparable \n{\n ...\n private double amount;\n public int compareTo(Balance that)\n {\n if (this.amount < that.amount - 0.005) return -1;\n if (this.amount > that.amount + 0.005) return +1;\n return 0;\n }\n ... \n}\nDescribe a way to fix this problem.","answer":"2.1.3\nArray: H G F E D C B A\n\nThanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/76","support_files":[],"metadata":{"number":"2.5.3","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Implement a method String[] dedup(String[] a) that returns the objects in a[] in sorted order, with duplicates removed.","answer":"2.1.4\n\t\ta[]\ni j 0 1 2 3 4 5 6 7 8 9 10 11 \n\tE A S Y Q U E S T I O N\n0 0 E A S Y Q U E S T I O N\n1 0 A E S Y Q U E S T I O N\n2 2 A E S Y Q U E S T I O N\n3 3 A E S Y Q U E S T I O N\n4 2 A E Q S Y U E S T I O N\n5 4 A E Q S U Y E S T I O N\n6 2 A E E Q S U Y S T I O N\n7 5 A E E Q S S U Y T I O N\n8 6 A E E Q S S T U Y I O N\n9 3 A E E I Q S S T U Y O N\n10 4 A E E I O Q S S T U Y N\n11 4 A E E I N O Q S S T U Y\n\tA E E I N O Q S S T U Y","support_files":[],"metadata":{"number":"2.5.4","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Explain why selection sort is not stable.","answer":"2.1.5\n\nCondition 1: j > 0 -> When the array is reverse ordered\nZ Q K D C B A\n\nCondition 2: less(a[j], a[j - 1]) -> When the array is ordered\nA B C D E F G","support_files":[],"metadata":{"number":"2.5.5","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Implement a recursive version of select().","answer":"2.1.6\n\nInsertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements,\nrunning in linear time. Selection sort will exchange each element with itself and will run in quadratic time.\n\nThanks to glucu (https://github.com/glucu) for correcting the number of exchanges done in selection sort.","support_files":[],"metadata":{"number":"2.5.6","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"About how many compares are required, on the average, to find the smallest of N items using select()?","answer":"2.1.7\n\nSelection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will\nonly make N exchanges, while insertion sort will make N * N / 2 exchanges.\n\nThanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and\nBOTbkcd (https://github.com/BOTbkcd) for correcting the number of exchanges in selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/194 and\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/211","support_files":[],"metadata":{"number":"2.5.7","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Write a program Frequency that reads strings from standard input and prints the number of times each string occurs, in descending order of frequency.","answer":"2.1.8\n\nQuadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal.\nWith three possible values the running time quadratic.","support_files":[],"metadata":{"number":"2.5.8","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Develop a data type that allows you to write a client that can sort a file such as the one shown at right.","answer":"2.1.9\n\t\t\t\ta[]\n h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n\t E A S Y S H E L L S O R T Q U E S T I O N\n13 13 13 E A S Y S H E L L S O R T Q U E S T I O N\n13 14 14 E A S Y S H E L L S O R T Q U E S T I O N\n13 15 2 E A E Y S H E L L S O R T Q U S S T I O N\n13 16 3 E A E S S H E L L S O R T Q U S Y T I O N\n13 17 17 E A E S S H E L L S O R T Q U S Y T I O N\n13 18 18 E A E S S H E L L S O R T Q U S Y T I O N\n13 19 19 E A E S S H E L L S O R T Q U S Y T I O N\n13 20 20 E A E S S H E L L S O R T Q U S Y T I O N\n\t E A E S S H E L L S O R T Q U S Y T I O N\n 4 4 4 E A E S S H E L L S O R T Q U S Y T I O N\n 4 5 5 E A E S S H E L L S O R T Q U S Y T I O N\n 4 6 6 E A E S S H E L L S O R T Q U S Y T I O N\n 4 7 3 E A E L S H E S L S O R T Q U S Y T I O N\n 4 8 4 E A E L L H E S S S O R T Q U S Y T I O N\n 4 9 9 E A E L L H E S S S O R T Q U S Y T I O N\n 4 10 10 E A E L L H E S S S O R T Q U S Y T I O N\n 4 11 7 E A E L L H E R S S O S T Q U S Y T I O N\n 4 12 12 E A E L L H E R S S O S T Q U S Y T I O N\n 4 13 9 E A E L L H E R S Q O S T S U S Y T I O N\n 4 14 14 E A E L L H E R S Q O S T S U S Y T I O N\n 4 15 15 E A E L L H E R S Q O S T S U S Y T I O N\n 4 16 16 E A E L L H E R S Q O S T S U S Y T I O N\n 4 17 17 E A E L L H E R S Q O S T S U S Y T I O N\n 4 18 10 E A E L L H E R S Q I S T S O S Y T U O N\n 4 19 7 E A E L L H E O S Q I R T S O S Y T U S N\n 4 20 8 E A E L L H E O N Q I R S S O S T T U S Y\n\t E A E L L H E O N Q I R S S O S T T U S Y\n 1 1 0 A E E L L H E O N Q I R S S O S T T U S Y\n 1 2 2 A E E L L H E O N Q I R S S O S T T U S Y\n 1 3 3 A E E L L H E O N Q I R S S O S T T U S Y\n 1 4 4 A E E L L H E O N Q I R S S O S T T U S Y\n 1 5 3 A E E H L L E O N Q I R S S O S T T U S Y\n 1 6 3 A E E E H L L O N Q I R S S O S T T U S Y\n 1 7 7 A E E E H L L O N Q I R S S O S T T U S Y\n 1 8 7 A E E E H L L N O Q I R S S O S T T U S Y\n 1 9 9 A E E E H L L N O Q I R S S O S T T U S Y\n 1 10 5 A E E E H I L L N O Q R S S O S T T U S Y\n 1 11 11 A E E E H I L L N O Q R S S O S T T U S Y\n 1 12 12 A E E E H I L L N O Q R S S O S T T U S Y\n 1 13 13 A E E E H I L L N O Q R S S O S T T U S Y\n 1 14 10 A E E E H I L L N O O Q R S S S T T U S Y\n 1 15 15 A E E E H I L L N O O Q R S S S T T U S Y\n 1 16 16 A E E E H I L L N O O Q R S S S T T U S Y\n 1 17 17 A E E E H I L L N O O Q R S S S T T U S Y\n 1 18 18 A E E E H I L L N O O Q R S S S T T U S Y\n 1 19 16 A E E E H I L L N O O Q R S S S S T T U Y\n 1 20 20 A E E E H I L L N O O Q R S S S S T T U Y\n\t A E E E H I L L N O O Q R S S S S T T U Y","support_files":[],"metadata":{"number":"2.5.9","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Create a data type Version that represents a software version number, such as 115.1.1, 115.10.1, 115.10.2. Implement the Comparable interface so that 115.1.1 is less than 115.10.1, and so forth.","answer":"2.1.10\nInsertion sort is faster than selection sort for h-sorting because as \"h\" decreases, the array becomes partially sorted.\nInsertion sort makes less comparisons in partially sorted arrays than selection sort.\nAlso, when h-sorting, eventually h will have an increment value of 1.\nUsing selection sort with an increment value of 1 would be the same as using the standard selection sort algorithm from the beginning.\nThis would make the steps with the previous increments to be unnecessary work.\n\nThanks to jaeheonshim (https://github.com/jaeheonshim) for adding an extra reason not to use selection sort.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/254","support_files":[],"metadata":{"number":"2.5.10","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Load balancing. Write a program LPT.java that takes an integer M as a command-line argument, reads job names and processing times from standard input and prints a schedule assigning the jobs to M processors that approximately minimizes the time when the last job completes using the longest processing time first rule, as described on page 349.","answer":"2.1.13 - Deck sort\nI would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank.\nAs we are dealing with physical objects it makes sense to minimize the number of swaps.\nWith selection sort it may be needed to look at more cards than insertion sort (twice as many in the average case),\nbut swaps will be required at most 52 times versus at most 676 times.\n\nThanks to zefrawg (https://github.com/zefrawg) and nedas-dev (https://github.com/nedas-dev) for improving this exercise:\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/198","support_files":[],"metadata":{"number":"2.5.13","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sort by reverse domain. Write a data type Domain that represents domain names, including an appropriate compareTo() method where the natural order is in order of the reverse domain name. For example, the reverse domain of cs.princeton.edu is edu.princeton.cs. This is useful for web log analysis. Hint: Use s.split(\"\\\\.\") to split the string s into tokens, delimited by dots. Write a client that reads domain names from standard input and prints the reverse domains in sorted order.","answer":"2.1.14 - Dequeue sort\nI would use a variation of bubble sort.\n\n1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them.\n2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck.\n3- I would send the top card to the bottom of the deck.\n4- I would repeat steps 1 and 3 until the marked card becomes the second card in the deck\n5- I would send the top card to the bottom of the deck (and the marked card is now at the top, signaling that a iteration is over)\n6- If there were no swaps in this iteration, the deck is sorted. Otherwise, repeat steps 1 to 6.\n\nNice explanation here: \nhttp://stackoverflow.com/questions/38061140/sort-a-deck-of-cards","support_files":[],"metadata":{"number":"2.5.14","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Spam campaign. To initiate an illegal spam campaign, you have a list of email addresses from various domains (the part of the email address that follows the @ symbol). To better forge the return addresses, you want to send the email from another user at the same domain. For example, you might want to forge an email from wayne@princeton.edu to rs@princeton.edu. How would you process the email list to make this an efficient task?","answer":"2.1.15 - Expensive exchange\n\nThe clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem.\nAnd it guarantees a cost of at most N exchanges.","support_files":[],"metadata":{"number":"2.5.15","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Idle time. Suppose that a parallel machine processes N jobs. Write a program that, given the list of job start and finish times, finds the largest interval where the machine is idle and the largest interval where the machine is not idle.","answer":"2.1.20 - Shellsort best case\n\nJust like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to \nbe compared only once in each iteration. \nThe time complexity in this case is O(n log n).\n\nGood explanation: https://www.toptal.com/developers/sorting-algorithms/shell-sort\nhttp://www.codingeek.com/algorithms/shell-sort-algorithm-explanation-implementation-and-complexity/","support_files":[],"metadata":{"number":"2.5.20","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sampling for selection. Investigate the idea of using sampling to improve selection. Hint: Using the median may not always be helpful.","answer":"2.1.23 - Deck sort\n\nThey separate all cards by suit, making the swaps in order to keep cards in the same suit next to each other (dividing the row in 4 areas).\nThen, in each suit, they sort the cards by rank using selection sort.\nIn the second step (once suits are sorted), some of them move the unsorted smaller ranks near to the front while searching for the next smallest rank.","support_files":[],"metadata":{"number":"2.5.23","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Stable priority queue. Develop a stable priority-queue implementation (which returns duplicate keys in the same order in which they were inserted).","answer":"2.1.24 - Insertion sort with sentinel\n\nFor 100000 random doubles\n Insertion Sort default is 1.1 times faster than Insertion Sort with a sentinel\n\nInsertion Sort default is slightly faster than Insertion Sort with a sentinel.","support_files":[],"metadata":{"number":"2.5.24","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Points in the plane. Write three static comparators for the Point2D data type of page 77, one that compares points by their x coordinate, one that compares them by their y coordinate, and one that compares them by their distance from the origin. Write two non-static comparators for the Point2D data type, one that compares them by their distance to a specified point and one that compares them by their polar angle with respect to a specified point.","answer":"2.1.25 - Insertion sort without exchanges\n\nFor 100000 random doubles\n Insertion Sort default is 0.7 times faster than Insertion Sort without exchanges\n\nInsertion Sort without exchanges is faster than Insertion Sort default.","support_files":[],"metadata":{"number":"2.5.25","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Simple polygon. Given N points in the plane, draw a simple polygon with N points as vertices. Hint: Find the point p with the smallest y coordinate, breaking ties with the smallest x coordinate. Connect the points in increasing order of the polar angle they make with p.","answer":"2.1.26 - Primitive types\n\nFor 100000 random doubles\n Insertion Sort with primitives is 2.0 times faster than Insertion Sort with objects\n\nInsertion Sort with primitives is faster than Insertion Sor with objects.","support_files":[],"metadata":{"number":"2.5.26","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sorting parallel arrays. When sorting parallel arrays, it is useful to have a version of a sorting routine that returns a permutation, say index[], of the indices in sorted order. Add a method indirectSort() to Insertion that takes an array of Comparable objects a[] as argument, but instead of rearranging the entries of a[] returns an integer array index[] so that a[index[0]] through a[index[N-1]] are the items in ascending order.","answer":"2.1.27 - Shellsort is subquadratic\n\nFor a total of 11 experiments with 128, 256, ..., 262,144 values\n\nShell Sort is 343.0 times faster than Selection Sort\nShell Sort is 338.8 times faster than Insertion Sort","support_files":[],"metadata":{"number":"2.5.27","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sort files by name. Write a program FileSorter that takes the name of a directory as a command-line argument and prints out all of the files in the current directory, sorted by file name. Hint: Use the File data type.","answer":"2.1.28 - Equal keys\n\nFrom the book we know that:\nProposition A. Selection sort uses ~(N^2 / 2) compares and N exchanges to sort an array of length N.\nProposition B. Insertion sort uses ~(N^2 / 4) compares and ~(N^2 / 4) exchanges to sort a randomly ordered array of\nlength N with distinct keys, on the average. The worst case is ~(N^2 / 2) compares and ~(N^2 / 2) exchanges and the best\ncase is N - 1 compares and 0 exchanges.\n\nThus the running time of selection sort is bound by O(N^2 / 2) and insertion sort averages on O(N^2 / 2)\n(this is because ~(N^2 / 4) compares + ~(N^2 / 4) exchanges = ~(N^2 / 4)).\n\nFor arrays with 2 key values (assuming value 1 and value 2) of equal probability:\n* Selection sort: it still needs to scan N - K elements to sort the Kth element.\n So its asymptotic running time remains the same O(N^2 / 2).\n* Insertion sort: when sorting the (K + 1)th element, there are already K / 2 ones and K / 2 twos sorted.\n Thus the (random variable) expected value of the running time for sorting the (K + 1)th element is:\n 0.5 * 1 + 0.5 * K\n Thus the total running time for K = 0, 1, 2, ..., N is:\n 0.5 * N + ((N + 1) * N / 2) * 0.5 = 3N/4 + (N ^ 2) / 4 ~= O(N^2 / 4)\n Comparing O(N^2 / 4) against O(N^2 / 2) we can make the hypothesis that the running time of insertion sort with\n 2 key values is half of that for random values.\n\nHypothesis: \n1- Selection sort will take the same time for both arrays with different values and arrays with only 2 possible values.\n2- Insertion sort will take half the same for arrays with only 2 possible values than for arrays with different values.\n\nValidation:\n\nSelection Sort\nFor an array of size 128: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 256: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 512: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 1024: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 2048: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 4096: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 8192: \nTime for an array with any values: 0.1\nTime for an array with 2 values: 0.1\n\nFor an array of size 16384: \nTime for an array with any values: 0.2\nTime for an array with 2 values: 0.2\n\nFor an array of size 32768: \nTime for an array with any values: 1.0\nTime for an array with 2 values: 0.7\n\nFor an array of size 65536: \nTime for an array with any values: 4.4\nTime for an array with 2 values: 3.0\n\nFor an array of size 131072: \nTime for an array with any values: 20.9\nTime for an array with 2 values: 11.7\n\nInsertion Sort\nFor an array of size 128: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 256: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 512: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 1024: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 2048: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 4096: \nTime for an array with any values: 0.0\nTime for an array with 2 values: 0.0\n\nFor an array of size 8192: \nTime for an array with any values: 0.1\nTime for an array with 2 values: 0.0\n\nFor an array of size 16384: \nTime for an array with any values: 0.2\nTime for an array with 2 values: 0.1\n\nFor an array of size 32768: \nTime for an array with any values: 1.0\nTime for an array with 2 values: 0.4\n\nFor an array of size 65536: \nTime for an array with any values: 4.3\nTime for an array with 2 values: 1.5\n\nFor an array of size 131072: \nTime for an array with any values: 18.9\nTime for an array with 2 values: 6.3\n\n--------\nResult:\n1- Selection sort is faster for arrays with only 2 possible values than for arrays with different values.\n2- Insertion sort is a lot faster (about a third of the time) for arrays with only 2 possible values than for arrays with different values.\n\nAlso, insertion sort is faster than selection sort for sorting arrays with only 2 possible values.\n\nThanks to faame (https://github.com/faame) for improving the analysis.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/216","support_files":[],"metadata":{"number":"2.5.28","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sort files by size and date of last modification. Write comparators for the type File to order by increasing/decreasing order of file size, ascending/descending order of file name, and ascending/descending order of last modification date. Use these comparators in a program LS that takes a command-line argument and lists the files in the current directory according to a specified order, e.g., \"-t\" to sort by timestamp. Support multiple flags to break ties. Be sure to use a stable sort.","answer":"2.1.29 - Shellsort increments\n\nSedgewicks's sequence is faster than the 3N + 1 sequence.\n\nExperiments:\n\nFor an array of size 32768: \n3N + 1 sequence: 0.0 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 65536: \n3N + 1 sequence: 0.0 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 131072: \n3N + 1 sequence: 0.1 \nSedgewicks's sequence: 0.0 \n\nFor an array of size 262144: \n3N + 1 sequence: 0.1 \nSedgewicks's sequence: 0.1 \n\nFor an array of size 524288: \n3N + 1 sequence: 0.3 \nSedgewicks's sequence: 0.3 \n\nFor an array of size 1048576: \n3N + 1 sequence: 1.0 \nSedgewicks's sequence: 0.7 \n\nFor an array of size 2097152: \n3N + 1 sequence: 2.5 \nSedgewicks's sequence: 1.8 \n\nFor an array of size 4194304: \n3N + 1 sequence: 7.2 \nSedgewicks's sequence: 4.5 \n\nFor an array of size 8388608: \n3N + 1 sequence: 18.4 \nSedgewicks's sequence: 11.2 \n\nFor an array of size 16777216: \n3N + 1 sequence: 46.0 \nSedgewicks's sequence: 26.6","support_files":[],"metadata":{"number":"2.5.29","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Boerner’s theorem. True or false: If you sort each column of a matrix, then sort each row, the columns are still sorted. Justify your answer.","answer":"2.1.30 - Geometric increments\n\nBest 1 tValue: 2.10\nBest 1 sequence:\n1 2 4 9 19 40 85 180 378 794 1667 3502 7355 15447 32439 68122 143056 300419 630880\n\nBest 2 tValue: 2.40\nBest 2 sequence:\n1 2 5 13 33 79 191 458 1100 2641 6340 15216 36520 87648 210357 504857\n\nBest 3 tValue: 2.20\nBest 3 sequence:\n1 2 4 10 23 51 113 249 548 1207 2655 5843 12855 28281 62218 136880 301136 662499","support_files":[],"metadata":{"number":"2.5.30","chapter":2,"chapter_title":"Sorting","section":2.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Give the number of calls to put() and get() issued by FrequencyCounter, as a function of the number W of words and the number D of distinct words in the input.","answer":"3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221","support_files":[],"metadata":{"number":"3.1.6","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"What is the average number of distinct keys that FrequencyCounter will find among N random nonnegative integers less than 1,000, for N=10, 10^2, 10^3, 10^4, 10^5, and 10^6?","answer":"3.1.7\n\nNumber of distinct keys among 10 random nonnegative integers less than 1000: 10\nNumber of distinct keys among 100 random nonnegative integers less than 1000: 97\nNumber of distinct keys among 1000 random nonnegative integers less than 1000: 635\nNumber of distinct keys among 10000 random nonnegative integers less than 1000: 999\nNumber of distinct keys among 100000 random nonnegative integers less than 1000: 1000\nNumber of distinct keys among 1000000 random nonnegative integers less than 1000: 1000","support_files":[],"metadata":{"number":"3.1.7","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"What is the most frequently used word of ten letters or more in Tale of Two Cities?","answer":"3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47","support_files":[],"metadata":{"number":"3.1.8","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Add code to FrequencyCounter to keep track of the last call to put(). Print the last word inserted and the number of words that were processed in the input stream prior to this insertion. Run your program for tale.txt with length cutoffs 1, 8, and 10.","answer":"3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890","support_files":[],"metadata":{"number":"3.1.9","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Give a trace of the process of inserting the keys E A S Y Q U E S T I O N into an initially empty table using SequentialSearchST. How many compares are involved?","answer":"3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102","support_files":[],"metadata":{"number":"3.1.10","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Give a trace of the process of inserting the keys E A S Y Q U E S T I O N into an initially empty table using BinarySearchST. How many compares are involved?","answer":"3.1.11\n\n\t\t\tkeys[]\t\t\t\t vals[]\nkey value 0 1 2 3 4 5 6 7 8 9 N 0 1 2 3 4 5 6 7 8 9\n E 0 E 1 0 0 compares\n A 1 A E 2 1 0 2 compares\n S 2 A E S 3 1 0 2 2 compares\n Y 3 A E S Y 4 1 0 2 3 2 compares\n Q 4 A E Q S Y 5 1 0 4 2 3 3 compares\n U 5 A E Q S U Y 6 1 0 4 2 5 3 4 compares\n E 6 A E Q S U Y 6 1 6 4 2 5 3 4 compares\n S 7 A E Q S U Y 6 1 6 4 7 5 3 4 compares\n T 8 A E Q S T U Y 6 1 6 4 7 8 5 3 4 compares\n I 9 A E I Q S T U Y 6 1 6 9 4 7 8 5 3 4 compares\n O 10 A E I O Q S T U Y 6 1 6 9 10 4 7 8 5 3 4 compares\n N 11 A E I N O Q S T U Y 6 1 6 9 11 10 4 7 8 5 3 5 compares\n A E I N O Q S T U Y 1 6 9 11 10 4 7 8 5 3\n\nTotal: 38 compares","support_files":[],"metadata":{"number":"3.1.11","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Which of the symbol-table implementations in this section would you use for an application that does 10^3 put() operations and 10^6 get() operations, randomly intermixed? Justify your answer.","answer":"3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.","support_files":[],"metadata":{"number":"3.1.13","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Which of the symbol-table implementations in this section would you use for an application that does 10^6 put() operations and 10^3 get() operations, randomly intermixed? Justify your answer.","answer":"3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119","support_files":[],"metadata":{"number":"3.1.14","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Assume that searches are 1,000 times more frequent than insertions for a BinarySearchST client. Estimate the percentage of the total time that is devoted to insertions, when the number of searches is 10^3, 10^6, and 10^9.","answer":"3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222","support_files":[],"metadata":{"number":"3.1.15","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Prove that the rank() method in BinarySearchST is correct.","answer":"3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.","support_files":[],"metadata":{"number":"3.1.18","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Complete the proof of Proposition B (show that it holds for all values of N). Hint: Start by showing that C(N) is monotonic: C(N) <= C(N+1) for all N > 0.","answer":"3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223","support_files":[],"metadata":{"number":"3.1.20","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Exercise","code_execution":false}} {"question":"Memory usage. Compare the memory usage of BinarySearchST with that of SequentialSearchST for N key-value pairs, under the assumptions described in Section 1.4. Do not count the memory for the keys and values themselves, but do count references to them. For BinarySearchST, assume that array resizing is used, so that the array is between 25 percent and 100 percent full.","answer":"3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes","support_files":[],"metadata":{"number":"3.1.21","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Creative Problem","code_execution":false}} {"question":"Analysis of binary search. Prove that the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N, because the operation of shifting 1 bit to the right converts the binary representation of N into the binary representation of floor(N/2).","answer":"3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.","support_files":[],"metadata":{"number":"3.1.23","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Creative Problem","code_execution":false}} {"question":"Small tables. Suppose that a BinarySearchST client has S search operations and N distinct keys. Give the order of growth of S such that the cost of building the table is the same as the cost of all the searches.","answer":"3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120","support_files":[],"metadata":{"number":"3.1.27","chapter":3,"chapter_title":"Searching","section":3.1,"section_title":"Symbol Tables","type":"Creative Problem","code_execution":false}} {"question":"Add to BST a method height() that computes the height of the tree. Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and a method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).","answer":"3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221","support_files":[],"metadata":{"number":"3.2.6","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Add to BST a recursive method avgCompares() that computes the average number of compares required by a random search hit in a given BST (the internal path length of the tree divided by its size, plus one). Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and a method like size() that adds a field to each node in the tree (and takes linear space and constant time per query).","answer":"3.1.7\n\nNumber of distinct keys among 10 random nonnegative integers less than 1000: 10\nNumber of distinct keys among 100 random nonnegative integers less than 1000: 97\nNumber of distinct keys among 1000 random nonnegative integers less than 1000: 635\nNumber of distinct keys among 10000 random nonnegative integers less than 1000: 999\nNumber of distinct keys among 100000 random nonnegative integers less than 1000: 1000\nNumber of distinct keys among 1000000 random nonnegative integers less than 1000: 1000","support_files":[],"metadata":{"number":"3.2.7","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Write a static method optCompares() that takes an integer argument N and computes the number of compares required by a random search hit in an optimal (perfectly balanced) BST, where all the null links are on the same level if the number of links is a power of 2 or on one of two levels otherwise.","answer":"3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47","support_files":[],"metadata":{"number":"3.2.8","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw all the different BST shapes that can result when N keys are inserted into an initially empty tree, for N = 2, 3, 4, 5, and 6.","answer":"3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890","support_files":[],"metadata":{"number":"3.2.9","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Write a test client TestBST.java for use in testing the implementations of min(), max(), floor(), ceiling(), select(), rank(), delete(), deleteMin(), deleteMax(), and keys() that are given in the text. Start with the standard indexing client given on page 370. Add code to take additional command-line arguments, as appropriate.","answer":"3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102","support_files":[],"metadata":{"number":"3.2.10","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"How many binary tree shapes of N nodes are there with height N? How many different ways are there to insert N distinct keys into an initially empty BST that result in a tree of height N? (See Exercise 3.2.2.)","answer":"3.1.11\n\n\t\t\tkeys[]\t\t\t\t vals[]\nkey value 0 1 2 3 4 5 6 7 8 9 N 0 1 2 3 4 5 6 7 8 9\n E 0 E 1 0 0 compares\n A 1 A E 2 1 0 2 compares\n S 2 A E S 3 1 0 2 2 compares\n Y 3 A E S Y 4 1 0 2 3 2 compares\n Q 4 A E Q S Y 5 1 0 4 2 3 3 compares\n U 5 A E Q S U Y 6 1 0 4 2 5 3 4 compares\n E 6 A E Q S U Y 6 1 6 4 2 5 3 4 compares\n S 7 A E Q S U Y 6 1 6 4 7 5 3 4 compares\n T 8 A E Q S T U Y 6 1 6 4 7 8 5 3 4 compares\n I 9 A E I Q S T U Y 6 1 6 9 4 7 8 5 3 4 compares\n O 10 A E I O Q S T U Y 6 1 6 9 10 4 7 8 5 3 4 compares\n N 11 A E I N O Q S T U Y 6 1 6 9 11 10 4 7 8 5 3 5 compares\n A E I N O Q S T U Y 1 6 9 11 10 4 7 8 5 3\n\nTotal: 38 compares","support_files":[],"metadata":{"number":"3.2.11","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Give nonrecursive implementations of get() and put() for BST.","answer":"3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.","support_files":[],"metadata":{"number":"3.2.13","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Give nonrecursive implementations of min(), max(), floor(), ceiling(), rank(), and select().","answer":"3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119","support_files":[],"metadata":{"number":"3.2.14","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Give the sequences of nodes examined when the methods in BST are used to compute each of the following quantities for the tree drawn at right.\na. floor(\"Q\")\nb. select(5)\nc. ceiling(\"Q\")\nd. rank(\"J\")\ne. size(\"D\", \"T\")\nf. keys(\"D\", \"T\")","answer":"3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222","support_files":[],"metadata":{"number":"3.2.15","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw the sequence of BSTs that results when you delete the keys from the tree of Exercise 3.2.1, one by one, in alphabetical order.","answer":"3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.","support_files":[],"metadata":{"number":"3.2.18","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Prove that the running time of the two-argument keys() in a BST with N nodes is at most proportional to the tree height plus the number of keys in the range.","answer":"3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223","support_files":[],"metadata":{"number":"3.2.20","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Add a BST method randomKey() that returns a random key from the symbol table in time proportional to the tree height, in the worst case.","answer":"3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes","support_files":[],"metadata":{"number":"3.2.21","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Is delete() commutative? (Does deleting x, then y give the same result as deleting y, then x?)","answer":"3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.","support_files":[],"metadata":{"number":"3.2.23","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Exercise","code_execution":false}} {"question":"Memory usage. Compare the memory usage of BST with the memory usage of BinarySearchST and SequentialSearchST for N key-value pairs, under the assumptions described in Section 1.4 (see Exercise 3.1.21). Do not count the memory for the keys and values themselves, but do count references to them. Then draw a diagram that depicts the precise memory usage of a BST with String keys and Integer values (such as the ones built by FrequencyCounter), and then estimate the memory usage (in bytes) for the BST built when FrequencyCounter uses BST for Tale of Two Cities.","answer":"3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120","support_files":[],"metadata":{"number":"3.2.27","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Equal key check. Write a method hasNoDuplicates() that takes a Node as argument and returns true if there are no equal keys in the binary tree rooted at the argument node, false otherwise. Assume that the test of the previous exercise has passed.","answer":"3.1.31 - Performance driver\n\nNumber of Experiments | Array Size | AVG Time Taken\n 1 100000 12.32\n 2 100000 12.13\n 3 100000 12.15\n 4 100000 14.73\n 5 100000 19.76","support_files":[],"metadata":{"number":"3.2.31","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Certification. Write a method isBST() that takes a Node as argument and returns true if the argument node is the root of a binary search tree, false otherwise. Hint: This task is also more difficult than it might seem, because the order in which you call the methods in the previous three exercises is important.","answer":"3.1.32 - Exercise driver\n\n Input Type | Array Size | Running Time\n Ordered 100000 6.8\n Ordered 200000 37.7\n Ordered 400000 142.9\n Reverse Ordered 100000 24.1\n Reverse Ordered 200000 102.2\n Reverse Ordered 400000 469.6\n Same Keys 100000 0.0\n Same Keys 200000 0.0\n Same Keys 400000 0.0\n Keys with only 2 Values 100000 0.0\n Keys with only 2 Values 200000 0.0\n Keys with only 2 Values 400000 0.0","support_files":[],"metadata":{"number":"3.2.32","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Select/rank check. Write a method that checks, for all i from 0 to size()-1, whether i is equal to rank(select(i)) and, for all keys in the BST, whether key is equal to select(rank(key)).","answer":"3.1.33 - Driver for self-organizing search\n\nArray Size | Self-Organizing Search Time | Default Binary Search Time\n 1000 0.01 0.01\n 10000 0.05 0.01\n 100000 4.46 0.10\n 1000000 576.02 0.87","support_files":[],"metadata":{"number":"3.2.33","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Threading. Your goal is to support an extended API ThreadedST that supports the following additional operations in constant time:\nKey next(Key key) key that follows key (null if key is the maximum)\nKey prev(Key key) key that precedes key (null if key is the minimum)\nTo do so, add fields pred and succ to Node that contain links to the predecessor and successor nodes, and modify put(), deleteMin(), deleteMax(), and delete() to maintain these fields.","answer":"3.1.34 - Zipf's law\n\nArray Size | Move-to-Front Time | Optimal Arrangement Time\n 1000 0.04 0.01\n 10000 0.42 0.18\n 100000 33.46 6.18\n 1000000 4069.86 481.80","support_files":[],"metadata":{"number":"3.2.34","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Refined analysis. Refine the mathematical model to better explain the experimental results in the table given in the text. Specifically, show that the average number of compares for a successful search in a tree built from random keys approaches the limit 2 ln N + 2γ - 3 ≈ 1.39 lg N – 1.85 as N increases, where γ ≈ .57721... is Euler’s constant. Hint: Referring to the quicksort analysis in Section 2.3, use the fact that the integral of 1/x approaches ln N + γ.","answer":"3.1.35 - Performance validation I\n\nThe running time of FrequencyCounter is close to quadratic when it uses SequentialSearchST for its symbol table.\n\nNumber of Words | Running Time | Ratio | Complexity (N^X)\n 1000 0.01 1.00 0.00\n 2000 0.01 1.60 0.68\n 4000 0.03 3.50 1.81\n 8000 0.11 3.86 1.95\n 16000 0.37 3.44 1.78\n 32000 1.34 3.60 1.85\n 64000 3.56 2.66 1.41\n 128000 12.67 3.56 1.83","support_files":[],"metadata":{"number":"3.2.35","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Iterator. Is it possible to write a nonrecursive version of keys() that uses space proportional to the tree height (independent of the number of keys in the range)?","answer":"3.1.36 - Performance validation II\n\nThe performance of BinarySearchST and SequentialSearchST for FrequencyCounter is even better than predicted by analysis because of the details of the FrequencyCounter application. \nFrequencyCounter does not add all the words in the symbol table (only the words with a length higher than a specified minLength parameter). Also, there are many repeated words in the Tale of Two Cities book, which was used as benchmark. Out of 135,938 words, only 561 are distinct. \nWith more search hits than search misses, a sequential search does not have to check all the N words in the symbol table (its worst case) as often. The same applies to a binary search, that does not have to do lg N compares as often than if there were many search misses.\nThese details of the application make the performance of the symbol tables better than predicted.","support_files":[],"metadata":{"number":"3.2.36","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Level-order traversal. Write a method printLevel() that takes a Node as argument and prints the keys in the subtree rooted at that node in level order (in order of their distance from the root, with nodes on each level in order from left to right). Hint: Use a Queue.","answer":"3.1.37 - Put/get ratio\n\nFor a symbol table with 10-bit int values the amount of time that BinarySearchST spent on put() was lower than the amount of time it spent on get().\nHowever, for all the other scenarios (counting the frequency of 20 and 30-bit values and the frequency of the words in the book Tale of Two Cities) the amount of time that BinarySearchST spends on put() operations is much higher than the amount of time it spends on get().\n\n Input | Running Time Put | Running Time Get | Ratio\n 10-bit int values 0.11 0.29 0.39\n 20-bit int values 216.62 0.78 279.51\n 30-bit int values 1303.54 0.81 1613.29\nTale of Two Cities 0.33 0.03 12.37","support_files":[],"metadata":{"number":"3.2.37","chapter":3,"chapter_title":"Searching","section":3.2,"section_title":"Binary Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Find the probability that each of the 2-3 trees in Exercise 3.3.5 is the result of the insertion of N random distinct keys into an initially empty tree.","answer":"3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221","support_files":[],"metadata":{"number":"3.3.6","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw diagrams like the one at the top of page 428 for the other five cases in the diagram at the bottom of that page.","answer":"3.1.7\n\nNumber of distinct keys among 10 random nonnegative integers less than 1000: 10\nNumber of distinct keys among 100 random nonnegative integers less than 1000: 97\nNumber of distinct keys among 1000 random nonnegative integers less than 1000: 635\nNumber of distinct keys among 10000 random nonnegative integers less than 1000: 999\nNumber of distinct keys among 100000 random nonnegative integers less than 1000: 1000\nNumber of distinct keys among 1000000 random nonnegative integers less than 1000: 1000","support_files":[],"metadata":{"number":"3.3.7","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Show all possible ways that one might represent a 4-node with three 2-nodes bound together with red links (not necessarily left-leaning).","answer":"3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47","support_files":[],"metadata":{"number":"3.3.8","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Which of the following are red-black BSTs?","answer":"3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890","support_files":[],"metadata":{"number":"3.3.9","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw the red-black BST that results when you insert items with the keys E A S Y Q U T I O N in that order into an initially empty tree.","answer":"3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102","support_files":[],"metadata":{"number":"3.3.10","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw the red-black BST that results when you insert items with the keys Y L P M X H C R A E S in that order into an initially empty tree.","answer":"3.1.11\n\n\t\t\tkeys[]\t\t\t\t vals[]\nkey value 0 1 2 3 4 5 6 7 8 9 N 0 1 2 3 4 5 6 7 8 9\n E 0 E 1 0 0 compares\n A 1 A E 2 1 0 2 compares\n S 2 A E S 3 1 0 2 2 compares\n Y 3 A E S Y 4 1 0 2 3 2 compares\n Q 4 A E Q S Y 5 1 0 4 2 3 3 compares\n U 5 A E Q S U Y 6 1 0 4 2 5 3 4 compares\n E 6 A E Q S U Y 6 1 6 4 2 5 3 4 compares\n S 7 A E Q S U Y 6 1 6 4 7 5 3 4 compares\n T 8 A E Q S T U Y 6 1 6 4 7 8 5 3 4 compares\n I 9 A E I Q S T U Y 6 1 6 9 4 7 8 5 3 4 compares\n O 10 A E I O Q S T U Y 6 1 6 9 10 4 7 8 5 3 4 compares\n N 11 A E I N O Q S T U Y 6 1 6 9 11 10 4 7 8 5 3 5 compares\n A E I N O Q S T U Y 1 6 9 11 10 4 7 8 5 3\n\nTotal: 38 compares","support_files":[],"metadata":{"number":"3.3.11","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"True or false: If you insert keys in increasing order into a red-black BST, the tree height is monotonically increasing.","answer":"3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.","support_files":[],"metadata":{"number":"3.3.13","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw the red-black BST that results when you insert letters A through K in order into an initially empty tree, then describe what happens in general when trees are built by insertion of keys in ascending order (see also the figure in the text).","answer":"3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119","support_files":[],"metadata":{"number":"3.3.14","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Answer the previous two questions for the case when the keys are inserted in descending order.","answer":"3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222","support_files":[],"metadata":{"number":"3.3.15","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Draw all the structurally different red-black BSTs with N keys, for N from 2 up to 10 (see Exercise 3.3.5).","answer":"3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.","support_files":[],"metadata":{"number":"3.3.18","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Compute the internal path length in a perfectly balanced BST of N nodes, when N is a power of 2 minus 1.","answer":"3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223","support_files":[],"metadata":{"number":"3.3.20","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"Create a test client TestRB.java, based on your solution to Exercise 3.2.10.","answer":"3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes","support_files":[],"metadata":{"number":"3.3.21","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Exercise","code_execution":false}} {"question":"2-3 trees without balance restriction. Develop an implementation of the basic symbol-table API that uses 2-3 trees that are not necessarily balanced as the underlying data structure. Allow 3-nodes to lean either way. Hook the new node onto the bottom with a black link when inserting into a 3-node at the bottom. Run experiments to develop a hypothesis estimating the average path length in a tree built from N random insertions.","answer":"3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.","support_files":[],"metadata":{"number":"3.3.23","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Allow right-leaning red links. Develop a modified version of your solution to Exercise 3.3.25 that allows right-leaning red links in the tree.","answer":"3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120","support_files":[],"metadata":{"number":"3.3.27","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Tree drawing. Add a method draw() to RedBlackBST that draws red-black BST figures in the style of the text (see Exercise 3.2.38).","answer":"3.1.31 - Performance driver\n\nNumber of Experiments | Array Size | AVG Time Taken\n 1 100000 12.32\n 2 100000 12.13\n 3 100000 12.15\n 4 100000 14.73\n 5 100000 19.76","support_files":[],"metadata":{"number":"3.3.31","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"AVL trees. An AVL tree is a BST where the height of every node and that of its sibling differ by at most 1. (The oldest balanced tree algorithms are based on using rotations to maintain height balance in AVL trees.) Show that coloring red links that go from nodes of even height to nodes of odd height in an AVL tree gives a (perfectly balanced) 2-3-4 tree, where red links are not necessarily left-leaning. Extra credit: Develop an implementation of the symbol-table API that uses this as the underlying data structure. One approach is to keep a height field in each node, using rotations after the recursive calls to adjust the height as necessary; another is to use the red-black representation and use methods like moveRedLeft() and moveRedRight() in Exercise 3.3.39 and Exercise 3.3.40.","answer":"3.1.32 - Exercise driver\n\n Input Type | Array Size | Running Time\n Ordered 100000 6.8\n Ordered 200000 37.7\n Ordered 400000 142.9\n Reverse Ordered 100000 24.1\n Reverse Ordered 200000 102.2\n Reverse Ordered 400000 469.6\n Same Keys 100000 0.0\n Same Keys 200000 0.0\n Same Keys 400000 0.0\n Keys with only 2 Values 100000 0.0\n Keys with only 2 Values 200000 0.0\n Keys with only 2 Values 400000 0.0","support_files":[],"metadata":{"number":"3.3.32","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Certification. Add to RedBlackBST a method is23() to check that no node is connected to two red links and that there are no right-leaning red links and a method isBalanced() to check that all paths from the root to a null link have the same number of black links. Combine these methods with code from isBST() in Exercise 3.2.32 to create a method isRedBlackBST() that checks that the tree is a red-black BST.","answer":"3.1.33 - Driver for self-organizing search\n\nArray Size | Self-Organizing Search Time | Default Binary Search Time\n 1000 0.01 0.01\n 10000 0.05 0.01\n 100000 4.46 0.10\n 1000000 576.02 0.87","support_files":[],"metadata":{"number":"3.3.33","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"All 2-3 trees. Write code to generate all structurally different 2-3 trees of height 2, 3, and 4. There are 2, 7, and 122 such trees, respectively. (Hint: Use a symbol table.)","answer":"3.1.34 - Zipf's law\n\nArray Size | Move-to-Front Time | Optimal Arrangement Time\n 1000 0.04 0.01\n 10000 0.42 0.18\n 100000 33.46 6.18\n 1000000 4069.86 481.80","support_files":[],"metadata":{"number":"3.3.34","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"2-3 trees. Write a program TwoThreeST.java that uses two node types to implement 2-3 search trees directly.","answer":"3.1.35 - Performance validation I\n\nThe running time of FrequencyCounter is close to quadratic when it uses SequentialSearchST for its symbol table.\n\nNumber of Words | Running Time | Ratio | Complexity (N^X)\n 1000 0.01 1.00 0.00\n 2000 0.01 1.60 0.68\n 4000 0.03 3.50 1.81\n 8000 0.11 3.86 1.95\n 16000 0.37 3.44 1.78\n 32000 1.34 3.60 1.85\n 64000 3.56 2.66 1.41\n 128000 12.67 3.56 1.83","support_files":[],"metadata":{"number":"3.3.35","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"2-3-4-5-6-7-8 trees. Describe algorithms for search and insertion in balanced 2-3-4-5-6-7-8 search trees.","answer":"3.1.36 - Performance validation II\n\nThe performance of BinarySearchST and SequentialSearchST for FrequencyCounter is even better than predicted by analysis because of the details of the FrequencyCounter application. \nFrequencyCounter does not add all the words in the symbol table (only the words with a length higher than a specified minLength parameter). Also, there are many repeated words in the Tale of Two Cities book, which was used as benchmark. Out of 135,938 words, only 561 are distinct. \nWith more search hits than search misses, a sequential search does not have to check all the N words in the symbol table (its worst case) as often. The same applies to a binary search, that does not have to do lg N compares as often than if there were many search misses.\nThese details of the application make the performance of the symbol tables better than predicted.","support_files":[],"metadata":{"number":"3.3.36","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Memoryless. Show that red-black BSTs are not memoryless: for example, if you insert a key that is smaller than all the keys in the tree and then immediately delete the minimum, you may get a different tree.","answer":"3.1.37 - Put/get ratio\n\nFor a symbol table with 10-bit int values the amount of time that BinarySearchST spent on put() was lower than the amount of time it spent on get().\nHowever, for all the other scenarios (counting the frequency of 20 and 30-bit values and the frequency of the words in the book Tale of Two Cities) the amount of time that BinarySearchST spends on put() operations is much higher than the amount of time it spends on get().\n\n Input | Running Time Put | Running Time Get | Ratio\n 10-bit int values 0.11 0.29 0.39\n 20-bit int values 216.62 0.78 279.51\n 30-bit int values 1303.54 0.81 1613.29\nTale of Two Cities 0.33 0.03 12.37","support_files":[],"metadata":{"number":"3.3.37","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Delete the minimum. Implement the deleteMin() operation for red-black BSTs by maintaining the correspondence with the transformations given in the text for moving down the left spine of the tree while maintaining the invariant that the current node is not a 2-node.","answer":"3.1.39 - Actual timings\n\nAs expected, BinarySearchST total running time is much smaller than SequentialSearchST total running time.\nBinarySearchST total running time for all the calls to get() and put() was 204 milliseconds while SequentialSearchST total running time was 2237 milliseconds.","support_files":[],"metadata":{"number":"3.3.39","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Delete the maximum. Implement the deleteMax() operation for red-black BSTs. Note that the transformations involved differ slightly from those in the previous exercise because red links are left-leaning.","answer":"3.1.40 - Crossover to binary search\n\nAnalysis:\nConsidering that sequential search has a complexity of O(n) and binary search has a complexity of O(lg (n)):\n\nN = 58: While sequential search does 58 operations (in the worst case), binary search does ~5.8 operations (in the worst case).\nBinary search is ~10 times faster than sequential search for N = 58.\n\nN = 996: While sequential search does 996 operations (in the worst case), binary search does ~9.96 operations (in the worst case).\nBinary search is ~100 times faster than sequential search for N = 996.\n\nN = 13746: While sequential search does 13,746 operations (in the worst case), binary search does ~13.746 operations (in the worst case).\nBinary search is ~1000 times faster than sequential search for N = 13,746.\n\nExperimental results:\n\nValue of N for which binary search becomes 10 times faster than sequential search: 120\nValue of N for which binary search becomes 100 times faster than sequential search: 1463\nValue of N for which binary search becomes 1000 times faster than sequential search: 22461","support_files":[],"metadata":{"number":"3.3.40","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Delete. Implement the delete() operation for red-black BSTs, combining the methods of the previous two exercises with the delete() operation for BSTs.","answer":"3.1.41 - Crossover to interpolation search\n\nAnalysis:\nConsidering that binary search has a complexity of O(lg (n)) and interpolation search has a complexity of O(lg(lg (n))) when the elements are uniformly distributed (and it is O(n) otherwise). \nAssuming an array with elements uniformly distributed:\n\nN = 1: Both binary search and interpolation search would be able to finish their search instantly with N = 1.\nInterpolation search and binary search are just as fast for N = 1.\n\nN = 4: Binary search does 2 operations (in the worst case) and interpolation search does 1 operation (in the worst case).\nInterpolation search is 2 times faster than binary search for N = 4.\n\nN = 490000000000000000 (49 * 10^16): Binary search does 58.76 operations (in the worst case) and interpolation search does 5.876 operations (in the worst case).\nInterpolation search is 10 times faster than binary search for N = 49 * 10^16.\n\nExperimental results:\n\nValue of N for which interpolation search becomes the same speed as binary search: 1\nValue of N for which interpolation search becomes 2 times faster than binary search: 21\nValue of N for which interpolation search becomes 10 times faster than binary search: 1033","support_files":[],"metadata":{"number":"3.3.41","chapter":3,"chapter_title":"Searching","section":3.3,"section_title":"Balanced Search Trees","type":"Creative Problem","code_execution":false}} {"question":"Suppose that keys are t-bit integers. For a modular hash function with prime M, prove that each key bit has the property that there exist two keys differing only in that bit that have different hash values.","answer":"3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221","support_files":[],"metadata":{"number":"3.4.6","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Consider the idea of implementing modular hashing for integer keys with the code (a * k) % M, where a is an arbitrary fixed prime. Does this change mix up the bits sufficiently well that you can use nonprime M?","answer":"3.1.7\n\nNumber of distinct keys among 10 random nonnegative integers less than 1000: 10\nNumber of distinct keys among 100 random nonnegative integers less than 1000: 97\nNumber of distinct keys among 1000 random nonnegative integers less than 1000: 635\nNumber of distinct keys among 10000 random nonnegative integers less than 1000: 999\nNumber of distinct keys among 100000 random nonnegative integers less than 1000: 1000\nNumber of distinct keys among 1000000 random nonnegative integers less than 1000: 1000","support_files":[],"metadata":{"number":"3.4.7","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"How many empty lists do you expect to see when you insert N keys into a hash table with SeparateChainingHashST, for N=10, 10^2, 10^3, 10^4, 10^5, and 10^6? Hint: See Exercise 2.5.31.","answer":"3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47","support_files":[],"metadata":{"number":"3.4.8","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Implement an eager delete() method for SeparateChainingHashST.","answer":"3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890","support_files":[],"metadata":{"number":"3.4.9","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Insert the keys E A S Y Q U T I O N in that order into an initially empty table of size M =16 using linear probing. Use the hash function 11 k % M to transform the kth letter of the alphabet into a table index. Redo this exercise for M = 10.","answer":"3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102","support_files":[],"metadata":{"number":"3.4.10","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Give the contents of a linear-probing hash table that results when you insert the keys E A S Y Q U T I O N in that order into an initially empty table of initial size M = 4 that is expanded with doubling whenever half full. Use the hash function 11 k % M to transform the kth letter of the alphabet into a table index.","answer":"3.1.11\n\n\t\t\tkeys[]\t\t\t\t vals[]\nkey value 0 1 2 3 4 5 6 7 8 9 N 0 1 2 3 4 5 6 7 8 9\n E 0 E 1 0 0 compares\n A 1 A E 2 1 0 2 compares\n S 2 A E S 3 1 0 2 2 compares\n Y 3 A E S Y 4 1 0 2 3 2 compares\n Q 4 A E Q S Y 5 1 0 4 2 3 3 compares\n U 5 A E Q S U Y 6 1 0 4 2 5 3 4 compares\n E 6 A E Q S U Y 6 1 6 4 2 5 3 4 compares\n S 7 A E Q S U Y 6 1 6 4 7 5 3 4 compares\n T 8 A E Q S T U Y 6 1 6 4 7 8 5 3 4 compares\n I 9 A E I Q S T U Y 6 1 6 9 4 7 8 5 3 4 compares\n O 10 A E I O Q S T U Y 6 1 6 9 10 4 7 8 5 3 4 compares\n N 11 A E I N O Q S T U Y 6 1 6 9 11 10 4 7 8 5 3 5 compares\n A E I N O Q S T U Y 1 6 9 11 10 4 7 8 5 3\n\nTotal: 38 compares","support_files":[],"metadata":{"number":"3.4.11","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Which of the following scenarios leads to expected linear running time for a random search hit in a linear-probing hash table?\na. All keys hash to the same index.\nb. All keys hash to different indices.\nc. All keys hash to an even-numbered index.\nd. All keys hash to different even-numbered indices.","answer":"3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.","support_files":[],"metadata":{"number":"3.4.13","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Answer the previous question for search miss, assuming the search key is equally likely to hash to each table position.","answer":"3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119","support_files":[],"metadata":{"number":"3.4.14","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"How many compares could it take, in the worst case, to insert N keys into an initially empty table, using linear probing with array resizing?","answer":"3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222","support_files":[],"metadata":{"number":"3.4.15","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Add a constructor to SeparateChainingHashST that gives the client the ability to specify the average number of probes to be tolerated for searches. Use array resizing to keep the average list size less than the specified value, and use the technique described on page 478 to ensure that the modulus for hash() is prime.","answer":"3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.","support_files":[],"metadata":{"number":"3.4.18","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Add a method to LinearProbingHashST that computes the average cost of a search hit in the table, assuming that each key in the table is equally likely to be sought.","answer":"3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223","support_files":[],"metadata":{"number":"3.4.20","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Add a method to LinearProbingHashST that computes the average cost of a search miss in the table, assuming a random hash function. Note: You do not have to compute any hash functions to solve this problem.","answer":"3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes","support_files":[],"metadata":{"number":"3.4.21","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Consider modular hashing for string keys with R = 256 and M = 255. Show that this is a bad choice because any permutation of letters within a string hashes to the same value.","answer":"3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.","support_files":[],"metadata":{"number":"3.4.23","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Exercise","code_execution":false}} {"question":"Double probing. Modify SeparateChainingHashST to use a second hash function and pick the shorter of the two lists. Give a trace of the process of inserting the keys E A S Y Q U T I O N in that order into an initially empty table of size M =3 using the function 11 k % M (for the kth letter) as the first hash function and the function 17 k % M (for the kth letter) as the second hash function. Give the average number of probes for random search hit and search miss in this table.","answer":"3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120","support_files":[],"metadata":{"number":"3.4.27","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Creative Problem","code_execution":false}} {"question":"Cuckoo hashing. Develop a symbol-table implementation that maintains two hash tables and two hash functions. Any given key is in one of the tables, but not both. When inserting a new key, hash to one of the tables; if the table position is occupied, replace that key with the new key and hash the old key into the other table (again kicking out a key that might reside there). If this process cycles, restart. Keep the tables less than half full. This method uses a constant number of equality tests in the worst case for search (trivial) and amortized constant time for insert.","answer":"3.1.31 - Performance driver\n\nNumber of Experiments | Array Size | AVG Time Taken\n 1 100000 12.32\n 2 100000 12.13\n 3 100000 12.15\n 4 100000 14.73\n 5 100000 19.76","support_files":[],"metadata":{"number":"3.4.31","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Creative Problem","code_execution":false}} {"question":"Hash attack. Find 2^N strings, each of length 2^N, that have the same hashCode() value, supposing that the hashCode() implementation for String is the following:\npublic int hashCode() { \n int hash = 0;\n for (int i = 0; i < length(); i ++)\n hash = (hash * 31) + charAt(i);\n return hash; \n} \nStrong hint: Aa and BB have the same value.","answer":"3.1.32 - Exercise driver\n\n Input Type | Array Size | Running Time\n Ordered 100000 6.8\n Ordered 200000 37.7\n Ordered 400000 142.9\n Reverse Ordered 100000 24.1\n Reverse Ordered 200000 102.2\n Reverse Ordered 400000 469.6\n Same Keys 100000 0.0\n Same Keys 200000 0.0\n Same Keys 400000 0.0\n Keys with only 2 Values 100000 0.0\n Keys with only 2 Values 200000 0.0\n Keys with only 2 Values 400000 0.0","support_files":[],"metadata":{"number":"3.4.32","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Creative Problem","code_execution":false}} {"question":"Bad hash function. Consider the following hashCode() implementation for String, which was used in early versions of Java:\npublic int hashCode() { \n int hash = 0;\n int skip = Math.max(1, length()/8);\n for (int i = 0; i < length(); i += skip)\n hash = (hash * 37) + charAt(i);\n return hash; \n} \nExplain why you think the designers chose this implementation and then why you think it was abandoned in favor of the one in the previous exercise.","answer":"3.1.33 - Driver for self-organizing search\n\nArray Size | Self-Organizing Search Time | Default Binary Search Time\n 1000 0.01 0.01\n 10000 0.05 0.01\n 100000 4.46 0.10\n 1000000 576.02 0.87","support_files":[],"metadata":{"number":"3.4.33","chapter":3,"chapter_title":"Searching","section":3.4,"section_title":"Hash Tables","type":"Creative Problem","code_execution":false}} {"question":"Develop classes HashSETint and HashSETdouble for maintaining sets of keys of primitive int and double types, respectively. (Eliminate code involving values in your solution to Exercise 3.5.4.)","answer":"3.1.6\n\nThe put() method will be called once for every word.\nThe get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.\n\nCalls to put() = W\nCalls to get() = W - D\n\nThanks to faame (https://github.com/faame) for suggesting a better answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/221","support_files":[],"metadata":{"number":"3.5.6","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Develop classes SETint and SETdouble for maintaining ordered sets of keys of primitive int and double types, respectively. (Eliminate code involving values in your solution to Exercise 3.5.5.)","answer":"3.1.7\n\nNumber of distinct keys among 10 random nonnegative integers less than 1000: 10\nNumber of distinct keys among 100 random nonnegative integers less than 1000: 97\nNumber of distinct keys among 1000 random nonnegative integers less than 1000: 635\nNumber of distinct keys among 10000 random nonnegative integers less than 1000: 999\nNumber of distinct keys among 100000 random nonnegative integers less than 1000: 1000\nNumber of distinct keys among 1000000 random nonnegative integers less than 1000: 1000","support_files":[],"metadata":{"number":"3.5.7","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Modify LinearProbingHashST to keep duplicate keys in the table. Return any value associated with the given key for get(), and remove all items in the table that have keys equal to the given key for delete().","answer":"3.1.8\n\nMost frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47","support_files":[],"metadata":{"number":"3.5.8","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Modify BST to keep duplicate keys in the tree. Return any value associated with the given key for get(), and remove all nodes in the tree that have keys equal to the given key for delete().","answer":"3.1.9\n\nLength cutoff Last word inserted Words processed\n 1 known.\" 135937\n 8 faltering 135905\n 10 disfigurement 135890","support_files":[],"metadata":{"number":"3.5.9","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Modify RedBlackBST to keep duplicate keys in the tree. Return any value associated with the given key for get(), and remove all nodes in the tree that have keys equal to the given key for delete().","answer":"3.1.10\n\nkey value first\n E 0 E0 0 compares\n A 1 A1 E0 1 compare\n S 2 S2 A1 E0 2 compares\n Y 3 Y3 S2 A1 E0 3 compares\n Q 4 Q4 Y3 S2 A1 E0 4 compares\n U 5 U5 Q4 Y3 S2 A1 E0 5 compares\n E 6 U5 Q4 Y3 S2 A1 E6 6 compares\n S 7 U5 Q4 Y3 S7 A1 E6 4 compares\n T 8 T8 U5 Q4 Y3 S7 A1 E6 6 compares\n I 9 I9 T8 U5 Q4 Y3 S7 A1 E6 7 compares\n O 10 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 8 compares\n N 11 N11 O10 I9 T8 U5 Q4 Y3 S7 A1 E6 9 compares\n\nTotal: 55 compares\n\nThanks to ebber22 (https://github.com/ebber22) for finding an issue with the way the nodes were being added.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/102","support_files":[],"metadata":{"number":"3.5.10","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Develop a MultiSET class that is like SET, but allows equal keys and thus implements a mathematical multiset.","answer":"3.1.11\n\n\t\t\tkeys[]\t\t\t\t vals[]\nkey value 0 1 2 3 4 5 6 7 8 9 N 0 1 2 3 4 5 6 7 8 9\n E 0 E 1 0 0 compares\n A 1 A E 2 1 0 2 compares\n S 2 A E S 3 1 0 2 2 compares\n Y 3 A E S Y 4 1 0 2 3 2 compares\n Q 4 A E Q S Y 5 1 0 4 2 3 3 compares\n U 5 A E Q S U Y 6 1 0 4 2 5 3 4 compares\n E 6 A E Q S U Y 6 1 6 4 2 5 3 4 compares\n S 7 A E Q S U Y 6 1 6 4 7 5 3 4 compares\n T 8 A E Q S T U Y 6 1 6 4 7 8 5 3 4 compares\n I 9 A E I Q S T U Y 6 1 6 9 4 7 8 5 3 4 compares\n O 10 A E I O Q S T U Y 6 1 6 9 10 4 7 8 5 3 4 compares\n N 11 A E I N O Q S T U Y 6 1 6 9 11 10 4 7 8 5 3 5 compares\n A E I N O Q S T U Y 1 6 9 11 10 4 7 8 5 3\n\nTotal: 38 compares","support_files":[],"metadata":{"number":"3.5.11","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Modify LookupCSV to make a program RangeLookupCSV that takes two key values from the standard input and prints all key-value pairs in the .csv file such that the key falls within the range specified.","answer":"3.1.13\n\nFor an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.\nThe application does a lot more get() than put() operations and a binary search symbol table implementation has a O(log(n)) runtime complexity for the get() operation, which is better than the O(n) runtime complexity of the sequential search symbol table implementation.","support_files":[],"metadata":{"number":"3.5.13","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Develop and test a static method invert() that takes as argument an ST> and produces as return value the inverse of the given symbol table (a symbol table of the same type).","answer":"3.1.14\n\nFor an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.\n\nThe worst-case runtime cost of the put() operation for a binary search symbol table is 2N while for a sequential search symbol table it is N.\nFor the get() operation, the worst-case runtime cost of a binary search symbol table is lg(n) while for the sequential search symbol table it is N.\n\nComparing the total number of operations in the worst-case:\nSequential search symbol table: 10^6 + 10^3 ~ 10^6 operations\nBinary search symbol table: 2 * 10^6 + lg(10^3) ~ 2 * 10^6 operations\n\nThe average-case runtime cost of both implementations in this case is similar because most of the operations are put() and both the sequential search symbol table and the binary search symbol table implementations have an average-case cost of N for it.\n\nSo for this application the sequential search symbol table performs better than the binary search symbol table in the worst-case and both perform similarly in the average-case, making the sequential search symbol table the best choice.\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for showing that the sequential search symbol table is the best option in this question.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/119","support_files":[],"metadata":{"number":"3.5.14","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Write a program that takes a string on standard input and an integer k as command-line argument and puts on standard output a sorted list of the k-grams found in the string, each followed by its index in the string.","answer":"3.1.15\n\n Searches Percentage of total time spent on insertions\n 1000 0.00%\n 1000000 6.10%\n 1000000000 96.26%\n\nThe average insertion cost is N, so the total insertion cost for N keys is N^2.\nThe average search cost is lg N, so the total search cost for M keys is M * lg N.\nAccording to the question, M = 1000 * N.\n\nThe total cost is then:\ntotal cost = N^2 + M * lg N = N^2 + 1000N * lg N\n\nThe insertion percentage is:\nP = (N^2) / (N^2 + 1000N * lg N)\nN^2 is the higher-order element in the equation, so as N increases, the insertion percentage approaches 100%.\n\nThanks to faame (https://github.com/faame) for improving this answer.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/222","support_files":[],"metadata":{"number":"3.5.15","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Exercise","code_execution":false}} {"question":"Multisets. After referring to Exercises 3.5.2 and 3.5.3 and the previous exercise, develop APIs MultiHashSET and MultiSET for multisets (sets that can have equal keys) and implementations SeparateChainingMultiSET and BinarySearchMultiSET for multisets and ordered multisets, respectively.","answer":"3.1.18\n\nThe rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.\nIf the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.\nAfter comparing the middle element with the search key, if it is smaller, the search continues on the right side of the array.\nIf it is bigger, the search continues on the left side of the array.\nIf they have the same value, the current element's index is the rank we are looking for.\n\nThis guarantees that if an element exists in the symbol table its rank will be found in the rank() method.\n\nWhen the element does not exist the value of the \"low\" variable will have passed the value of the \"high\" variable, pointing to the correct rank of where the key should be. This only happens when both the element on the left of the final rank has been checked and the element on the current (final) rank has been checked. After these checks, low will be pointing to the correct rank location.\n\nExample:\n\nSymbol Table: 0 1 2 3 5 6\nRank of key 4 (non-existent)\n\n1- The initial search range is [0..5]. The rank() method checks the left of the middle elements on index 2 -> value 2\n2- 2 is less than 4, so the new range to search is [3..5]. The rank() method checks the middle element on index 4 -> value 5\n3- 5 is more than 4, so the new range to search is [3..3]. The rank() method checks the only element left (index 3) -> value 3\n4- 3 is less than 4, so the new range to search is [4..3]. Now the \"low\" variable is bigger than the \"high\" variable.\n5- The rank() method returns the value of the \"low\" variable, 4. This is the correct rank for key 4.","support_files":[],"metadata":{"number":"3.5.18","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Concordance. Write an ST client Concordance that puts on standard output a concordance of the strings in the standard input stream (see page 498).","answer":"3.1.20\n\nProposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful). \n\nProof: Let C(N) be the number of compares to search for a key in a symbol table of size N.\nWe have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationship that directly mirrors the recursive method:\nC(N) <= C(FLOOR(N / 2)) + 1\n\nWhether the search goes to the left or to the right, the size of the subarray is no more than FLOOR(N / 2), and we can use one compare to check for equality and to choose whether to go left or right.\n\nLet's first prove by induction that C(N) is monotonic: C(N) <= C(N + 1) for all N > 0.\n\nIt is trivial to prove that:\nC(1) = 1\nC(2) = 1 or 2\n\nThus we have:\nC(1) <= C(2)\n\nAssume for all N=[0, K]\nC(N + 1) >= C(N)\n\nThus we have:\nC(K + 1) >= C(K)\n\nAt the beginning of the binary search, low has value 0 and high has value N. Mid is computed as:\nmid = low + (high - low) / 2 = high / 2\n\nLet's use L to represent the size of the left half and R to represent the size of the right half.\nThe mid element has size 1.\nWhen N = K + 1 the total size is L + 1 + R.\n\nWhen N = K + 2:\nmid = low + (high - low) / 2 = (high + 1) / 2 = (N + 1) / 2\n\nWhen N is incremented by 1 (from K + 1 to K + 2), the mid point either remains in the same place or shifts to the right by 1.\n1- If mid remains in the same place, then L remains the same, and R is incremented by 1.\nSince (R + 1) <= K + 1, we have:\nC(K + 2) = C(L) + 1 + C(R + 1) >= C(L) + 1 + C(R) = C(K + 1)\n2- If mid shifts to the right by 1, then L is incremented by 1 and R remains the same.\nSince (L + 1) <= K + 1, we have:\nC(K + 2) = C(L + 1) + 1 + C(R) >= C(L) + 1 + C(R) = C(K + 1)\n\nTherefore, given C(K + 1) >= C(K) it is also true that C(K + 2) >= C(K + 1), which proves that C(N) is monotonic.\n\nFor a general N, we have that:\n\nC(N) <= C(N / 2) + 1 (one comparison to check equality or decide which way of the subarray to go)\nC(N / 2) <= C(N / 4) + 1\n\nPutting the value of C(N / 2) in the first equation:\nC(N) <= C(N / 4) + 1 + 1\n\nAnd adding all values to the first equation until C = 1:\nC(N) <= C(N / 8) + 1 + 1 + 1\nC(N) <= C(N / 16) + 1 + 1 + 1 + 1\nC(N) <= C(N / 2^k) + 1 + 1 + 1 + 1 + ... + 1\n\nuntil we get to\nC(N) <= 1 + 1 + 1 + 1 + 1 + ... + 1 (even if N is not divisible by 2 there is still a compare operation)\nC(N) <= k + 1\n\nIn this case, 2^k = N\nk <= lg N + 1\n\nWe can also prove it using the Master theorem:\n\nBinary search recurrence relation:\nT(N) = T(N/2) + O(1)\n\nMaster theorem:\nT(N) = aT(N/b) + f(N)\n\nHere, a = 1, b = 2 and f(n) is O(1) (constant)\n\nc = log(a base b) = log(1 base 2) = 0\n\nWe can see that this is the case 2 of the Master theorem by taking k = 0 in this equation:\nO(n^c * (log n)^k)\nO(n^0 * (log n)^0) = O(1) = f(n) -> This means we are in case 2 of the Master theorem\n\nFrom the Case 2 of the Master Theorem we know that:\nT(n) = O(n^(log a base b) * (log n)^(k + 1))\nT(n) = O(n^0 * log(n)^1) = O(log n)\n\nWith binary search, we achieve a logarithmic-time search guarantee.\n\nReference: https://en.wikipedia.org/wiki/Master_theorem\n\nThanks to faame (https://github.com/faame) for adding the section proving that C(N) is monotonic.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/223","support_files":[],"metadata":{"number":"3.5.20","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Inverted concordance. Write a program InvertedConcordance that takes a concordance on standard input and puts the original string on standard output stream. Note: This computation is associated with a famous story having to do with the Dead Sea Scrolls. The team that discovered the original tablets enforced a secrecy rule that essentially resulted in their making public only a concordance. After a while, other researchers figured out how to invert the concordance, and the full text was eventually made public.","answer":"3.1.21 - Memory usage\n\n* BinarySearchST\n object overhead -> 16 bytes\n Key[] reference (keys) -> 8 bytes\n Value[] reference (values) -> 8 bytes\n int value (size) -> 4 bytes\n padding -> 4 bytes\n Key[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Key references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\n Value[]\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n N Value references -> between 8N and 32N bytes (the resizing array may be 25% to 100% full)\nAmount of memory needed: 16 + 8 + 8 + 4 + 4 + 16 + 4 + 4 + (8N to 32N) + 16 + 4 + 4 + (8N to 32N) = (16N to 64N) + 88 bytes\n\n* SequentialSearchST\n object overhead -> 16 bytes\n Node reference (first) -> 8 bytes\n Node\n object overhead -> 16 bytes\n extra overhead for reference to the enclosing instance -> 8 bytes\n Key reference (key) -> 8 bytes\n Value reference (value) -> 8 bytes\n Node reference (next) -> 8 bytes\n (N Node references -> 48N bytes)\n int value (size) -> 4 bytes\n padding -> 4 bytes\nAmount of memory needed: 16 + 8 + (16 + 8 + 8 + 8 + 8)N + 4 + 4 = 48N + 32 bytes","support_files":[],"metadata":{"number":"3.5.21","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"Sparse matrices. Develop an API and an implementation for sparse 2D matrices. Support matrix addition and matrix multiplication. Include constructors for row and column vectors.","answer":"3.1.23 - Analysis of binary search\n\nAs the book and exercise 3.1.20 have proven, the maximum number of compares used for a binary search in a table of size N is lg N + 1.\n\nA number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).\n\nFor example:\n\nN Bit representation Number of bits lg N + 1\n1 1 1 1\n2 10 2 2\n4 100 3 3\n5 101 3 3\n9 1001 4 4\n\nTherefore, the maximum number of compares used for a binary search in a table of size N is precisely the number of bits in the binary representation of N.","support_files":[],"metadata":{"number":"3.5.23","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"List. Develop an implementation of the following API:\npublic class List implements Iterable\n List() create a list\n void addFront(Item item) add item to the front\n void addBack(Item item) add item to the back\n Item deleteFront() remove from the front\n Item deleteBack() remove from the back\n void delete(Item item) remove item from the list\n void add(int i, Item item) add item as the ith in the list\n Item delete(int i) remove the ith item from the list\n boolean contains(Item item) is key in the list?\n boolean isEmpty() is the list empty?\n int size() number of items in the list\nHint: Use two symbol tables, one to find the ith item in the list efficiently, and the other to efficiently search by item. (Java’s java.util.List interface contains methods like these but does not supply any implementation that efficiently supports all operations.)","answer":"3.1.27 - Small tables\n\nBuilding the binary search symbol table requires N calls to put().\nEvery put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).\nAssuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the smallest element and ending with the highest element.\nBy doing this, every element will be inserted at the end of the keys[] and values[] array, making the put() operation use O(lg N) for the rank() operation and O(1) for the insert (there will be no need to move keys and values to the right since the new element is the rightmost element). N inserts will have an order of growth of O(N lg N).\n\nA search operation has the order of growth O(lg N).\nTherefore, the order of growth of S should be O(N), with S search operations having an order of growth O(N lg N), making the cost of building the table the same as the cost of all searches.\n\nIf the items are inserted in random order, the put operation has an order of growth O(N): O(lg N) for the rank operation and O(N) for inserting an element. N inserts will have an order of growth of O(N^2).\nIn this case, the order of growth of S should be O(N^2 / lg N).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for correcting the orders of growth of S.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/120","support_files":[],"metadata":{"number":"3.5.27","chapter":3,"chapter_title":"Searching","section":3.5,"section_title":"Applications","type":"Creative Problem","code_execution":false}} {"question":"What is the maximum number of edges in a graph with V vertices and no parallel edges? What is the minimum number of edges in a graph with V vertices, none of which are isolated?","answer":"4.1.1\n\nThe maximum number of edges in a graph with V vertices and no parallel edges is V * (V - 1) / 2.\nSince we do not have self-loops or parallel edges, each vertex can connect to V - 1 other vertices. In an undirected graph vertex v connected to vertex w is the same as vertex w connected to vertex v, so we divide the result by 2.\n\nExample:\no - o\n| X |\no — o\n\nThe minimum number of edges in a graph with V vertices, none of which are isolated (have degree 0) is V - 1.\nExample:\no — o — o","support_files":[],"metadata":{"number":"4.1.1","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Draw, in the style of the figure in the text (page 524), the adjacency lists built by Graph’s input stream constructor for the file tinyGex2.txt depicted at left.","answer":"4.1.2\n\nadj[]\n 0 -> 5 -> 2 -> 6\n 1 -> 4 -> 8 -> 11\n 2 -> 5 -> 6 -> 0 -> 3\n 3 -> 10 -> 6 -> 2\n 4 -> 1 -> 8\n 5 -> 0 -> 10 -> 2\n 6 -> 2 -> 3 -> 0\n 7 -> 8 -> 11\n 8 -> 1 -> 11 -> 7 -> 4\n 9 -> \n 10 -> 5 -> 3\n 11 -> 8 -> 7 -> 1","support_files":[],"metadata":{"number":"4.1.2","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Consider the four-vertex graph with edges 0-1, 1-2, 2-3, and 3-0. Draw an array of adjacency-lists that could not have been built calling addEdge() for these edges no matter what order.","answer":"4.1.6\n\nThe edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.\n\nadj[]\n 0 -> 1 -> 3 (the original was 0 -> 3 -> 1)\n 1 -> 2 -> 0\n 2 -> 3 -> 1\n 3 -> 0 -> 2","support_files":[],"metadata":{"number":"4.1.6","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the figure on page 533, a detailed trace of the call dfs(0) for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). Also, draw the tree represented by edgeTo[].","answer":"4.1.9\n marked[] adj[]\ndfs (0) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (5) 0 T 0 5 2 6\n check 0 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (10) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (3) 0 T 0 5 2 6\n check 10 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (6) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (2) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n check 6 2 T 2 5 6 0 3\n check 0 3 T 3 10 6 2 \n check 3 4 4 1 8 \n 2 done 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\n\nedgeTo[] tree\n \n 0\n 5\n 10\n 3\n 6\n 2","support_files":[],"metadata":{"number":"4.1.9","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Prove that every connected graph has a vertex whose removal (including all adjacent edges) will not disconnect the graph, and write a DFS method that finds such a vertex. Hint: Consider a vertex whose adjacent vertices are all marked.","answer":"4.1.10\n\nEvery connected graph has a vertex whose removal (including all incident edges) will not disconnect the graph.\n\nProof by contradiction:\nIf the graph has a node of degree one, removing it gives a connected graph.\nExample: o - o\n\nOtherwise, every path in the graph belongs to a cycle. To see this, start with any path, then notice that the terminal nodes of this path must be connected to other nodes that are not in the path, so we add them to the path to make a new path. Since the graph is connected, continuing this process it is possible to see that in the end all the nodes from the graph will be in the path.\n\nIf among all those paths there is no path from which one can remove a node without disconnecting the graph, then all those paths are bridges. In this case, they do not belong to a cycle, which is a contradiction (assuming the graph is finite).\n\nBased on: https://math.stackexchange.com/questions/891325/proof-verification-a-connected-graph-always-has-a-vertex-that-is-not-a-cut-vert","support_files":[],"metadata":{"number":"4.1.10","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Draw the tree represented by edgeTo[] after the call bfs(G, 0) in ALGORITHM 4.2 for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2).","answer":"4.1.11\n\nTree represented by edgeTo[] after call to bfs(G, 0):\n\n 0\n 5 2 6\n 10 3","support_files":[],"metadata":{"number":"4.1.11","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"What does the BFS tree tell us about the distance from v to w when neither is at the root?","answer":"4.1.12\n\nWhen neither v nor w are at the root, the BFS tree tell us that if they are on the same branch, there is a path between v and w of distance equal to the number of edges between them in the branch.\nIf they are not on the same branch, there is a path between v and w of distance Dv + Dw, where Dv is the distance from the root to vertex v and Dw is the distance from the root to vertex w.","support_files":[],"metadata":{"number":"4.1.12","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Suppose you use a stack instead of a queue when running breadth-first search. Does it still compute shortest paths?","answer":"4.1.14\n\nIf we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.\nThis can be seen in the following graph:\n\n 0 (source)\n / \\\n1 - 2\n| |\n4 - 3\n\nIf the edge 0 - 2 is inserted before the edge 0 - 1:\nUsing a stack, the distance from 0 to 4 will be 3.\nUsing a queue, the distance from 0 to 4 will be 2.\n\nIf the edge 0 - 1 is inserted before the edge 0 - 2:\nUsing a stack, the distance from 0 to 3 will be 3.\nUsing a queue, the distance from 0 to 3 will be 2.\n\nThanks to lemonadeseason (https://github.com/lemonadeseason) for correcting the example in this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/24","support_files":[],"metadata":{"number":"4.1.14","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the figure on page 545, a detailed trace of CC for finding the connected components in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2).","answer":"4.1.19\n count marked[] id[]\n 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) 0 T 0\n dfs(5) 0 T T 0 0\n check 0\n dfs(10) 0 T T T 0 0 0\n check 5\n dfs(3) 0 T T T T 0 0 0 0\n check 10\n dfs(6) 0 T T T T T 0 0 0 0 0\n dfs(2) 0 T T T T T T 0 0 0 0 0 0\n check 5\n check 6\n check 0\n check 3\n 2 done\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\ndfs(1) 1 T T T T T T T 0 1 0 0 0 0 0\n dfs(4) 1 T T T T T T T T 0 1 0 0 1 0 0 0\n check 1\n dfs(8) 1 T T T T T T T T T 0 1 0 0 1 0 0 1 0\n check 1\n dfs(11) 1 T T T T T T T T T T 0 1 0 0 1 0 0 1 0 1\n check 8\n dfs(7) 1 T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 0 1\n check 8\n check 11\n 7 done\n check 1\n 11 done\n check 7\n check 4\n 8 done\n 4 done\n check 8\n check 11\n1 done\ndfs(9) 2 T T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 2 0 1\n9 done","support_files":[],"metadata":{"number":"4.1.19","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the figures in this section, a detailed trace of Cycle for finding a cycle in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the Cycle constructor, in the worst case?","answer":"4.1.20\n Has Cycle? marked[] \n F 0 1 2 3 4 5 6 7 8 9 10 11 \ndfs(0) T \n dfs(5) T T \n check 0 F\n dfs(10) T T T \n check 5 F\n dfs(3) T T T T \n check 10 F\n dfs(6) T T T T T \n dfs(2) T T T T T T \n check 5 T (cycle found here)\n check 6 T\n check 0 T\n check 3 T\n 2 done\n check 3 T\n check 0 T\n 6 done\n check 2 T\n 3 done\n 10 done\n check 2 T\n 5 done\n check 2 T\n check 6 T\n0 done\ndfs(1) T T T T T T T \n dfs(4) T T T T T T T T \n check 1 T\n dfs(8) T T T T T T T T T \n check 1 T\n dfs(11) T T T T T T T T T T \n check 8 T\n dfs(7) T T T T T T T T T T T \n check 8 T\n check 11 T\n 7 done\n check 1 T\n 11 done\n check 7 T\n check 4 T\n 8 done\n 4 done\n check 8 T\n check 11 T\n1 done\ndfs(9) T T T T T T T T T T T T\n9 done\n\nThe order of growth of the running time of the Cycle constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] array takes time proportional to V.","support_files":[],"metadata":{"number":"4.1.20","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the figures in this section, a detailed trace of TwoColor for finding a two-coloring of the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the TwoColor constructor, in the worst case?","answer":"4.1.21\n Is 2-colorable? marked[] color[]\n T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) T F F F F F F F F F F F F\n dfs(5) T T F F F F F T F F F F F F\n check 0 T\n dfs(10) T T T F F F F F T F F F F F F\n check 5 T\n dfs(3) T T T T F F F T F T F F F F F F\n check 10 T\n dfs(6) T T T T T F F F T F T F F F F F F\n dfs(2) T T T T T T F F T T F T F F F F F F\n check 5 F\n check 6 F\n check 0 F\n check 3 F\n 2 done\n check 3 F\n check 0 F\n 6 done\n check 2 F\n 3 done\n 10 done\n check 2 F\n 5 done\n check 2 F\n check 6 F\n0 done\ndfs(1) T T T T T T T F F T T F T F F F F F F\n dfs(4) T T T T T T T T F F T T T T F F F F F F\n check 1 F\n dfs(8) T T T T T T T T T F F T T F T F F F F F F\n check 1 F\n dfs(11) T T T T T T T T T T F F T T F T F F F F F T\n check 8 F\n dfs(7) T T T T T T T T T T T F F T T F T F F F F F F\n check 8 F\n check 11 F\n 7 done\n check 1 F\n 11 done\n check 7 F\n check 4 F\n 8 done\n 4 done\n check 8 F\n check 11 F\n1 done\ndfs(9) T T T T T T T T T T T T F F T T F T F F F F F F\n9 done\n\nThe order of growth of the running time of the TwoColor constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] and color[] arrays takes time proportional to V.","support_files":[],"metadata":{"number":"4.1.21","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Compute the number of connected components in movies.txt, the size of the largest component, and the number of components of size less than 10. Find the eccentricity, diameter, radius, a center, and the girth of the largest component in the graph. Does it contain Kevin Bacon?","answer":"4.1.24\n\nNumber of connected components: 33\nSize of the largest component: 118774\nNumber of components of size less than 10: 5\nDoes the largest component contain Kevin Bacon: Yes\n\nEccentricity, diameter, radius, center and girth:\n\nThe strategy for computing the eccentricity, diameter, radius, center and girth of the largest component was the following:\nThe algorithm required for these exact computations has complexity of O(V * E) (running breadth-first search from all vertices). V is ~= 10^5, which means the algorithm required for these exact computation has complexity ~= 10^10.\n\nIn order to reduce the complexity of the computations (and to be able to compute them), domain knowledge was used to compute approximate results.\nBased on the Kevin Bacon game, we know that Kevin Bacon has been on several movies and that he is closely connected to most of the actors and actresses in the graph. Therefore, he has a high probability of being the center of the graph.\n\nUsing Kevin Bacon as the center, we compute his vertex eccentricity to get the graph radius.\nA breadth-first search using Kevin Bacon as the source computes the vertices that are furthest from the center. Computing the eccentricities of these vertices we can find the diameter of the graph.\n\nThe eccentricities of the center and of the vertices furthest from it are shown in the results. The range of the eccentricities is [10, 18]. Computing the eccentricities of all vertices would bring us back to the original problem of =~ 10^10 operations.\n\nFinally, for the girth, we know that there is a very high probability that two actors have worked together on two different movies. This gives a girth of 4, which is the minimum girth possible for the movies graph:\nActor -- Movie -- Actor\n \\ /\n \\ Movie /\nTo validate this theory we run the algorithm to compute the girth of the graph but stop once we find a cycle of length 4, since it is the shortest cycle possible.\n\n\nEccentricities of Kevin Bacon and of vertices furthest from the center in the largest component:\nEccentricity of vertex 22970: 16\nEccentricity of vertex 22971: 16\nEccentricity of vertex 22972: 16\nEccentricity of vertex 22973: 16\nEccentricity of vertex 22974: 16\nEccentricity of vertex 22976: 16\nEccentricity of vertex 22977: 16\nEccentricity of vertex 22978: 16\nEccentricity of vertex 22979: 16\nEccentricity of vertex 22980: 16\nEccentricity of vertex 51437: 18\nEccentricity of vertex 51438: 18\nEccentricity of vertex 51439: 18\nEccentricity of vertex 51440: 18\nEccentricity of vertex 51441: 18\nEccentricity of vertex 51442: 18\nEccentricity of vertex 51443: 18\nEccentricity of vertex 51444: 18\nEccentricity of vertex 51445: 18\nEccentricity of vertex 51446: 18\nEccentricity of vertex 51447: 18\nEccentricity of vertex 51448: 18\nEccentricity of vertex 51449: 18\nEccentricity of vertex 51450: 18\nEccentricity of vertex 51451: 18\nEccentricity of vertex 51452: 18\nEccentricity of vertex 51453: 18\nEccentricity of vertex 51454: 18\nEccentricity of vertex 51455: 18\nEccentricity of vertex 51456: 18\nEccentricity of vertex 51457: 18\nEccentricity of vertex 51458: 18\nEccentricity of vertex 51459: 18\nEccentricity of vertex 51460: 18\nEccentricity of vertex 51461: 18\nEccentricity of vertex 51462: 18\nEccentricity of vertex 51463: 18\nEccentricity of vertex 51464: 18\nEccentricity of vertex 51465: 18\nEccentricity of vertex 51466: 18\nEccentricity of vertex 51467: 18\nEccentricity of vertex 51468: 18\nEccentricity of vertex 51469: 18\nEccentricity of vertex 51470: 18\nEccentricity of vertex 51471: 18\nEccentricity of vertex 51472: 18\nEccentricity of vertex 51473: 18\nEccentricity of vertex 51474: 18\nEccentricity of vertex 51475: 18\nEccentricity of vertex 51476: 18\nEccentricity of vertex 51477: 18\nEccentricity of vertex 51478: 18\nEccentricity of vertex 51479: 18\nEccentricity of vertex 51480: 18\nEccentricity of vertex 51481: 18\nEccentricity of vertex 51482: 18\nEccentricity of vertex 51483: 18\nEccentricity of vertex 51484: 18\nEccentricity of vertex 51485: 18\nEccentricity of vertex 51486: 18\nEccentricity of vertex 51487: 18\nEccentricity of vertex 51488: 18\nEccentricity of vertex 51489: 18\nEccentricity of vertex 51490: 18\nEccentricity of vertex 51491: 18\nEccentricity of vertex 51492: 18\nEccentricity of vertex 51493: 18\nEccentricity of vertex 51494: 18\nEccentricity of vertex 51495: 18\nEccentricity of vertex 51496: 18\nEccentricity of vertex 51497: 18\nEccentricity of vertex 51498: 18\nEccentricity of vertex 51499: 18\nEccentricity of vertex 51500: 18\nEccentricity of vertex 51501: 18\nEccentricity of vertex 51502: 18\nEccentricity of vertex 51503: 18\nEccentricity of vertex 51504: 18\nEccentricity of vertex 51505: 18\nEccentricity of vertex 51506: 18\nEccentricity of vertex 51507: 18\nEccentricity of vertex 51508: 18\nEccentricity of vertex 51509: 18\nEccentricity of vertex 51510: 18\nEccentricity of vertex 51511: 18\nEccentricity of vertex 51512: 18\nEccentricity of vertex 51513: 18\nEccentricity of vertex 51514: 18\nEccentricity of vertex 51515: 18\nEccentricity of vertex 51516: 18\nEccentricity of vertex 51517: 18\nEccentricity of vertex 51518: 18\nEccentricity of vertex 51519: 18\nEccentricity of vertex 51520: 18\nEccentricity of vertex 86241: 16\nEccentricity of vertex 86242: 16\nEccentricity of vertex 86243: 16\nEccentricity of vertex 86244: 16\nEccentricity of vertex 86245: 16\nEccentricity of vertex 86246: 16\nEccentricity of vertex 86247: 16\nEccentricity of vertex 86248: 16\nEccentricity of vertex 86249: 16\nEccentricity of vertex 86250: 16\nEccentricity of vertex 86251: 16\nEccentricity of vertex 86252: 16\nEccentricity of vertex 86253: 16\nEccentricity of vertex 86254: 16\nEccentricity of vertex 86255: 16\nEccentricity of vertex 86256: 16\nEccentricity of vertex 86257: 16\nEccentricity of vertex 86258: 16\nEccentricity of vertex 86259: 16\nEccentricity of vertex 118353: 18\nEccentricity of vertex 118354: 18\nEccentricity of vertex 118355: 18\nEccentricity of vertex 118356: 18\nEccentricity of vertex 118357: 18\nEccentricity of vertex 118358: 18\nEccentricity of vertex 118359: 18\nEccentricity of vertex 118360: 18\nEccentricity of vertex 118361: 18\nEccentricity of vertex 118362: 18\nEccentricity of vertex 118363: 18\nEccentricity of vertex 118364: 18\nEccentricity of vertex 9145: 10\n\nDiameter of largest component: 18\nRadius of largest component: 10\nCenter of largest component: 9145\nGirth of largest component: 4","support_files":[],"metadata":{"number":"4.1.24","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Determine the amount of memory used by Graph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4.","answer":"4.1.27\n\nInteger\n* object overhead -> 16 bytes\n* int value -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 4 + 4 = 24 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* Integer (item) -> 24N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 24N = 64N + 32 bytes\n\nGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 64E + 32 bytes -> There are V Bags and in total, they have 2E nodes -> 128E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 128E + 32V = 128E + 40V + 56 bytes","support_files":[],"metadata":{"number":"4.1.27","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Two graphs are isomorphic if there is a way to rename the vertices of one to make it identical to the other. Draw all the nonisomorphic graphs with two, three, four, and five vertices.","answer":"4.1.28\n\nNon-isomorphic graphs:\n\nThere are 2 non-isomorphic graphs with 2 vertices:\no o\n\no-o\n\nThere are 4 non-isomorphic graphs with 3 vertices:\n o\no o\n\n o\no-o\n\no-o-o\n\n o\n/ \\\no-o\n\nThere are 11 non-isomorphic graphs with 4 vertices:\no o o o\n\no-o o o\n\no-o-o o\n\no-o-o-o\n\no-o o-o\n\n o\n |\n o\n / \\\no o\n\n o\n / \\\no---o o\n\no-o\n| |\no-o\n\n o\n | \n o\n / \\\no---o\n\n o\n / \\\no---o\n \\ /\n o\n\n o\n /|\\\n / o \\\n/ / \\ \\\no------o\n\nThere are 34 non-isomorphic graphs with 5 vertices:\n o\no o\n o o\n\n o\no o\n o-o\n\n o\no o\n /\n o-o\n\n o\no o\n \\ /\n o o\n\n o\n / | \\\no o o \n o\n\n o\n / \\\no o \n o-o\n\n o\n / \\\no o \n \\\n o o\n\n o\n / \\\no----o\n o o\n\n o\n /|\\\\\no o oo\n\no-o\n| |\no-o o\n\no\n|\no-o\n| |\no o\n\n o\n |\n o\n / \\\no---o o\n\no-o-o-o-o\n\n o o\n /| |\no | |\n \\| |\n o o\n\no--o\n| |\no--o\n|\no\n\no o\n| |\no---o\n \\ /\n o\n\n o--o\n \\/\no--o--o\n\n o\n / \\\no o \n \\ /\n o-o\n\n o (This is a complete graph, where all vertices have degree = 4)\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o---o\n\n o\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|/\no---o\n\no---o\n|\\ /|\n| o |\n|/ \\|\no---o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|\no---o\n\n o\n // \\\no-o o\n \\/\n o\n\no-o-o-o\n \\| | /\n o\n\n o\n /\\\n / \\\n / \\\no------o\n\\ \\ / /\n \\ /\\ /\n o o\n\no---o\n| X | o\no---o\n\no o\n|\\ /|\n| o |\n|/ \\|\no o\n\n o\n /|\\\no--o | o\n \\|/\n o\n\n o\n |\n o\n /|\\\no | o\n \\|/\n o\n\n o\n / \\\no---o\n| |\no---o\n\no---o\n| /|\n| o |\n|/ |\no---o\n\n o\n |\n o\n |\n o\n / \\\no---o\n\no---o\n| \\ |\no---o o\n\nBased on: http://www.graphclasses.org/smallgraphs.html","support_files":[],"metadata":{"number":"4.1.28","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Exercise","code_execution":false}} {"question":"Eulerian and Hamiltonian cycles. Consider the graphs defined by the following four sets of edges:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\nWhich of these graphs have Euler cycles (cycles that visit each edge exactly once)? Which of them have Hamilton cycles (cycles that visit each vertex exactly once)?","answer":"4.1.30 - Eulerian and Hamiltonian cycles\n\nAn Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.\nA Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visited twice).\n\nAccording to Euler theorems a graph has an Eulerian cycle/circuit if and only if it does not have any vertices of odd degree.\n\nFirst graph:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9).\nIt has a Hamiltonian cycle: 1-4 4-8 8-7 7-6 6-9 9-5 5-2 2-0 0-3 3-1\n\nSecond graph:\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n\nIt has an Eulerian cycle (all the vertices have even degrees):\n0-3 3-0 0-2 2-5 5-9 9-6 6-5 5-8 8-8 8-4 4-7 7-6 6-3 3-1 1-0\nThere is no Hamiltonian cycle.\n\nThird graph:\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 4-8 8-7 7-6 6-9 9-5 5-2 2-1 1-3 3-0 0-4\n\nFourth graph:\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 0-5 5-4 4-1 1-6 6-3 3-7 7-9 9-8 8-2 2-0","support_files":[],"metadata":{"number":"4.1.30","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Creative Problem","code_execution":false}} {"question":"Graph enumeration. How many different undirected graphs are there with V vertices and E edges (and no parallel edges)?","answer":"4.1.31 - Graph enumeration\n\nIf we were considering graphs with no self-loops:\n\nThere are (V) ways to choose a set {u, v} of two vertices. From this set there are E ways to choose the vertices to connect.\n (2)\nSo there are ((V)) = (V! / 2! * (V - 2)!)! / E! * ((V! / 2! * (V - 2)!) - E)!\n ((2))\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges and no self-loops).\n\nSince we are also considering graphs with self-loops, there are (V) * 2^V ways to choose a set {u, v} of two vertices in which\n (2)\nvertices may or may not have a self-loop.\n\nSo there are ((V) * 2^V) = ((V! / 2! * (V - 2)!) * 2^V)! / E! * (((V! / 2! * (V - 2)!) * 2^V) - E)!\n ((2) )\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges).\n\nReference:\nHandbook of Discrete and Combinatorial Mathematics by Kenneth H. Rosen, page 580\nhttps://math.stackexchange.com/questions/1072726/counting-simple-connected-labeled-graphs-with-n-vertices-and-k-edges\nhttps://math.stackexchange.com/questions/128439/how-to-determine-the-number-of-directed-undirected-graphs","support_files":[],"metadata":{"number":"4.1.31","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Creative Problem","code_execution":false}} {"question":"Odd cycles. Prove that a graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.","answer":"4.1.33 - Odd cycles\n\nA graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.\n\nProof:\n1- Proving that a graph with an odd-length cycle cannot be bipartite:\nIf a graph G is bipartite with vertex sets V1 and V2, every step along a walk takes you either from V1 to V2 or from V2 to V1. To end up where you started, therefore, you must take an even number of steps.\n\n2- Proving that a graph with only even-length cycles is bipartite:\nConsider G to be a graph with only even-length cycles. Let v0 be any vertex. For each vertex v in the same component C0 as v0 let d(v) be the length of the shortest path from v0 to v. Color red every vertex in C0 whose distance from v0 is even, and color the other vertices of C0 blue. Do the same for each component of G. Check that if G had any edge between two red vertices or between two blue vertices, it would have an odd cycle. Thus, G is bipartite, the red vertices and the blue vertices being the two parts.\n\nReference: \nhttps://math.stackexchange.com/questions/311665/proof-a-graph-is-bipartite-if-and-only-if-it-contains-no-odd-cycles","support_files":[],"metadata":{"number":"4.1.33","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Creative Problem","code_execution":false}} {"question":"Biconnectedness. A graph is biconnected if every pair of vertices is connected by two disjoint paths. An articulation point in a connected graph is a vertex that would disconnect the graph if it (and its adjacent edges) were removed. Prove that any graph with no articulation points is biconnected. Hint: Given a pair of vertices s and t and a path connecting them, use the fact that none of the vertices on the path are articulation points to construct two disjoint paths connecting s and t.","answer":"4.1.35 - Biconnectedness\n\nAny graph with no articulation points is biconnected.\n\nProof:\nConsider two vertices, s, t, and a path P1 connecting s to t.\nWe know that no vertex in P1 is an articulation point, so for each vertex v in the path, there is always another path P2 connecting s to t that does not include it. Also, P2 does not include any of the vertices of P1, otherwise any vertex included in both paths would be an articulation point (being the only way to connect s to t).\nThis means that every pair of vertices is connected by two vertex-disjoint paths (such as P1 and P2), making the graph biconnected.\n\nGraph illustration (P1 is the path s-v1 v1-v2 v2-t and P2 is the path s-v3 v3-v4 v4-t):\n\ns\n|\\\n| \\\nv1 v3\n| \\\n| v4\nv2 /\n| /\n|/\nt","support_files":[],"metadata":{"number":"4.1.35","chapter":4,"chapter_title":"Graphs","section":4.1,"section_title":"Undirected Graphs","type":"Creative Problem","code_execution":false}} {"question":"What is the maximum number of edges in a digraph with V vertices and no parallel edges? What is the minimum number of edges in a digraph with V vertices, none of which are isolated?","answer":"4.1.1\n\nThe maximum number of edges in a graph with V vertices and no parallel edges is V * (V - 1) / 2.\nSince we do not have self-loops or parallel edges, each vertex can connect to V - 1 other vertices. In an undirected graph vertex v connected to vertex w is the same as vertex w connected to vertex v, so we divide the result by 2.\n\nExample:\no - o\n| X |\no — o\n\nThe minimum number of edges in a graph with V vertices, none of which are isolated (have degree 0) is V - 1.\nExample:\no — o — o","support_files":[],"metadata":{"number":"4.2.1","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Draw, in the style of the figure in the text (page 524), the adjacency lists built by Digraph’s input stream constructor for the file tinyDGex2.txt depicted at left.","answer":"4.1.2\n\nadj[]\n 0 -> 5 -> 2 -> 6\n 1 -> 4 -> 8 -> 11\n 2 -> 5 -> 6 -> 0 -> 3\n 3 -> 10 -> 6 -> 2\n 4 -> 1 -> 8\n 5 -> 0 -> 10 -> 2\n 6 -> 2 -> 3 -> 0\n 7 -> 8 -> 11\n 8 -> 1 -> 11 -> 7 -> 4\n 9 -> \n 10 -> 5 -> 3\n 11 -> 8 -> 7 -> 1","support_files":[],"metadata":{"number":"4.2.2","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Develop a test client for Digraph.","answer":"4.1.6\n\nThe edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.\n\nadj[]\n 0 -> 1 -> 3 (the original was 0 -> 3 -> 1)\n 1 -> 2 -> 0\n 2 -> 3 -> 1\n 3 -> 0 -> 2","support_files":[],"metadata":{"number":"4.2.6","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Write a method that checks whether or not a given permutation of a DAG’s vertices is a topological order of that DAG.","answer":"4.1.9\n marked[] adj[]\ndfs (0) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (5) 0 T 0 5 2 6\n check 0 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (10) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (3) 0 T 0 5 2 6\n check 10 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (6) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (2) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n check 6 2 T 2 5 6 0 3\n check 0 3 T 3 10 6 2 \n check 3 4 4 1 8 \n 2 done 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\n\nedgeTo[] tree\n \n 0\n 5\n 10\n 3\n 6\n 2","support_files":[],"metadata":{"number":"4.2.9","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Given a DAG, does there exist a topological order that cannot result from applying a DFS-based algorithm, no matter in what order the vertices adjacent to each vertex are chosen? Prove your answer.","answer":"4.1.10\n\nEvery connected graph has a vertex whose removal (including all incident edges) will not disconnect the graph.\n\nProof by contradiction:\nIf the graph has a node of degree one, removing it gives a connected graph.\nExample: o - o\n\nOtherwise, every path in the graph belongs to a cycle. To see this, start with any path, then notice that the terminal nodes of this path must be connected to other nodes that are not in the path, so we add them to the path to make a new path. Since the graph is connected, continuing this process it is possible to see that in the end all the nodes from the graph will be in the path.\n\nIf among all those paths there is no path from which one can remove a node without disconnecting the graph, then all those paths are bridges. In this case, they do not belong to a cycle, which is a contradiction (assuming the graph is finite).\n\nBased on: https://math.stackexchange.com/questions/891325/proof-verification-a-connected-graph-always-has-a-vertex-that-is-not-a-cut-vert","support_files":[],"metadata":{"number":"4.2.10","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Describe a family of sparse digraphs whose number of directed cycles grows exponentially in the number of vertices.","answer":"4.1.11\n\nTree represented by edgeTo[] after call to bfs(G, 0):\n\n 0\n 5 2 6\n 10 3","support_files":[],"metadata":{"number":"4.2.11","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"How many edges are there in the transitive closure of a digraph that is a simple directed path with V vertices and V–1 edges?","answer":"4.1.12\n\nWhen neither v nor w are at the root, the BFS tree tell us that if they are on the same branch, there is a path between v and w of distance equal to the number of edges between them in the branch.\nIf they are not on the same branch, there is a path between v and w of distance Dv + Dw, where Dv is the distance from the root to vertex v and Dw is the distance from the root to vertex w.","support_files":[],"metadata":{"number":"4.2.12","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Prove that the strong components in G^R are the same as in G.","answer":"4.1.14\n\nIf we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.\nThis can be seen in the following graph:\n\n 0 (source)\n / \\\n1 - 2\n| |\n4 - 3\n\nIf the edge 0 - 2 is inserted before the edge 0 - 1:\nUsing a stack, the distance from 0 to 4 will be 3.\nUsing a queue, the distance from 0 to 4 will be 2.\n\nIf the edge 0 - 1 is inserted before the edge 0 - 2:\nUsing a stack, the distance from 0 to 3 will be 3.\nUsing a queue, the distance from 0 to 3 will be 2.\n\nThanks to lemonadeseason (https://github.com/lemonadeseason) for correcting the example in this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/24","support_files":[],"metadata":{"number":"4.2.14","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Exercise","code_execution":false}} {"question":"Topological sort and BFS. Explain why the following algorithm does not necessarily produce a topological order: Run BFS, and label the vertices by increasing distance to their respective source.","answer":"4.1.19\n count marked[] id[]\n 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) 0 T 0\n dfs(5) 0 T T 0 0\n check 0\n dfs(10) 0 T T T 0 0 0\n check 5\n dfs(3) 0 T T T T 0 0 0 0\n check 10\n dfs(6) 0 T T T T T 0 0 0 0 0\n dfs(2) 0 T T T T T T 0 0 0 0 0 0\n check 5\n check 6\n check 0\n check 3\n 2 done\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\ndfs(1) 1 T T T T T T T 0 1 0 0 0 0 0\n dfs(4) 1 T T T T T T T T 0 1 0 0 1 0 0 0\n check 1\n dfs(8) 1 T T T T T T T T T 0 1 0 0 1 0 0 1 0\n check 1\n dfs(11) 1 T T T T T T T T T T 0 1 0 0 1 0 0 1 0 1\n check 8\n dfs(7) 1 T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 0 1\n check 8\n check 11\n 7 done\n check 1\n 11 done\n check 7\n check 4\n 8 done\n 4 done\n check 8\n check 11\n1 done\ndfs(9) 2 T T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 2 0 1\n9 done","support_files":[],"metadata":{"number":"4.2.19","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Directed Eulerian cycle. An Eulerian cycle is a directed cycle that contains each edge exactly once. Write a graph client Euler that finds an Eulerian cycle or reports that no such tour exists. Hint: Prove that a digraph G has a directed Eulerian cycle if and only if G is connected and each vertex has its indegree equal to its outdegree.","answer":"4.1.20\n Has Cycle? marked[] \n F 0 1 2 3 4 5 6 7 8 9 10 11 \ndfs(0) T \n dfs(5) T T \n check 0 F\n dfs(10) T T T \n check 5 F\n dfs(3) T T T T \n check 10 F\n dfs(6) T T T T T \n dfs(2) T T T T T T \n check 5 T (cycle found here)\n check 6 T\n check 0 T\n check 3 T\n 2 done\n check 3 T\n check 0 T\n 6 done\n check 2 T\n 3 done\n 10 done\n check 2 T\n 5 done\n check 2 T\n check 6 T\n0 done\ndfs(1) T T T T T T T \n dfs(4) T T T T T T T T \n check 1 T\n dfs(8) T T T T T T T T T \n check 1 T\n dfs(11) T T T T T T T T T T \n check 8 T\n dfs(7) T T T T T T T T T T T \n check 8 T\n check 11 T\n 7 done\n check 1 T\n 11 done\n check 7 T\n check 4 T\n 8 done\n 4 done\n check 8 T\n check 11 T\n1 done\ndfs(9) T T T T T T T T T T T T\n9 done\n\nThe order of growth of the running time of the Cycle constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] array takes time proportional to V.","support_files":[],"metadata":{"number":"4.2.20","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"LCA of a DAG. Given a DAG and two vertices v and w, find the lowest common ancestor (LCA) of v and w. The LCA of v and w is an ancestor of v and w that has no descendants that are also ancestors of v and w. Computing the LCA is useful in multiple inheritance in programming languages, analysis of genealogical data (find degree of inbreeding in a pedigree graph), and other applications. Hint: Define the height of a vertex v in a DAG to be the length of the longest path from a root to v. Among vertices that are ancestors of both v and w, the one with the greatest height is an LCA of v and w.","answer":"4.1.21\n Is 2-colorable? marked[] color[]\n T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) T F F F F F F F F F F F F\n dfs(5) T T F F F F F T F F F F F F\n check 0 T\n dfs(10) T T T F F F F F T F F F F F F\n check 5 T\n dfs(3) T T T T F F F T F T F F F F F F\n check 10 T\n dfs(6) T T T T T F F F T F T F F F F F F\n dfs(2) T T T T T T F F T T F T F F F F F F\n check 5 F\n check 6 F\n check 0 F\n check 3 F\n 2 done\n check 3 F\n check 0 F\n 6 done\n check 2 F\n 3 done\n 10 done\n check 2 F\n 5 done\n check 2 F\n check 6 F\n0 done\ndfs(1) T T T T T T T F F T T F T F F F F F F\n dfs(4) T T T T T T T T F F T T T T F F F F F F\n check 1 F\n dfs(8) T T T T T T T T T F F T T F T F F F F F F\n check 1 F\n dfs(11) T T T T T T T T T T F F T T F T F F F F F T\n check 8 F\n dfs(7) T T T T T T T T T T T F F T T F T F F F F F F\n check 8 F\n check 11 F\n 7 done\n check 1 F\n 11 done\n check 7 F\n check 4 F\n 8 done\n 4 done\n check 8 F\n check 11 F\n1 done\ndfs(9) T T T T T T T T T T T T F F T T F T F F F F F F\n9 done\n\nThe order of growth of the running time of the TwoColor constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] and color[] arrays takes time proportional to V.","support_files":[],"metadata":{"number":"4.2.21","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Hamiltonian path in DAGs. Given a DAG, design a linear-time algorithm to determine whether there is a directed path that visits each vertex exactly once.\nAnswer: Compute a topological sort and check if there is an edge between each consecutive pair of vertices in the topological order.","answer":"4.1.24\n\nNumber of connected components: 33\nSize of the largest component: 118774\nNumber of components of size less than 10: 5\nDoes the largest component contain Kevin Bacon: Yes\n\nEccentricity, diameter, radius, center and girth:\n\nThe strategy for computing the eccentricity, diameter, radius, center and girth of the largest component was the following:\nThe algorithm required for these exact computations has complexity of O(V * E) (running breadth-first search from all vertices). V is ~= 10^5, which means the algorithm required for these exact computation has complexity ~= 10^10.\n\nIn order to reduce the complexity of the computations (and to be able to compute them), domain knowledge was used to compute approximate results.\nBased on the Kevin Bacon game, we know that Kevin Bacon has been on several movies and that he is closely connected to most of the actors and actresses in the graph. Therefore, he has a high probability of being the center of the graph.\n\nUsing Kevin Bacon as the center, we compute his vertex eccentricity to get the graph radius.\nA breadth-first search using Kevin Bacon as the source computes the vertices that are furthest from the center. Computing the eccentricities of these vertices we can find the diameter of the graph.\n\nThe eccentricities of the center and of the vertices furthest from it are shown in the results. The range of the eccentricities is [10, 18]. Computing the eccentricities of all vertices would bring us back to the original problem of =~ 10^10 operations.\n\nFinally, for the girth, we know that there is a very high probability that two actors have worked together on two different movies. This gives a girth of 4, which is the minimum girth possible for the movies graph:\nActor -- Movie -- Actor\n \\ /\n \\ Movie /\nTo validate this theory we run the algorithm to compute the girth of the graph but stop once we find a cycle of length 4, since it is the shortest cycle possible.\n\n\nEccentricities of Kevin Bacon and of vertices furthest from the center in the largest component:\nEccentricity of vertex 22970: 16\nEccentricity of vertex 22971: 16\nEccentricity of vertex 22972: 16\nEccentricity of vertex 22973: 16\nEccentricity of vertex 22974: 16\nEccentricity of vertex 22976: 16\nEccentricity of vertex 22977: 16\nEccentricity of vertex 22978: 16\nEccentricity of vertex 22979: 16\nEccentricity of vertex 22980: 16\nEccentricity of vertex 51437: 18\nEccentricity of vertex 51438: 18\nEccentricity of vertex 51439: 18\nEccentricity of vertex 51440: 18\nEccentricity of vertex 51441: 18\nEccentricity of vertex 51442: 18\nEccentricity of vertex 51443: 18\nEccentricity of vertex 51444: 18\nEccentricity of vertex 51445: 18\nEccentricity of vertex 51446: 18\nEccentricity of vertex 51447: 18\nEccentricity of vertex 51448: 18\nEccentricity of vertex 51449: 18\nEccentricity of vertex 51450: 18\nEccentricity of vertex 51451: 18\nEccentricity of vertex 51452: 18\nEccentricity of vertex 51453: 18\nEccentricity of vertex 51454: 18\nEccentricity of vertex 51455: 18\nEccentricity of vertex 51456: 18\nEccentricity of vertex 51457: 18\nEccentricity of vertex 51458: 18\nEccentricity of vertex 51459: 18\nEccentricity of vertex 51460: 18\nEccentricity of vertex 51461: 18\nEccentricity of vertex 51462: 18\nEccentricity of vertex 51463: 18\nEccentricity of vertex 51464: 18\nEccentricity of vertex 51465: 18\nEccentricity of vertex 51466: 18\nEccentricity of vertex 51467: 18\nEccentricity of vertex 51468: 18\nEccentricity of vertex 51469: 18\nEccentricity of vertex 51470: 18\nEccentricity of vertex 51471: 18\nEccentricity of vertex 51472: 18\nEccentricity of vertex 51473: 18\nEccentricity of vertex 51474: 18\nEccentricity of vertex 51475: 18\nEccentricity of vertex 51476: 18\nEccentricity of vertex 51477: 18\nEccentricity of vertex 51478: 18\nEccentricity of vertex 51479: 18\nEccentricity of vertex 51480: 18\nEccentricity of vertex 51481: 18\nEccentricity of vertex 51482: 18\nEccentricity of vertex 51483: 18\nEccentricity of vertex 51484: 18\nEccentricity of vertex 51485: 18\nEccentricity of vertex 51486: 18\nEccentricity of vertex 51487: 18\nEccentricity of vertex 51488: 18\nEccentricity of vertex 51489: 18\nEccentricity of vertex 51490: 18\nEccentricity of vertex 51491: 18\nEccentricity of vertex 51492: 18\nEccentricity of vertex 51493: 18\nEccentricity of vertex 51494: 18\nEccentricity of vertex 51495: 18\nEccentricity of vertex 51496: 18\nEccentricity of vertex 51497: 18\nEccentricity of vertex 51498: 18\nEccentricity of vertex 51499: 18\nEccentricity of vertex 51500: 18\nEccentricity of vertex 51501: 18\nEccentricity of vertex 51502: 18\nEccentricity of vertex 51503: 18\nEccentricity of vertex 51504: 18\nEccentricity of vertex 51505: 18\nEccentricity of vertex 51506: 18\nEccentricity of vertex 51507: 18\nEccentricity of vertex 51508: 18\nEccentricity of vertex 51509: 18\nEccentricity of vertex 51510: 18\nEccentricity of vertex 51511: 18\nEccentricity of vertex 51512: 18\nEccentricity of vertex 51513: 18\nEccentricity of vertex 51514: 18\nEccentricity of vertex 51515: 18\nEccentricity of vertex 51516: 18\nEccentricity of vertex 51517: 18\nEccentricity of vertex 51518: 18\nEccentricity of vertex 51519: 18\nEccentricity of vertex 51520: 18\nEccentricity of vertex 86241: 16\nEccentricity of vertex 86242: 16\nEccentricity of vertex 86243: 16\nEccentricity of vertex 86244: 16\nEccentricity of vertex 86245: 16\nEccentricity of vertex 86246: 16\nEccentricity of vertex 86247: 16\nEccentricity of vertex 86248: 16\nEccentricity of vertex 86249: 16\nEccentricity of vertex 86250: 16\nEccentricity of vertex 86251: 16\nEccentricity of vertex 86252: 16\nEccentricity of vertex 86253: 16\nEccentricity of vertex 86254: 16\nEccentricity of vertex 86255: 16\nEccentricity of vertex 86256: 16\nEccentricity of vertex 86257: 16\nEccentricity of vertex 86258: 16\nEccentricity of vertex 86259: 16\nEccentricity of vertex 118353: 18\nEccentricity of vertex 118354: 18\nEccentricity of vertex 118355: 18\nEccentricity of vertex 118356: 18\nEccentricity of vertex 118357: 18\nEccentricity of vertex 118358: 18\nEccentricity of vertex 118359: 18\nEccentricity of vertex 118360: 18\nEccentricity of vertex 118361: 18\nEccentricity of vertex 118362: 18\nEccentricity of vertex 118363: 18\nEccentricity of vertex 118364: 18\nEccentricity of vertex 9145: 10\n\nDiameter of largest component: 18\nRadius of largest component: 10\nCenter of largest component: 9145\nGirth of largest component: 4","support_files":[],"metadata":{"number":"4.2.24","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Digraph enumeration. Show that the number of different V-vertex digraphs with no parallel edges is 2^(V^2). (How many digraphs are there that contain V vertices and E edges?) Then compute an upper bound on the percentage of 20-vertex digraphs that could ever be examined by any computer, under the assumptions that every electron in the universe examines a digraph every nanosecond, that the universe has fewer than 10^80 electrons, and that the age of the universe will be less than 10^20 years.","answer":"4.1.27\n\nInteger\n* object overhead -> 16 bytes\n* int value -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 4 + 4 = 24 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* Integer (item) -> 24N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 24N = 64N + 32 bytes\n\nGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 64E + 32 bytes -> There are V Bags and in total, they have 2E nodes -> 128E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 128E + 32V = 128E + 40V + 56 bytes","support_files":[],"metadata":{"number":"4.2.27","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"DAG enumeration. Give a formula for the number of V-vertex DAGs with E edges.","answer":"4.1.28\n\nNon-isomorphic graphs:\n\nThere are 2 non-isomorphic graphs with 2 vertices:\no o\n\no-o\n\nThere are 4 non-isomorphic graphs with 3 vertices:\n o\no o\n\n o\no-o\n\no-o-o\n\n o\n/ \\\no-o\n\nThere are 11 non-isomorphic graphs with 4 vertices:\no o o o\n\no-o o o\n\no-o-o o\n\no-o-o-o\n\no-o o-o\n\n o\n |\n o\n / \\\no o\n\n o\n / \\\no---o o\n\no-o\n| |\no-o\n\n o\n | \n o\n / \\\no---o\n\n o\n / \\\no---o\n \\ /\n o\n\n o\n /|\\\n / o \\\n/ / \\ \\\no------o\n\nThere are 34 non-isomorphic graphs with 5 vertices:\n o\no o\n o o\n\n o\no o\n o-o\n\n o\no o\n /\n o-o\n\n o\no o\n \\ /\n o o\n\n o\n / | \\\no o o \n o\n\n o\n / \\\no o \n o-o\n\n o\n / \\\no o \n \\\n o o\n\n o\n / \\\no----o\n o o\n\n o\n /|\\\\\no o oo\n\no-o\n| |\no-o o\n\no\n|\no-o\n| |\no o\n\n o\n |\n o\n / \\\no---o o\n\no-o-o-o-o\n\n o o\n /| |\no | |\n \\| |\n o o\n\no--o\n| |\no--o\n|\no\n\no o\n| |\no---o\n \\ /\n o\n\n o--o\n \\/\no--o--o\n\n o\n / \\\no o \n \\ /\n o-o\n\n o (This is a complete graph, where all vertices have degree = 4)\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o---o\n\n o\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|/\no---o\n\no---o\n|\\ /|\n| o |\n|/ \\|\no---o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|\no---o\n\n o\n // \\\no-o o\n \\/\n o\n\no-o-o-o\n \\| | /\n o\n\n o\n /\\\n / \\\n / \\\no------o\n\\ \\ / /\n \\ /\\ /\n o o\n\no---o\n| X | o\no---o\n\no o\n|\\ /|\n| o |\n|/ \\|\no o\n\n o\n /|\\\no--o | o\n \\|/\n o\n\n o\n |\n o\n /|\\\no | o\n \\|/\n o\n\n o\n / \\\no---o\n| |\no---o\n\no---o\n| /|\n| o |\n|/ |\no---o\n\n o\n |\n o\n |\n o\n / \\\no---o\n\no---o\n| \\ |\no---o o\n\nBased on: http://www.graphclasses.org/smallgraphs.html","support_files":[],"metadata":{"number":"4.2.28","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Queue-based topological sort. Develop a topological sort implementation that maintains a vertex-indexed array that keeps track of the indegree of each vertex. Initialize the array and a queue of sources in a single pass through all the edges, as in EXERCISE 4.2.7. Then, perform the following operations until the source queue is empty:\n■ Remove a source from the queue and label it.\n■ Decrement the entries in the indegree array corresponding to the destination vertex of each of the removed vertex’s edges.\n■ If decrementing any entry causes it to become 0, insert the corresponding vertex onto the source queue.","answer":"4.1.30 - Eulerian and Hamiltonian cycles\n\nAn Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.\nA Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visited twice).\n\nAccording to Euler theorems a graph has an Eulerian cycle/circuit if and only if it does not have any vertices of odd degree.\n\nFirst graph:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9).\nIt has a Hamiltonian cycle: 1-4 4-8 8-7 7-6 6-9 9-5 5-2 2-0 0-3 3-1\n\nSecond graph:\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n\nIt has an Eulerian cycle (all the vertices have even degrees):\n0-3 3-0 0-2 2-5 5-9 9-6 6-5 5-8 8-8 8-4 4-7 7-6 6-3 3-1 1-0\nThere is no Hamiltonian cycle.\n\nThird graph:\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 4-8 8-7 7-6 6-9 9-5 5-2 2-1 1-3 3-0 0-4\n\nFourth graph:\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 0-5 5-4 4-1 1-6 6-3 3-7 7-9 9-8 8-2 2-0","support_files":[],"metadata":{"number":"4.2.30","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Euclidean digraphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanDigraph for graphs whose vertices are points in the plane, so that you can work with graphical representations.","answer":"4.1.31 - Graph enumeration\n\nIf we were considering graphs with no self-loops:\n\nThere are (V) ways to choose a set {u, v} of two vertices. From this set there are E ways to choose the vertices to connect.\n (2)\nSo there are ((V)) = (V! / 2! * (V - 2)!)! / E! * ((V! / 2! * (V - 2)!) - E)!\n ((2))\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges and no self-loops).\n\nSince we are also considering graphs with self-loops, there are (V) * 2^V ways to choose a set {u, v} of two vertices in which\n (2)\nvertices may or may not have a self-loop.\n\nSo there are ((V) * 2^V) = ((V! / 2! * (V - 2)!) * 2^V)! / E! * (((V! / 2! * (V - 2)!) * 2^V) - E)!\n ((2) )\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges).\n\nReference:\nHandbook of Discrete and Combinatorial Mathematics by Kenneth H. Rosen, page 580\nhttps://math.stackexchange.com/questions/1072726/counting-simple-connected-labeled-graphs-with-n-vertices-and-k-edges\nhttps://math.stackexchange.com/questions/128439/how-to-determine-the-number-of-directed-undirected-graphs","support_files":[],"metadata":{"number":"4.2.31","chapter":4,"chapter_title":"Graphs","section":4.2,"section_title":"Directed Graphs","type":"Creative Problem","code_execution":false}} {"question":"Prove that you can rescale the weights by adding a positive constant to all of them or by multiplying them all by a positive constant without affecting the MST.","answer":"4.1.1\n\nThe maximum number of edges in a graph with V vertices and no parallel edges is V * (V - 1) / 2.\nSince we do not have self-loops or parallel edges, each vertex can connect to V - 1 other vertices. In an undirected graph vertex v connected to vertex w is the same as vertex w connected to vertex v, so we divide the result by 2.\n\nExample:\no - o\n| X |\no — o\n\nThe minimum number of edges in a graph with V vertices, none of which are isolated (have degree 0) is V - 1.\nExample:\no — o — o","support_files":[],"metadata":{"number":"4.3.1","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Draw all of the MSTs of the graph depicted at right (all edge weights are equal).","answer":"4.1.2\n\nadj[]\n 0 -> 5 -> 2 -> 6\n 1 -> 4 -> 8 -> 11\n 2 -> 5 -> 6 -> 0 -> 3\n 3 -> 10 -> 6 -> 2\n 4 -> 1 -> 8\n 5 -> 0 -> 10 -> 2\n 6 -> 2 -> 3 -> 0\n 7 -> 8 -> 11\n 8 -> 1 -> 11 -> 7 -> 4\n 9 -> \n 10 -> 5 -> 3\n 11 -> 8 -> 7 -> 1","support_files":[],"metadata":{"number":"4.3.2","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Give the MST of the weighted graph obtained by deleting vertex 7 from tinyEWG.txt (see page 604).","answer":"4.1.6\n\nThe edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.\n\nadj[]\n 0 -> 1 -> 3 (the original was 0 -> 3 -> 1)\n 1 -> 2 -> 0\n 2 -> 3 -> 1\n 3 -> 0 -> 2","support_files":[],"metadata":{"number":"4.3.6","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Implement the constructor for EdgeWeightedGraph that reads a graph from the input stream, by suitably modifying the constructor from Graph (see page 526).","answer":"4.1.9\n marked[] adj[]\ndfs (0) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (5) 0 T 0 5 2 6\n check 0 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (10) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (3) 0 T 0 5 2 6\n check 10 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (6) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (2) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n check 6 2 T 2 5 6 0 3\n check 0 3 T 3 10 6 2 \n check 3 4 4 1 8 \n 2 done 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\n\nedgeTo[] tree\n \n 0\n 5\n 10\n 3\n 6\n 2","support_files":[],"metadata":{"number":"4.3.9","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Develop an EdgeWeightedGraph implementation for dense graphs that uses an adjacency-matrix (two-dimensional array of weights) representation. Disallow parallel edges.","answer":"4.1.10\n\nEvery connected graph has a vertex whose removal (including all incident edges) will not disconnect the graph.\n\nProof by contradiction:\nIf the graph has a node of degree one, removing it gives a connected graph.\nExample: o - o\n\nOtherwise, every path in the graph belongs to a cycle. To see this, start with any path, then notice that the terminal nodes of this path must be connected to other nodes that are not in the path, so we add them to the path to make a new path. Since the graph is connected, continuing this process it is possible to see that in the end all the nodes from the graph will be in the path.\n\nIf among all those paths there is no path from which one can remove a node without disconnecting the graph, then all those paths are bridges. In this case, they do not belong to a cycle, which is a contradiction (assuming the graph is finite).\n\nBased on: https://math.stackexchange.com/questions/891325/proof-verification-a-connected-graph-always-has-a-vertex-that-is-not-a-cut-vert","support_files":[],"metadata":{"number":"4.3.10","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Determine the amount of memory used by EdgeWeightedGraph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4.","answer":"4.1.11\n\nTree represented by edgeTo[] after call to bfs(G, 0):\n\n 0\n 5 2 6\n 10 3","support_files":[],"metadata":{"number":"4.3.11","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Suppose that a graph has distinct edge weights. Does its shortest edge have to belong to the MST? Can its longest edge belong to the MST? Does a min-weight edge on every cycle have to belong to the MST? Prove your answer to each question or give a counterexample.","answer":"4.1.12\n\nWhen neither v nor w are at the root, the BFS tree tell us that if they are on the same branch, there is a path between v and w of distance equal to the number of edges between them in the branch.\nIf they are not on the same branch, there is a path between v and w of distance Dv + Dw, where Dv is the distance from the root to vertex v and Dw is the distance from the root to vertex w.","support_files":[],"metadata":{"number":"4.3.12","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Given an MST for an edge-weighted graph G, suppose that an edge in G that does not disconnect G is deleted. Describe how to find an MST of the new graph in time proportional to E.","answer":"4.1.14\n\nIf we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.\nThis can be seen in the following graph:\n\n 0 (source)\n / \\\n1 - 2\n| |\n4 - 3\n\nIf the edge 0 - 2 is inserted before the edge 0 - 1:\nUsing a stack, the distance from 0 to 4 will be 3.\nUsing a queue, the distance from 0 to 4 will be 2.\n\nIf the edge 0 - 1 is inserted before the edge 0 - 2:\nUsing a stack, the distance from 0 to 3 will be 3.\nUsing a queue, the distance from 0 to 3 will be 2.\n\nThanks to lemonadeseason (https://github.com/lemonadeseason) for correcting the example in this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/24","support_files":[],"metadata":{"number":"4.3.14","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Suppose that you use a priority-queue implementation that maintains a sorted list. What would be the order of growth of the worst-case running time for Prim’s algorithm and for Kruskal’s algorithm for graphs with V vertices and E edges? When would this method be appropriate, if ever? Defend your answer.","answer":"4.1.19\n count marked[] id[]\n 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) 0 T 0\n dfs(5) 0 T T 0 0\n check 0\n dfs(10) 0 T T T 0 0 0\n check 5\n dfs(3) 0 T T T T 0 0 0 0\n check 10\n dfs(6) 0 T T T T T 0 0 0 0 0\n dfs(2) 0 T T T T T T 0 0 0 0 0 0\n check 5\n check 6\n check 0\n check 3\n 2 done\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\ndfs(1) 1 T T T T T T T 0 1 0 0 0 0 0\n dfs(4) 1 T T T T T T T T 0 1 0 0 1 0 0 0\n check 1\n dfs(8) 1 T T T T T T T T T 0 1 0 0 1 0 0 1 0\n check 1\n dfs(11) 1 T T T T T T T T T T 0 1 0 0 1 0 0 1 0 1\n check 8\n dfs(7) 1 T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 0 1\n check 8\n check 11\n 7 done\n check 1\n 11 done\n check 7\n check 4\n 8 done\n 4 done\n check 8\n check 11\n1 done\ndfs(9) 2 T T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 2 0 1\n9 done","support_files":[],"metadata":{"number":"4.3.19","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"True or false: At any point during the execution of Kruskal’s algorithm, each vertex is closer to some vertex in its subtree than to any vertex not in its subtree. Prove your answer.","answer":"4.1.20\n Has Cycle? marked[] \n F 0 1 2 3 4 5 6 7 8 9 10 11 \ndfs(0) T \n dfs(5) T T \n check 0 F\n dfs(10) T T T \n check 5 F\n dfs(3) T T T T \n check 10 F\n dfs(6) T T T T T \n dfs(2) T T T T T T \n check 5 T (cycle found here)\n check 6 T\n check 0 T\n check 3 T\n 2 done\n check 3 T\n check 0 T\n 6 done\n check 2 T\n 3 done\n 10 done\n check 2 T\n 5 done\n check 2 T\n check 6 T\n0 done\ndfs(1) T T T T T T T \n dfs(4) T T T T T T T T \n check 1 T\n dfs(8) T T T T T T T T T \n check 1 T\n dfs(11) T T T T T T T T T T \n check 8 T\n dfs(7) T T T T T T T T T T T \n check 8 T\n check 11 T\n 7 done\n check 1 T\n 11 done\n check 7 T\n check 4 T\n 8 done\n 4 done\n check 8 T\n check 11 T\n1 done\ndfs(9) T T T T T T T T T T T T\n9 done\n\nThe order of growth of the running time of the Cycle constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] array takes time proportional to V.","support_files":[],"metadata":{"number":"4.3.20","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Provide an implementation of edges() for PrimMST (page 622).\nSolution:\npublic Iterable edges()\n{\n Bag mst = new Bag();\n for (int v = 1; v < edgeTo.length; v++)\n mst.add(edgeTo[v]);\n return mst;\n}","answer":"4.1.21\n Is 2-colorable? marked[] color[]\n T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) T F F F F F F F F F F F F\n dfs(5) T T F F F F F T F F F F F F\n check 0 T\n dfs(10) T T T F F F F F T F F F F F F\n check 5 T\n dfs(3) T T T T F F F T F T F F F F F F\n check 10 T\n dfs(6) T T T T T F F F T F T F F F F F F\n dfs(2) T T T T T T F F T T F T F F F F F F\n check 5 F\n check 6 F\n check 0 F\n check 3 F\n 2 done\n check 3 F\n check 0 F\n 6 done\n check 2 F\n 3 done\n 10 done\n check 2 F\n 5 done\n check 2 F\n check 6 F\n0 done\ndfs(1) T T T T T T T F F T T F T F F F F F F\n dfs(4) T T T T T T T T F F T T T T F F F F F F\n check 1 F\n dfs(8) T T T T T T T T T F F T T F T F F F F F F\n check 1 F\n dfs(11) T T T T T T T T T T F F T T F T F F F F F T\n check 8 F\n dfs(7) T T T T T T T T T T T F F T T F T F F F F F F\n check 8 F\n check 11 F\n 7 done\n check 1 F\n 11 done\n check 7 F\n check 4 F\n 8 done\n 4 done\n check 8 F\n check 11 F\n1 done\ndfs(9) T T T T T T T T T T T T F F T T F T F F F F F F\n9 done\n\nThe order of growth of the running time of the TwoColor constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] and color[] arrays takes time proportional to V.","support_files":[],"metadata":{"number":"4.3.21","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Exercise","code_execution":false}} {"question":"Reverse-delete algorithm. Develop an implementation that computes the MST as follows: Start with a graph containing all of the edges. Then repeatedly go through the edges in decreasing order of weight. For each edge, check if deleting that edge will disconnect the graph; if not, delete it. Prove that this algorithm computes the MST. What is the order of growth of the number of edge-weight compares performed by your implementation?","answer":"4.1.24\n\nNumber of connected components: 33\nSize of the largest component: 118774\nNumber of components of size less than 10: 5\nDoes the largest component contain Kevin Bacon: Yes\n\nEccentricity, diameter, radius, center and girth:\n\nThe strategy for computing the eccentricity, diameter, radius, center and girth of the largest component was the following:\nThe algorithm required for these exact computations has complexity of O(V * E) (running breadth-first search from all vertices). V is ~= 10^5, which means the algorithm required for these exact computation has complexity ~= 10^10.\n\nIn order to reduce the complexity of the computations (and to be able to compute them), domain knowledge was used to compute approximate results.\nBased on the Kevin Bacon game, we know that Kevin Bacon has been on several movies and that he is closely connected to most of the actors and actresses in the graph. Therefore, he has a high probability of being the center of the graph.\n\nUsing Kevin Bacon as the center, we compute his vertex eccentricity to get the graph radius.\nA breadth-first search using Kevin Bacon as the source computes the vertices that are furthest from the center. Computing the eccentricities of these vertices we can find the diameter of the graph.\n\nThe eccentricities of the center and of the vertices furthest from it are shown in the results. The range of the eccentricities is [10, 18]. Computing the eccentricities of all vertices would bring us back to the original problem of =~ 10^10 operations.\n\nFinally, for the girth, we know that there is a very high probability that two actors have worked together on two different movies. This gives a girth of 4, which is the minimum girth possible for the movies graph:\nActor -- Movie -- Actor\n \\ /\n \\ Movie /\nTo validate this theory we run the algorithm to compute the girth of the graph but stop once we find a cycle of length 4, since it is the shortest cycle possible.\n\n\nEccentricities of Kevin Bacon and of vertices furthest from the center in the largest component:\nEccentricity of vertex 22970: 16\nEccentricity of vertex 22971: 16\nEccentricity of vertex 22972: 16\nEccentricity of vertex 22973: 16\nEccentricity of vertex 22974: 16\nEccentricity of vertex 22976: 16\nEccentricity of vertex 22977: 16\nEccentricity of vertex 22978: 16\nEccentricity of vertex 22979: 16\nEccentricity of vertex 22980: 16\nEccentricity of vertex 51437: 18\nEccentricity of vertex 51438: 18\nEccentricity of vertex 51439: 18\nEccentricity of vertex 51440: 18\nEccentricity of vertex 51441: 18\nEccentricity of vertex 51442: 18\nEccentricity of vertex 51443: 18\nEccentricity of vertex 51444: 18\nEccentricity of vertex 51445: 18\nEccentricity of vertex 51446: 18\nEccentricity of vertex 51447: 18\nEccentricity of vertex 51448: 18\nEccentricity of vertex 51449: 18\nEccentricity of vertex 51450: 18\nEccentricity of vertex 51451: 18\nEccentricity of vertex 51452: 18\nEccentricity of vertex 51453: 18\nEccentricity of vertex 51454: 18\nEccentricity of vertex 51455: 18\nEccentricity of vertex 51456: 18\nEccentricity of vertex 51457: 18\nEccentricity of vertex 51458: 18\nEccentricity of vertex 51459: 18\nEccentricity of vertex 51460: 18\nEccentricity of vertex 51461: 18\nEccentricity of vertex 51462: 18\nEccentricity of vertex 51463: 18\nEccentricity of vertex 51464: 18\nEccentricity of vertex 51465: 18\nEccentricity of vertex 51466: 18\nEccentricity of vertex 51467: 18\nEccentricity of vertex 51468: 18\nEccentricity of vertex 51469: 18\nEccentricity of vertex 51470: 18\nEccentricity of vertex 51471: 18\nEccentricity of vertex 51472: 18\nEccentricity of vertex 51473: 18\nEccentricity of vertex 51474: 18\nEccentricity of vertex 51475: 18\nEccentricity of vertex 51476: 18\nEccentricity of vertex 51477: 18\nEccentricity of vertex 51478: 18\nEccentricity of vertex 51479: 18\nEccentricity of vertex 51480: 18\nEccentricity of vertex 51481: 18\nEccentricity of vertex 51482: 18\nEccentricity of vertex 51483: 18\nEccentricity of vertex 51484: 18\nEccentricity of vertex 51485: 18\nEccentricity of vertex 51486: 18\nEccentricity of vertex 51487: 18\nEccentricity of vertex 51488: 18\nEccentricity of vertex 51489: 18\nEccentricity of vertex 51490: 18\nEccentricity of vertex 51491: 18\nEccentricity of vertex 51492: 18\nEccentricity of vertex 51493: 18\nEccentricity of vertex 51494: 18\nEccentricity of vertex 51495: 18\nEccentricity of vertex 51496: 18\nEccentricity of vertex 51497: 18\nEccentricity of vertex 51498: 18\nEccentricity of vertex 51499: 18\nEccentricity of vertex 51500: 18\nEccentricity of vertex 51501: 18\nEccentricity of vertex 51502: 18\nEccentricity of vertex 51503: 18\nEccentricity of vertex 51504: 18\nEccentricity of vertex 51505: 18\nEccentricity of vertex 51506: 18\nEccentricity of vertex 51507: 18\nEccentricity of vertex 51508: 18\nEccentricity of vertex 51509: 18\nEccentricity of vertex 51510: 18\nEccentricity of vertex 51511: 18\nEccentricity of vertex 51512: 18\nEccentricity of vertex 51513: 18\nEccentricity of vertex 51514: 18\nEccentricity of vertex 51515: 18\nEccentricity of vertex 51516: 18\nEccentricity of vertex 51517: 18\nEccentricity of vertex 51518: 18\nEccentricity of vertex 51519: 18\nEccentricity of vertex 51520: 18\nEccentricity of vertex 86241: 16\nEccentricity of vertex 86242: 16\nEccentricity of vertex 86243: 16\nEccentricity of vertex 86244: 16\nEccentricity of vertex 86245: 16\nEccentricity of vertex 86246: 16\nEccentricity of vertex 86247: 16\nEccentricity of vertex 86248: 16\nEccentricity of vertex 86249: 16\nEccentricity of vertex 86250: 16\nEccentricity of vertex 86251: 16\nEccentricity of vertex 86252: 16\nEccentricity of vertex 86253: 16\nEccentricity of vertex 86254: 16\nEccentricity of vertex 86255: 16\nEccentricity of vertex 86256: 16\nEccentricity of vertex 86257: 16\nEccentricity of vertex 86258: 16\nEccentricity of vertex 86259: 16\nEccentricity of vertex 118353: 18\nEccentricity of vertex 118354: 18\nEccentricity of vertex 118355: 18\nEccentricity of vertex 118356: 18\nEccentricity of vertex 118357: 18\nEccentricity of vertex 118358: 18\nEccentricity of vertex 118359: 18\nEccentricity of vertex 118360: 18\nEccentricity of vertex 118361: 18\nEccentricity of vertex 118362: 18\nEccentricity of vertex 118363: 18\nEccentricity of vertex 118364: 18\nEccentricity of vertex 9145: 10\n\nDiameter of largest component: 18\nRadius of largest component: 10\nCenter of largest component: 9145\nGirth of largest component: 4","support_files":[],"metadata":{"number":"4.3.24","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"Animations. Write a client program that does dynamic graphical animations of MST algorithms. Run your program for mediumEWG.txt to produce images like the figures on page 621 and page 624.","answer":"4.1.27\n\nInteger\n* object overhead -> 16 bytes\n* int value -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 4 + 4 = 24 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* Integer (item) -> 24N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 24N = 64N + 32 bytes\n\nGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 64E + 32 bytes -> There are V Bags and in total, they have 2E nodes -> 128E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 128E + 32V = 128E + 40V + 56 bytes","support_files":[],"metadata":{"number":"4.3.27","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"Space-efficient data structures. Develop an implementation of the lazy version of Prim’s algorithm that saves space by using lower-level data structures for EdgeWeightedGraph and for MinPQ instead of Bag and Edge. Estimate the amount of memory saved as a function of V and E, using the memory-cost model of SECTION 1.4 (see EXERCISE 4.3.11).","answer":"4.1.28\n\nNon-isomorphic graphs:\n\nThere are 2 non-isomorphic graphs with 2 vertices:\no o\n\no-o\n\nThere are 4 non-isomorphic graphs with 3 vertices:\n o\no o\n\n o\no-o\n\no-o-o\n\n o\n/ \\\no-o\n\nThere are 11 non-isomorphic graphs with 4 vertices:\no o o o\n\no-o o o\n\no-o-o o\n\no-o-o-o\n\no-o o-o\n\n o\n |\n o\n / \\\no o\n\n o\n / \\\no---o o\n\no-o\n| |\no-o\n\n o\n | \n o\n / \\\no---o\n\n o\n / \\\no---o\n \\ /\n o\n\n o\n /|\\\n / o \\\n/ / \\ \\\no------o\n\nThere are 34 non-isomorphic graphs with 5 vertices:\n o\no o\n o o\n\n o\no o\n o-o\n\n o\no o\n /\n o-o\n\n o\no o\n \\ /\n o o\n\n o\n / | \\\no o o \n o\n\n o\n / \\\no o \n o-o\n\n o\n / \\\no o \n \\\n o o\n\n o\n / \\\no----o\n o o\n\n o\n /|\\\\\no o oo\n\no-o\n| |\no-o o\n\no\n|\no-o\n| |\no o\n\n o\n |\n o\n / \\\no---o o\n\no-o-o-o-o\n\n o o\n /| |\no | |\n \\| |\n o o\n\no--o\n| |\no--o\n|\no\n\no o\n| |\no---o\n \\ /\n o\n\n o--o\n \\/\no--o--o\n\n o\n / \\\no o \n \\ /\n o-o\n\n o (This is a complete graph, where all vertices have degree = 4)\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o---o\n\n o\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|/\no---o\n\no---o\n|\\ /|\n| o |\n|/ \\|\no---o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|\no---o\n\n o\n // \\\no-o o\n \\/\n o\n\no-o-o-o\n \\| | /\n o\n\n o\n /\\\n / \\\n / \\\no------o\n\\ \\ / /\n \\ /\\ /\n o o\n\no---o\n| X | o\no---o\n\no o\n|\\ /|\n| o |\n|/ \\|\no o\n\n o\n /|\\\no--o | o\n \\|/\n o\n\n o\n |\n o\n /|\\\no | o\n \\|/\n o\n\n o\n / \\\no---o\n| |\no---o\n\no---o\n| /|\n| o |\n|/ |\no---o\n\n o\n |\n o\n |\n o\n / \\\no---o\n\no---o\n| \\ |\no---o o\n\nBased on: http://www.graphclasses.org/smallgraphs.html","support_files":[],"metadata":{"number":"4.3.28","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"Euclidean weighted graphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanEdgeWeightedGraph for graphs whose vertices are points in the plane, so that you can work with graphical representations.","answer":"4.1.30 - Eulerian and Hamiltonian cycles\n\nAn Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.\nA Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visited twice).\n\nAccording to Euler theorems a graph has an Eulerian cycle/circuit if and only if it does not have any vertices of odd degree.\n\nFirst graph:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9).\nIt has a Hamiltonian cycle: 1-4 4-8 8-7 7-6 6-9 9-5 5-2 2-0 0-3 3-1\n\nSecond graph:\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n\nIt has an Eulerian cycle (all the vertices have even degrees):\n0-3 3-0 0-2 2-5 5-9 9-6 6-5 5-8 8-8 8-4 4-7 7-6 6-3 3-1 1-0\nThere is no Hamiltonian cycle.\n\nThird graph:\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 4-8 8-7 7-6 6-9 9-5 5-2 2-1 1-3 3-0 0-4\n\nFourth graph:\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 0-5 5-4 4-1 1-6 6-3 3-7 7-9 9-8 8-2 2-0","support_files":[],"metadata":{"number":"4.3.30","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"MST weights. Develop implementations of weight() for LazyPrimMST, PrimMST, and KruskalMST, using a lazy strategy that iterates through the MST edges when the client calls weight().Then develop alternate implementations that use an eager strategy that maintains a running total as the MST is computed.","answer":"4.1.31 - Graph enumeration\n\nIf we were considering graphs with no self-loops:\n\nThere are (V) ways to choose a set {u, v} of two vertices. From this set there are E ways to choose the vertices to connect.\n (2)\nSo there are ((V)) = (V! / 2! * (V - 2)!)! / E! * ((V! / 2! * (V - 2)!) - E)!\n ((2))\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges and no self-loops).\n\nSince we are also considering graphs with self-loops, there are (V) * 2^V ways to choose a set {u, v} of two vertices in which\n (2)\nvertices may or may not have a self-loop.\n\nSo there are ((V) * 2^V) = ((V! / 2! * (V - 2)!) * 2^V)! / E! * (((V! / 2! * (V - 2)!) * 2^V) - E)!\n ((2) )\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges).\n\nReference:\nHandbook of Discrete and Combinatorial Mathematics by Kenneth H. Rosen, page 580\nhttps://math.stackexchange.com/questions/1072726/counting-simple-connected-labeled-graphs-with-n-vertices-and-k-edges\nhttps://math.stackexchange.com/questions/128439/how-to-determine-the-number-of-directed-undirected-graphs","support_files":[],"metadata":{"number":"4.3.31","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"Certification. Write an MST and EdgeWeightedGraph client check() that uses the following cut optimality conditions implied by PROPOSITION J to verify that a proposed set of edges is in fact an MST: A set of edges is an MST if it is a spanning tree and every edge is a minimum-weight edge in the cut defined by removing that edge from the tree. What is the order of growth of the running time of your method?","answer":"4.1.33 - Odd cycles\n\nA graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.\n\nProof:\n1- Proving that a graph with an odd-length cycle cannot be bipartite:\nIf a graph G is bipartite with vertex sets V1 and V2, every step along a walk takes you either from V1 to V2 or from V2 to V1. To end up where you started, therefore, you must take an even number of steps.\n\n2- Proving that a graph with only even-length cycles is bipartite:\nConsider G to be a graph with only even-length cycles. Let v0 be any vertex. For each vertex v in the same component C0 as v0 let d(v) be the length of the shortest path from v0 to v. Color red every vertex in C0 whose distance from v0 is even, and color the other vertices of C0 blue. Do the same for each component of G. Check that if G had any edge between two red vertices or between two blue vertices, it would have an odd cycle. Thus, G is bipartite, the red vertices and the blue vertices being the two parts.\n\nReference: \nhttps://math.stackexchange.com/questions/311665/proof-a-graph-is-bipartite-if-and-only-if-it-contains-no-odd-cycles","support_files":[],"metadata":{"number":"4.3.33","chapter":4,"chapter_title":"Graphs","section":4.3,"section_title":"Minimum Spanning Trees","type":"Creative Problem","code_execution":false}} {"question":"True or false: Adding a constant to every edge weight does not change the solution to the single-source shortest-paths problem.","answer":"4.1.1\n\nThe maximum number of edges in a graph with V vertices and no parallel edges is V * (V - 1) / 2.\nSince we do not have self-loops or parallel edges, each vertex can connect to V - 1 other vertices. In an undirected graph vertex v connected to vertex w is the same as vertex w connected to vertex v, so we divide the result by 2.\n\nExample:\no - o\n| X |\no — o\n\nThe minimum number of edges in a graph with V vertices, none of which are isolated (have degree 0) is V - 1.\nExample:\no — o — o","support_files":[],"metadata":{"number":"4.4.1","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Provide an implementation of toString() for EdgeWeightedDigraph.","answer":"4.1.2\n\nadj[]\n 0 -> 5 -> 2 -> 6\n 1 -> 4 -> 8 -> 11\n 2 -> 5 -> 6 -> 0 -> 3\n 3 -> 10 -> 6 -> 2\n 4 -> 1 -> 8\n 5 -> 0 -> 10 -> 2\n 6 -> 2 -> 3 -> 0\n 7 -> 8 -> 11\n 8 -> 1 -> 11 -> 7 -> 4\n 9 -> \n 10 -> 5 -> 3\n 11 -> 8 -> 7 -> 1","support_files":[],"metadata":{"number":"4.4.2","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Give a trace that shows the process of computing the SPT of the digraph defined in EXERCISE 4.4.5 with the eager version of Dijkstra’s algorithm.","answer":"4.1.6\n\nThe edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.\n\nadj[]\n 0 -> 1 -> 3 (the original was 0 -> 3 -> 1)\n 1 -> 2 -> 0\n 2 -> 3 -> 1\n 3 -> 0 -> 2","support_files":[],"metadata":{"number":"4.4.6","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"The table below, from an old published road map, purports to give the length of the shortest routes connecting the cities. It contains an error. Correct the table. Also, add a table that shows how to achieve the shortest routes.","answer":"4.1.9\n marked[] adj[]\ndfs (0) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (5) 0 T 0 5 2 6\n check 0 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 10 5 3\n 11 11 8 7 1\n\n dfs (10) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n 2 2 5 6 0 3\n 3 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (3) 0 T 0 5 2 6\n check 10 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (6) 0 T 0 5 2 6\n 1 1 4 8 11\n 2 2 5 6 0 3\n 3 T 3 10 6 2 \n 4 4 1 8 \n 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n\n dfs (2) 0 T 0 5 2 6\n check 5 1 1 4 8 11\n check 6 2 T 2 5 6 0 3\n check 0 3 T 3 10 6 2 \n check 3 4 4 1 8 \n 2 done 5 T 5 0 10 2\n 6 T 6 2 3 0\n 7 7 8 11\n 8 8 1 11 7 4\n 9 9 \n 10 T 10 5 3\n 11 11 8 7 1\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\n\nedgeTo[] tree\n \n 0\n 5\n 10\n 3\n 6\n 2","support_files":[],"metadata":{"number":"4.4.9","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Consider the edges in the digraph defined in EXERCISE 4.4.4 to be undirected edges such that each edge corresponds to equal-weight edges in both directions in the edge-weighted digraph. Answer EXERCISE 4.4.6 for this corresponding edge-weighted digraph.","answer":"4.1.10\n\nEvery connected graph has a vertex whose removal (including all incident edges) will not disconnect the graph.\n\nProof by contradiction:\nIf the graph has a node of degree one, removing it gives a connected graph.\nExample: o - o\n\nOtherwise, every path in the graph belongs to a cycle. To see this, start with any path, then notice that the terminal nodes of this path must be connected to other nodes that are not in the path, so we add them to the path to make a new path. Since the graph is connected, continuing this process it is possible to see that in the end all the nodes from the graph will be in the path.\n\nIf among all those paths there is no path from which one can remove a node without disconnecting the graph, then all those paths are bridges. In this case, they do not belong to a cycle, which is a contradiction (assuming the graph is finite).\n\nBased on: https://math.stackexchange.com/questions/891325/proof-verification-a-connected-graph-always-has-a-vertex-that-is-not-a-cut-vert","support_files":[],"metadata":{"number":"4.4.10","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Use the memory-cost model of SECTION 1.4 to determine the amount of memory used by EdgeWeightedDigraph to represent a graph with V vertices and E edges.","answer":"4.1.11\n\nTree represented by edgeTo[] after call to bfs(G, 0):\n\n 0\n 5 2 6\n 10 3","support_files":[],"metadata":{"number":"4.4.11","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Adapt the DirectedCycle and Topological classes from SECTION 4.2 to use the EdgeWeightedDigraph and DirectedEdge APIs of this section, thus implementing EdgeWeightedCycleFinder and EdgeWeightedTopological classes.","answer":"4.1.12\n\nWhen neither v nor w are at the root, the BFS tree tell us that if they are on the same branch, there is a path between v and w of distance equal to the number of edges between them in the branch.\nIf they are not on the same branch, there is a path between v and w of distance Dv + Dw, where Dv is the distance from the root to vertex v and Dw is the distance from the root to vertex w.","support_files":[],"metadata":{"number":"4.4.12","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Show the paths that would be discovered by the two strawman approaches described on page 668 for the example tinyEWDn.txt shown on that page.","answer":"4.1.14\n\nIf we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.\nThis can be seen in the following graph:\n\n 0 (source)\n / \\\n1 - 2\n| |\n4 - 3\n\nIf the edge 0 - 2 is inserted before the edge 0 - 1:\nUsing a stack, the distance from 0 to 4 will be 3.\nUsing a queue, the distance from 0 to 4 will be 2.\n\nIf the edge 0 - 1 is inserted before the edge 0 - 2:\nUsing a stack, the distance from 0 to 3 will be 3.\nUsing a queue, the distance from 0 to 3 will be 2.\n\nThanks to lemonadeseason (https://github.com/lemonadeseason) for correcting the example in this exercise.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/24","support_files":[],"metadata":{"number":"4.4.14","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Find the lowest-weight cycle (best arbitrage opportunity) in the example shown in the text.","answer":"4.1.19\n count marked[] id[]\n 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) 0 T 0\n dfs(5) 0 T T 0 0\n check 0\n dfs(10) 0 T T T 0 0 0\n check 5\n dfs(3) 0 T T T T 0 0 0 0\n check 10\n dfs(6) 0 T T T T T 0 0 0 0 0\n dfs(2) 0 T T T T T T 0 0 0 0 0 0\n check 5\n check 6\n check 0\n check 3\n 2 done\n check 3\n check 0\n 6 done\n check 2\n 3 done\n 10 done\n check 2\n 5 done\n check 2\n check 6\n0 done\ndfs(1) 1 T T T T T T T 0 1 0 0 0 0 0\n dfs(4) 1 T T T T T T T T 0 1 0 0 1 0 0 0\n check 1\n dfs(8) 1 T T T T T T T T T 0 1 0 0 1 0 0 1 0\n check 1\n dfs(11) 1 T T T T T T T T T T 0 1 0 0 1 0 0 1 0 1\n check 8\n dfs(7) 1 T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 0 1\n check 8\n check 11\n 7 done\n check 1\n 11 done\n check 7\n check 4\n 8 done\n 4 done\n check 8\n check 11\n1 done\ndfs(9) 2 T T T T T T T T T T T T 0 1 0 0 1 0 0 1 1 2 0 1\n9 done","support_files":[],"metadata":{"number":"4.4.19","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Find a currency-conversion table online or in a newspaper. Use it to build an arbitrage table. Note: Avoid tables that are derived (calculated) from a few values and that therefore do not give sufficiently accurate conversion information to be interesting. Extra credit: Make a killing in the money-exchange market!","answer":"4.1.20\n Has Cycle? marked[] \n F 0 1 2 3 4 5 6 7 8 9 10 11 \ndfs(0) T \n dfs(5) T T \n check 0 F\n dfs(10) T T T \n check 5 F\n dfs(3) T T T T \n check 10 F\n dfs(6) T T T T T \n dfs(2) T T T T T T \n check 5 T (cycle found here)\n check 6 T\n check 0 T\n check 3 T\n 2 done\n check 3 T\n check 0 T\n 6 done\n check 2 T\n 3 done\n 10 done\n check 2 T\n 5 done\n check 2 T\n check 6 T\n0 done\ndfs(1) T T T T T T T \n dfs(4) T T T T T T T T \n check 1 T\n dfs(8) T T T T T T T T T \n check 1 T\n dfs(11) T T T T T T T T T T \n check 8 T\n dfs(7) T T T T T T T T T T T \n check 8 T\n check 11 T\n 7 done\n check 1 T\n 11 done\n check 7 T\n check 4 T\n 8 done\n 4 done\n check 8 T\n check 11 T\n1 done\ndfs(9) T T T T T T T T T T T T\n9 done\n\nThe order of growth of the running time of the Cycle constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] array takes time proportional to V.","support_files":[],"metadata":{"number":"4.4.20","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Show, in the style of the trace in the text, the process of computing the SPT with the Bellman-Ford algorithm for the edge-weighted digraph of EXERCISE 4.4.5.","answer":"4.1.21\n Is 2-colorable? marked[] color[]\n T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11\ndfs(0) T F F F F F F F F F F F F\n dfs(5) T T F F F F F T F F F F F F\n check 0 T\n dfs(10) T T T F F F F F T F F F F F F\n check 5 T\n dfs(3) T T T T F F F T F T F F F F F F\n check 10 T\n dfs(6) T T T T T F F F T F T F F F F F F\n dfs(2) T T T T T T F F T T F T F F F F F F\n check 5 F\n check 6 F\n check 0 F\n check 3 F\n 2 done\n check 3 F\n check 0 F\n 6 done\n check 2 F\n 3 done\n 10 done\n check 2 F\n 5 done\n check 2 F\n check 6 F\n0 done\ndfs(1) T T T T T T T F F T T F T F F F F F F\n dfs(4) T T T T T T T T F F T T T T F F F F F F\n check 1 F\n dfs(8) T T T T T T T T T F F T T F T F F F F F F\n check 1 F\n dfs(11) T T T T T T T T T T F F T T F T F F F F F T\n check 8 F\n dfs(7) T T T T T T T T T T T F F T T F T F F F F F F\n check 8 F\n check 11 F\n 7 done\n check 1 F\n 11 done\n check 7 F\n check 4 F\n 8 done\n 4 done\n check 8 F\n check 11 F\n1 done\ndfs(9) T T T T T T T T T T T T F F T T F T F F F F F F\n9 done\n\nThe order of growth of the running time of the TwoColor constructor, in the worst case is O(V + E).\nEach adjacency-list entry is examined exactly once, and there are 2 * E such entries (two for each edge); initializing the marked[] and color[] arrays takes time proportional to V.","support_files":[],"metadata":{"number":"4.4.21","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Exercise","code_execution":false}} {"question":"Multisource shortest paths. Develop an API and implementation that uses Dijkstra’s algorithm to solve the multisource shortest-paths problem on edge-weighted digraphs with positive edge weights: given a set of sources, find a shortest-paths forest that enables implementation of a method that returns to clients the shortest path from any source to each vertex. Hint: Add a dummy vertex with a zero-weight edge to each source, or initialize the priority queue with all sources, with their distTo[] entries set to 0.","answer":"4.1.24\n\nNumber of connected components: 33\nSize of the largest component: 118774\nNumber of components of size less than 10: 5\nDoes the largest component contain Kevin Bacon: Yes\n\nEccentricity, diameter, radius, center and girth:\n\nThe strategy for computing the eccentricity, diameter, radius, center and girth of the largest component was the following:\nThe algorithm required for these exact computations has complexity of O(V * E) (running breadth-first search from all vertices). V is ~= 10^5, which means the algorithm required for these exact computation has complexity ~= 10^10.\n\nIn order to reduce the complexity of the computations (and to be able to compute them), domain knowledge was used to compute approximate results.\nBased on the Kevin Bacon game, we know that Kevin Bacon has been on several movies and that he is closely connected to most of the actors and actresses in the graph. Therefore, he has a high probability of being the center of the graph.\n\nUsing Kevin Bacon as the center, we compute his vertex eccentricity to get the graph radius.\nA breadth-first search using Kevin Bacon as the source computes the vertices that are furthest from the center. Computing the eccentricities of these vertices we can find the diameter of the graph.\n\nThe eccentricities of the center and of the vertices furthest from it are shown in the results. The range of the eccentricities is [10, 18]. Computing the eccentricities of all vertices would bring us back to the original problem of =~ 10^10 operations.\n\nFinally, for the girth, we know that there is a very high probability that two actors have worked together on two different movies. This gives a girth of 4, which is the minimum girth possible for the movies graph:\nActor -- Movie -- Actor\n \\ /\n \\ Movie /\nTo validate this theory we run the algorithm to compute the girth of the graph but stop once we find a cycle of length 4, since it is the shortest cycle possible.\n\n\nEccentricities of Kevin Bacon and of vertices furthest from the center in the largest component:\nEccentricity of vertex 22970: 16\nEccentricity of vertex 22971: 16\nEccentricity of vertex 22972: 16\nEccentricity of vertex 22973: 16\nEccentricity of vertex 22974: 16\nEccentricity of vertex 22976: 16\nEccentricity of vertex 22977: 16\nEccentricity of vertex 22978: 16\nEccentricity of vertex 22979: 16\nEccentricity of vertex 22980: 16\nEccentricity of vertex 51437: 18\nEccentricity of vertex 51438: 18\nEccentricity of vertex 51439: 18\nEccentricity of vertex 51440: 18\nEccentricity of vertex 51441: 18\nEccentricity of vertex 51442: 18\nEccentricity of vertex 51443: 18\nEccentricity of vertex 51444: 18\nEccentricity of vertex 51445: 18\nEccentricity of vertex 51446: 18\nEccentricity of vertex 51447: 18\nEccentricity of vertex 51448: 18\nEccentricity of vertex 51449: 18\nEccentricity of vertex 51450: 18\nEccentricity of vertex 51451: 18\nEccentricity of vertex 51452: 18\nEccentricity of vertex 51453: 18\nEccentricity of vertex 51454: 18\nEccentricity of vertex 51455: 18\nEccentricity of vertex 51456: 18\nEccentricity of vertex 51457: 18\nEccentricity of vertex 51458: 18\nEccentricity of vertex 51459: 18\nEccentricity of vertex 51460: 18\nEccentricity of vertex 51461: 18\nEccentricity of vertex 51462: 18\nEccentricity of vertex 51463: 18\nEccentricity of vertex 51464: 18\nEccentricity of vertex 51465: 18\nEccentricity of vertex 51466: 18\nEccentricity of vertex 51467: 18\nEccentricity of vertex 51468: 18\nEccentricity of vertex 51469: 18\nEccentricity of vertex 51470: 18\nEccentricity of vertex 51471: 18\nEccentricity of vertex 51472: 18\nEccentricity of vertex 51473: 18\nEccentricity of vertex 51474: 18\nEccentricity of vertex 51475: 18\nEccentricity of vertex 51476: 18\nEccentricity of vertex 51477: 18\nEccentricity of vertex 51478: 18\nEccentricity of vertex 51479: 18\nEccentricity of vertex 51480: 18\nEccentricity of vertex 51481: 18\nEccentricity of vertex 51482: 18\nEccentricity of vertex 51483: 18\nEccentricity of vertex 51484: 18\nEccentricity of vertex 51485: 18\nEccentricity of vertex 51486: 18\nEccentricity of vertex 51487: 18\nEccentricity of vertex 51488: 18\nEccentricity of vertex 51489: 18\nEccentricity of vertex 51490: 18\nEccentricity of vertex 51491: 18\nEccentricity of vertex 51492: 18\nEccentricity of vertex 51493: 18\nEccentricity of vertex 51494: 18\nEccentricity of vertex 51495: 18\nEccentricity of vertex 51496: 18\nEccentricity of vertex 51497: 18\nEccentricity of vertex 51498: 18\nEccentricity of vertex 51499: 18\nEccentricity of vertex 51500: 18\nEccentricity of vertex 51501: 18\nEccentricity of vertex 51502: 18\nEccentricity of vertex 51503: 18\nEccentricity of vertex 51504: 18\nEccentricity of vertex 51505: 18\nEccentricity of vertex 51506: 18\nEccentricity of vertex 51507: 18\nEccentricity of vertex 51508: 18\nEccentricity of vertex 51509: 18\nEccentricity of vertex 51510: 18\nEccentricity of vertex 51511: 18\nEccentricity of vertex 51512: 18\nEccentricity of vertex 51513: 18\nEccentricity of vertex 51514: 18\nEccentricity of vertex 51515: 18\nEccentricity of vertex 51516: 18\nEccentricity of vertex 51517: 18\nEccentricity of vertex 51518: 18\nEccentricity of vertex 51519: 18\nEccentricity of vertex 51520: 18\nEccentricity of vertex 86241: 16\nEccentricity of vertex 86242: 16\nEccentricity of vertex 86243: 16\nEccentricity of vertex 86244: 16\nEccentricity of vertex 86245: 16\nEccentricity of vertex 86246: 16\nEccentricity of vertex 86247: 16\nEccentricity of vertex 86248: 16\nEccentricity of vertex 86249: 16\nEccentricity of vertex 86250: 16\nEccentricity of vertex 86251: 16\nEccentricity of vertex 86252: 16\nEccentricity of vertex 86253: 16\nEccentricity of vertex 86254: 16\nEccentricity of vertex 86255: 16\nEccentricity of vertex 86256: 16\nEccentricity of vertex 86257: 16\nEccentricity of vertex 86258: 16\nEccentricity of vertex 86259: 16\nEccentricity of vertex 118353: 18\nEccentricity of vertex 118354: 18\nEccentricity of vertex 118355: 18\nEccentricity of vertex 118356: 18\nEccentricity of vertex 118357: 18\nEccentricity of vertex 118358: 18\nEccentricity of vertex 118359: 18\nEccentricity of vertex 118360: 18\nEccentricity of vertex 118361: 18\nEccentricity of vertex 118362: 18\nEccentricity of vertex 118363: 18\nEccentricity of vertex 118364: 18\nEccentricity of vertex 9145: 10\n\nDiameter of largest component: 18\nRadius of largest component: 10\nCenter of largest component: 9145\nGirth of largest component: 4","support_files":[],"metadata":{"number":"4.4.24","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"Shortest paths in Euclidean graphs. Adapt our APIs to speed up Dijkstra’s algorithm in the case where it is known that vertices are points in the plane.","answer":"4.1.27\n\nInteger\n* object overhead -> 16 bytes\n* int value -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 4 + 4 = 24 bytes\n\nNode\n* object overhead -> 16 bytes\n* extra overhead for reference to the enclosing instance -> 8 bytes\n* Item reference (item) -> 8 bytes\n* Node reference (next) -> 8 bytes\nAmount of memory needed: 16 + 8 + 8 + 8 = 40 bytes\n\nBag\n* object overhead -> 16 bytes\n* Node reference (first) -> 8 bytes\n* int value (size) -> 4 bytes\n* padding -> 4 bytes\n* N Nodes -> 40N bytes\n* Integer (item) -> 24N bytes\nAmount of memory needed: 16 + 8 + 4 + 4 + 40N + 24N = 64N + 32 bytes\n\nGraph\n* object overhead -> 16 bytes\n* int value (V) -> 4 bytes\n* int value (E) -> 4 bytes\n* Bag[] reference (adj) -> 8 bytes\n* Bag[] (adj)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n Bag references -> 8V\n Bag -> 64E + 32 bytes -> There are V Bags and in total, they have 2E nodes -> 128E + 32V\nAmount of memory needed: 16 + 4 + 4 + 8 + 16 + 4 + 4 + 8V + 128E + 32V = 128E + 40V + 56 bytes","support_files":[],"metadata":{"number":"4.4.27","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"Longest paths in DAGs. Develop an implementation AcyclicLP that can solve the longest-paths problem in edge-weighted DAGs, as described in PROPOSITION T.","answer":"4.1.28\n\nNon-isomorphic graphs:\n\nThere are 2 non-isomorphic graphs with 2 vertices:\no o\n\no-o\n\nThere are 4 non-isomorphic graphs with 3 vertices:\n o\no o\n\n o\no-o\n\no-o-o\n\n o\n/ \\\no-o\n\nThere are 11 non-isomorphic graphs with 4 vertices:\no o o o\n\no-o o o\n\no-o-o o\n\no-o-o-o\n\no-o o-o\n\n o\n |\n o\n / \\\no o\n\n o\n / \\\no---o o\n\no-o\n| |\no-o\n\n o\n | \n o\n / \\\no---o\n\n o\n / \\\no---o\n \\ /\n o\n\n o\n /|\\\n / o \\\n/ / \\ \\\no------o\n\nThere are 34 non-isomorphic graphs with 5 vertices:\n o\no o\n o o\n\n o\no o\n o-o\n\n o\no o\n /\n o-o\n\n o\no o\n \\ /\n o o\n\n o\n / | \\\no o o \n o\n\n o\n / \\\no o \n o-o\n\n o\n / \\\no o \n \\\n o o\n\n o\n / \\\no----o\n o o\n\n o\n /|\\\\\no o oo\n\no-o\n| |\no-o o\n\no\n|\no-o\n| |\no o\n\n o\n |\n o\n / \\\no---o o\n\no-o-o-o-o\n\n o o\n /| |\no | |\n \\| |\n o o\n\no--o\n| |\no--o\n|\no\n\no o\n| |\no---o\n \\ /\n o\n\n o--o\n \\/\no--o--o\n\n o\n / \\\no o \n \\ /\n o-o\n\n o (This is a complete graph, where all vertices have degree = 4)\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o---o\n\n o\n / / \\\\\no------o\n\\ /\\ /\\/\n \\|/\\ |/\n o o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|/\no---o\n\no---o\n|\\ /|\n| o |\n|/ \\|\no---o\n\no---o\n|\\ /|\\\n| X | o\n|/ \\|\no---o\n\n o\n // \\\no-o o\n \\/\n o\n\no-o-o-o\n \\| | /\n o\n\n o\n /\\\n / \\\n / \\\no------o\n\\ \\ / /\n \\ /\\ /\n o o\n\no---o\n| X | o\no---o\n\no o\n|\\ /|\n| o |\n|/ \\|\no o\n\n o\n /|\\\no--o | o\n \\|/\n o\n\n o\n |\n o\n /|\\\no | o\n \\|/\n o\n\n o\n / \\\no---o\n| |\no---o\n\no---o\n| /|\n| o |\n|/ |\no---o\n\n o\n |\n o\n |\n o\n / \\\no---o\n\no---o\n| \\ |\no---o o\n\nBased on: http://www.graphclasses.org/smallgraphs.html","support_files":[],"metadata":{"number":"4.4.28","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"All-pairs shortest path in graphs with negative cycles. Articulate an API like the one implemented on page 656 for the all-pairs shortest-paths problem in graphs with no negative cycles. Develop an implementation that runs a version of Bellman-Ford to identify weights pi[v] such that for any edge v->w, the edge weight plus the difference between pi[v] and pi[w] is nonnegative. Then use these weights to reweight the graph, so that Dijkstra’s algorithm is effective for finding all shortest paths in the reweighted graph.","answer":"4.1.30 - Eulerian and Hamiltonian cycles\n\nAn Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.\nA Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visited twice).\n\nAccording to Euler theorems a graph has an Eulerian cycle/circuit if and only if it does not have any vertices of odd degree.\n\nFirst graph:\n0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9).\nIt has a Hamiltonian cycle: 1-4 4-8 8-7 7-6 6-9 9-5 5-2 2-0 0-3 3-1\n\nSecond graph:\n0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8\n\nIt has an Eulerian cycle (all the vertices have even degrees):\n0-3 3-0 0-2 2-5 5-9 9-6 6-5 5-8 8-8 8-4 4-7 7-6 6-3 3-1 1-0\nThere is no Hamiltonian cycle.\n\nThird graph:\n0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 4-8 8-7 7-6 6-9 9-5 5-2 2-1 1-3 3-0 0-4\n\nFourth graph:\n4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-8 1-5 9-8 4-5 4-7\n\nIt does not have an Eulerian cycle because it has vertices of odd degree (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).\nIt has a Hamiltonian cycle: 0-5 5-4 4-1 1-6 6-3 3-7 7-9 9-8 8-2 2-0","support_files":[],"metadata":{"number":"4.4.30","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"All-pairs shortest path on a line. Given a weighted line graph (undirected connected graph, all vertices of degree 2, except two endpoints which have degree 1), devise an algorithm that preprocesses the graph in linear time and can return the distance of the shortest path between any two vertices in constant time.","answer":"4.1.31 - Graph enumeration\n\nIf we were considering graphs with no self-loops:\n\nThere are (V) ways to choose a set {u, v} of two vertices. From this set there are E ways to choose the vertices to connect.\n (2)\nSo there are ((V)) = (V! / 2! * (V - 2)!)! / E! * ((V! / 2! * (V - 2)!) - E)!\n ((2))\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges and no self-loops).\n\nSince we are also considering graphs with self-loops, there are (V) * 2^V ways to choose a set {u, v} of two vertices in which\n (2)\nvertices may or may not have a self-loop.\n\nSo there are ((V) * 2^V) = ((V! / 2! * (V - 2)!) * 2^V)! / E! * (((V! / 2! * (V - 2)!) * 2^V) - E)!\n ((2) )\n ( E )\ndifferent undirected graphs with V vertices and E edges (and no parallel edges).\n\nReference:\nHandbook of Discrete and Combinatorial Mathematics by Kenneth H. Rosen, page 580\nhttps://math.stackexchange.com/questions/1072726/counting-simple-connected-labeled-graphs-with-n-vertices-and-k-edges\nhttps://math.stackexchange.com/questions/128439/how-to-determine-the-number-of-directed-undirected-graphs","support_files":[],"metadata":{"number":"4.4.31","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"Shortest path in a grid. Given an N-by-N matrix of positive integers, find the shortest path from the (0, 0) entry to the (N-1, N-1) entry, where the length of the path is the sum of the integers in the path. Repeat the problem but assume you can only move right and down.","answer":"4.1.33 - Odd cycles\n\nA graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.\n\nProof:\n1- Proving that a graph with an odd-length cycle cannot be bipartite:\nIf a graph G is bipartite with vertex sets V1 and V2, every step along a walk takes you either from V1 to V2 or from V2 to V1. To end up where you started, therefore, you must take an even number of steps.\n\n2- Proving that a graph with only even-length cycles is bipartite:\nConsider G to be a graph with only even-length cycles. Let v0 be any vertex. For each vertex v in the same component C0 as v0 let d(v) be the length of the shortest path from v0 to v. Color red every vertex in C0 whose distance from v0 is even, and color the other vertices of C0 blue. Do the same for each component of G. Check that if G had any edge between two red vertices or between two blue vertices, it would have an odd cycle. Thus, G is bipartite, the red vertices and the blue vertices being the two parts.\n\nReference: \nhttps://math.stackexchange.com/questions/311665/proof-a-graph-is-bipartite-if-and-only-if-it-contains-no-odd-cycles","support_files":[],"metadata":{"number":"4.4.33","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"Bitonic shortest path. Given a digraph, find a bitonic shortest path from s to every other vertex (if one exists). A path is bitonic if there is an intermediate vertex v such that the edges on the path from s to v are strictly increasing and the edges on the path from v to t are strictly decreasing. The path should be simple (no repeated vertices).","answer":"4.1.35 - Biconnectedness\n\nAny graph with no articulation points is biconnected.\n\nProof:\nConsider two vertices, s, t, and a path P1 connecting s to t.\nWe know that no vertex in P1 is an articulation point, so for each vertex v in the path, there is always another path P2 connecting s to t that does not include it. Also, P2 does not include any of the vertices of P1, otherwise any vertex included in both paths would be an articulation point (being the only way to connect s to t).\nThis means that every pair of vertices is connected by two vertex-disjoint paths (such as P1 and P2), making the graph biconnected.\n\nGraph illustration (P1 is the path s-v1 v1-v2 v2-t and P2 is the path s-v3 v3-v4 v4-t):\n\ns\n|\\\n| \\\nv1 v3\n| \\\n| v4\nv2 /\n| /\n|/\nt","support_files":[],"metadata":{"number":"4.4.35","chapter":4,"chapter_title":"Graphs","section":4.4,"section_title":"Shortest Paths","type":"Creative Problem","code_execution":false}} {"question":"Give a trace for LSD string sort for the keys\n no is th ti fo al go pe to co to th ai of th pa","answer":"5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to","support_files":[],"metadata":{"number":"5.1.2","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Give a trace for MSD string sort for the keys\n no is th ti fo al go pe to co to th ai of th pa","answer":"5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --","support_files":[],"metadata":{"number":"5.1.3","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Give a trace for 3-way string quicksort for the keys\n no is th ti fo al go pe to co to th ai of th pa","answer":"5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --","support_files":[],"metadata":{"number":"5.1.4","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Give a trace for MSD string sort for the keys\n now is the time for all good people to come to the aid of","answer":"5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to","support_files":[],"metadata":{"number":"5.1.5","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Give a trace for 3-way string quicksort for the keys\n now is the time for all good people to come to the aid of","answer":"5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --","support_files":[],"metadata":{"number":"5.1.6","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Give the number of characters examined by MSD string sort and 3-way string quicksort for a file of N keys a, aa, aaa, aaaa, aaaaa, . . .","answer":"5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----","support_files":[],"metadata":{"number":"5.1.8","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"What is the total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W), in the worst case?","answer":"5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245","support_files":[],"metadata":{"number":"5.1.10","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Exercise","code_execution":false}} {"question":"Hybrid sort. Investigate the idea of using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.","answer":"5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.","support_files":[],"metadata":{"number":"5.1.13","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Creative Problem","code_execution":false}} {"question":"In-place key-indexed counting. Develop a version of key-indexed counting that uses only a constant amount of extra space. Prove that your version is stable or provide a counterexample.","answer":"5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]","support_files":[],"metadata":{"number":"5.1.17","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Creative Problem","code_execution":false}} {"question":"Timings. Compare the running times of MSD string sort and 3-way string quicksort, using various key generators. For fixed-length keys, include LSD string sort.","answer":"5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.","support_files":[],"metadata":{"number":"5.1.22","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Experiment","code_execution":false}} {"question":"Array accesses. Compare the number of array accesses used by MSD string sort and 3-way string sort, using various key generators. For fixed-length keys, include LSD string sort.","answer":"5.1.23 - Array accesses\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Number of array accesses\n Decimal keys Least-Significant-Digit 40000000\n Decimal keys Most-Significant-Digit 35443947\n Decimal keys 3-way string quicksort 78124405\n CA license plates Least-Significant-Digit 28000000\n CA license plates Most-Significant-Digit 25703588\n CA license plates 3-way string quicksort 82889002\n Fixed length words Least-Significant-Digit 40000000\n Fixed length words Most-Significant-Digit 14841196\n Fixed length words 3-way string quicksort 95310075\n Variable length items Most-Significant-Digit 72121457\n Variable length items 3-way string quicksort 97523400\n\nThe experiment results show that for all random string types, 3-way string quicksort accessed the array more times than LSD and MSD sort; LSD sort accessed the array more times than MSD sort; and MSD sort had the lowest number of array accesses.\nA possible explanation for these results is the fact that 3-way string quicksort accesses the array 4 times for each exchange operation, which leads to more array accesses than both LSD and MSD sorts, that do not make inplace exchanges.\nLSD sort will always access the array 4 * N * W times, where N is the number of strings and W is the length of the strings (which is equivalent to 4 array accesses for each character in the keys) and MSD sort will only access the array while the strings have common prefixes, which explains why MSD sort has the lowest number of array accesses of all sort types.","support_files":[],"metadata":{"number":"5.1.23","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Experiment","code_execution":false}} {"question":"Rightmost character accessed. Compare the position of the rightmost character accessed for MSD string sort and 3-way string quicksort, using various key generators.","answer":"5.1.24 - Rightmost character accessed\n\nRunning 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Rightmost character accessed\n Decimal keys Most-Significant-Digit 9\n Decimal keys 3-way string quicksort 9\n CA license plates Most-Significant-Digit 6\n CA license plates 3-way string quicksort 6\n Fixed length words Most-Significant-Digit 5\n Fixed length words 3-way string quicksort 5\n Variable length items Most-Significant-Digit 20\n Variable length items 3-way string quicksort 20\n\nIn all experiments the rightmost character position accessed in MSD sort and in 3-way string quicksort was the same, which shows that both algorithms scan the same characters.","support_files":[],"metadata":{"number":"5.1.24","chapter":5,"chapter_title":"Strings","section":5.1,"section_title":"String Sorts","type":"Experiment","code_execution":false}} {"question":"Draw the TST that results when the keys\n no is th ti fo al go pe to co to th ai of th pa\nare inserted in that order into an initially empty TST.","answer":"5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to","support_files":[],"metadata":{"number":"5.2.2","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Exercise","code_execution":false}} {"question":"Draw the R-way trie that results when the keys\n now is the time for all good people to come to the aid of\nare inserted in that order into an initially empty trie (do not draw null links).","answer":"5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --","support_files":[],"metadata":{"number":"5.2.3","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Exercise","code_execution":false}} {"question":"Draw the TST that results when the keys\n now is the time for all good people to come to the aid of\nare inserted in that order into an initially empty TST.","answer":"5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --","support_files":[],"metadata":{"number":"5.2.4","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Exercise","code_execution":false}} {"question":"Develop nonrecursive versions of TrieST and TST.","answer":"5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to","support_files":[],"metadata":{"number":"5.2.5","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Exercise","code_execution":false}} {"question":"Implement the following API, for a StringSET data type:\npublic class StringSET\nStringSET() create a string set\nvoid add(String key) put key into the set\nvoid delete(String key) remove key from the set\nboolean contains(String key) is key in the set?\nboolean isEmpty() is the set empty?\nint size() number of keys in the set\nint toString() string representation of the set","answer":"5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --","support_files":[],"metadata":{"number":"5.2.6","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Exercise","code_execution":false}} {"question":"Ordered operations for tries. Implement the floor(), ceil(), rank(), and select() (from our standard ordered ST API from Chapter 3) for TrieST.","answer":"5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----","support_files":[],"metadata":{"number":"5.2.8","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Creative Problem","code_execution":false}} {"question":"Size. Implement very eager size() (that keeps in each node the number of keys in its subtree) for TrieST and TST.","answer":"5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245","support_files":[],"metadata":{"number":"5.2.10","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Creative Problem","code_execution":false}} {"question":"Hybrid TST with R2-way branching at the root. Add code to TST to do multiway branching at the first two levels, as described in the text.","answer":"5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.","support_files":[],"metadata":{"number":"5.2.13","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Creative Problem","code_execution":false}} {"question":"Spell checking. Write a TST client SpellChecker that takes as command-line argument the name of a file containing a dictionary of words in the English language, and then reads a string from standard input and prints out any word that is not in the dictionary. Use a string set.","answer":"5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]","support_files":[],"metadata":{"number":"5.2.17","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Creative Problem","code_execution":false}} {"question":"Typing monkeys. Suppose that a typing monkey creates random words by appending each of 26 possible letter with probability p to the current word and finishes the word with probability 1 - 26p. Write a program to estimate the frequency distribution of the lengths of words produced. If \"abc\" is produced more than once, count it only once.","answer":"5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.","support_files":[],"metadata":{"number":"5.2.22","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Creative Problem","code_execution":false}} {"question":"Duplicates (revisited again). Redo Exercise 3.5.30 using StringSET (see Exercise 5.2.6) instead of HashSET. Compare the running times of the two approaches. Then use Dedup to run the experiments for N = 10^7, 10^8, and10^9, repeat the experiments for random long values and discuss the results.","answer":"5.1.23 - Array accesses\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Number of array accesses\n Decimal keys Least-Significant-Digit 40000000\n Decimal keys Most-Significant-Digit 35443947\n Decimal keys 3-way string quicksort 78124405\n CA license plates Least-Significant-Digit 28000000\n CA license plates Most-Significant-Digit 25703588\n CA license plates 3-way string quicksort 82889002\n Fixed length words Least-Significant-Digit 40000000\n Fixed length words Most-Significant-Digit 14841196\n Fixed length words 3-way string quicksort 95310075\n Variable length items Most-Significant-Digit 72121457\n Variable length items 3-way string quicksort 97523400\n\nThe experiment results show that for all random string types, 3-way string quicksort accessed the array more times than LSD and MSD sort; LSD sort accessed the array more times than MSD sort; and MSD sort had the lowest number of array accesses.\nA possible explanation for these results is the fact that 3-way string quicksort accesses the array 4 times for each exchange operation, which leads to more array accesses than both LSD and MSD sorts, that do not make inplace exchanges.\nLSD sort will always access the array 4 * N * W times, where N is the number of strings and W is the length of the strings (which is equivalent to 4 array accesses for each character in the keys) and MSD sort will only access the array while the strings have common prefixes, which explains why MSD sort has the lowest number of array accesses of all sort types.","support_files":[],"metadata":{"number":"5.2.23","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Experiment","code_execution":false}} {"question":"Spell checker. Redo Exercise 3.5.31, which uses the file dictionary.txt from the booksite and the BlackFilter client on page 491 to print all misspelled words in a text file. Compare the performance of TrieST and TST for the file war.txt with this client and discuss the results.","answer":"5.1.24 - Rightmost character accessed\n\nRunning 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Rightmost character accessed\n Decimal keys Most-Significant-Digit 9\n Decimal keys 3-way string quicksort 9\n CA license plates Most-Significant-Digit 6\n CA license plates 3-way string quicksort 6\n Fixed length words Most-Significant-Digit 5\n Fixed length words 3-way string quicksort 5\n Variable length items Most-Significant-Digit 20\n Variable length items 3-way string quicksort 20\n\nIn all experiments the rightmost character position accessed in MSD sort and in 3-way string quicksort was the same, which shows that both algorithms scan the same characters.","support_files":[],"metadata":{"number":"5.2.24","chapter":5,"chapter_title":"Strings","section":5.2,"section_title":"Tries","type":"Experiment","code_execution":false}} {"question":"Give the dfa[][] array for the Knuth-Morris-Pratt algorithm for the pattern A A A A A A A A A, and draw the DFA, in the style of the figures in the text.","answer":"5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to","support_files":[],"metadata":{"number":"5.3.2","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Give the dfa[][] array for the Knuth-Morris-Pratt algorithm for the pattern A B R A C A D A B R A, and draw the DFA, in the style of the figures in the text.","answer":"5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --","support_files":[],"metadata":{"number":"5.3.3","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Write an efficient method that takes a string txt and an integer M as arguments and returns the position of the first occurrence of M consecutive blanks in the string, txt.length if there is no such occurrence. Estimate the number of character compares used by your method, on typical text and in the worst case.","answer":"5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --","support_files":[],"metadata":{"number":"5.3.4","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Develop a brute-force substring search implementation BruteForceRL that processes the pattern from right to left (a simplified version of ALGORITHM 5.7).","answer":"5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to","support_files":[],"metadata":{"number":"5.3.5","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Give the right[] array computed by the constructor in ALGORITHM 5.7 for the pattern A B R A C A D A B R A.","answer":"5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --","support_files":[],"metadata":{"number":"5.3.6","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Add to KMP a count() method to count occurrences and a searchAll() method to print all occurrences.","answer":"5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----","support_files":[],"metadata":{"number":"5.3.8","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Add to RabinKarp a count() method to count occurrences and a searchAll() method to print all occurrences.","answer":"5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245","support_files":[],"metadata":{"number":"5.3.10","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"In the Boyer-Moore implementation in ALGORITHM 5.7, show that you can set right[c] to the penultimate occurrence of c when c is the last character in the pattern.","answer":"5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.","support_files":[],"metadata":{"number":"5.3.13","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Draw the KMP DFA for the following pattern strings.\na. AAAAAAB\nb. AACAAAB\nc. ABABABAB\nd. ABAABAAABAAAB\ne. ABAABCABAABCB","answer":"5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]","support_files":[],"metadata":{"number":"5.3.17","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"How would you modify the Rabin-Karp algorithm to search for an H-by-V pattern in an N-by-N text?","answer":"5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.","support_files":[],"metadata":{"number":"5.3.22","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Write a program that reads characters one at a time and reports at each instant if the current string is a palindrome. Hint : Use the Rabin-Karp hashing idea.","answer":"5.1.23 - Array accesses\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Number of array accesses\n Decimal keys Least-Significant-Digit 40000000\n Decimal keys Most-Significant-Digit 35443947\n Decimal keys 3-way string quicksort 78124405\n CA license plates Least-Significant-Digit 28000000\n CA license plates Most-Significant-Digit 25703588\n CA license plates 3-way string quicksort 82889002\n Fixed length words Least-Significant-Digit 40000000\n Fixed length words Most-Significant-Digit 14841196\n Fixed length words 3-way string quicksort 95310075\n Variable length items Most-Significant-Digit 72121457\n Variable length items 3-way string quicksort 97523400\n\nThe experiment results show that for all random string types, 3-way string quicksort accessed the array more times than LSD and MSD sort; LSD sort accessed the array more times than MSD sort; and MSD sort had the lowest number of array accesses.\nA possible explanation for these results is the fact that 3-way string quicksort accesses the array 4 times for each exchange operation, which leads to more array accesses than both LSD and MSD sorts, that do not make inplace exchanges.\nLSD sort will always access the array 4 * N * W times, where N is the number of strings and W is the length of the strings (which is equivalent to 4 array accesses for each character in the keys) and MSD sort will only access the array while the strings have common prefixes, which explains why MSD sort has the lowest number of array accesses of all sort types.","support_files":[],"metadata":{"number":"5.3.23","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Exercise","code_execution":false}} {"question":"Find all occurrences. Add a method findAll() to each of the four substring search algorithms given in the text that returns an Iterable that allows clients to iterate through all offsets of the pattern in the text.","answer":"5.1.24 - Rightmost character accessed\n\nRunning 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Rightmost character accessed\n Decimal keys Most-Significant-Digit 9\n Decimal keys 3-way string quicksort 9\n CA license plates Most-Significant-Digit 6\n CA license plates 3-way string quicksort 6\n Fixed length words Most-Significant-Digit 5\n Fixed length words 3-way string quicksort 5\n Variable length items Most-Significant-Digit 20\n Variable length items 3-way string quicksort 20\n\nIn all experiments the rightmost character position accessed in MSD sort and in 3-way string quicksort was the same, which shows that both algorithms scan the same characters.","support_files":[],"metadata":{"number":"5.3.24","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Creative Problem","code_execution":false}} {"question":"Tandem repeat search. A tandem repeat of a base string b in a string s is a substring of s having at least two consecutive copies b (nonoverlapping). Develop and implement a linear-time algorithm that, given two strings b and s, returns the index of the beginning of the longest tandem repeat of b in s. For example, your program should return 3 when b is abcab and s is abcabcababcababcababcab.","answer":"5.5.27 - Long repeats\n\nCompressing 2 * 1000 random characters (for N = 1000), with 16000 bits (8 bits per character).\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n53736 bits\n\nCompression ratio: 53736 / 16000 = 335%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n12624 bits\n\nCompression ratio: 12624 / 16000 = 79%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n13416 bits\n\nCompression ratio: 13416 / 16000 = 83%","support_files":[],"metadata":{"number":"5.3.27","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Creative Problem","code_execution":false}} {"question":"Random patterns. How many character compares are needed to do a substring search for a random pattern of length 100 in a given text?\nAnswer: None. The method\npublic boolean search(char[] txt)\n{ return false; }\nis quite effective for this problem, since the chances of a random pattern of length 100 appearing in any text are so low that you may consider it to be 0.","answer":"5.3.31 - Random patterns\n\nNone. The method\npublic boolean search(char[] text) {\n return false;\n}\nis quite effective for this problem, since the chances of a random pattern of length 100 appearing in any text are so low that you may consider it to be 0.","support_files":[],"metadata":{"number":"5.3.31","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Creative Problem","code_execution":false}} {"question":"Timings. Write a program that times the four methods for the task of searchng for the substring\nit is a far far better thing that i do than i have ever done\nin the text of Tale of Two Cities (tale.txt). Discuss the extent to which your results validate the hypthotheses about performance that are stated in the text.","answer":"5.3.39 - Timings\n\n Method | Time spent\n Bruteforce 0.01\nKnuth-Morris-Pratt 0.01\n Boyer-Moore 0.00\n Rabin-Karp 0.04\n\nThe results validate the hypotheses about performance stated in the text:\nBoth brute force and Knuth-Morris-Pratt methods took 0.01 seconds to do the search, which is aligned with their expected performance of 1.1N operations when searching in typical texts.\nBoyer-Moore took 0.00 seconds to do the search, which suggests that it did a sublinear number of operations. This is aligned with its expected performance of N / M operations when searching in typical texts.\nRabin-Karp took 0.04 seconds to do the search, a longer time than all other three methods. However, this is expected according to the hypothesis in the text that it performs 7N operations when searching in typical texts.","support_files":[],"metadata":{"number":"5.3.39","chapter":5,"chapter_title":"Strings","section":5.3,"section_title":"Substring Search","type":"Experiment","code_execution":false}} {"question":"Give a brief English description of each of the following REs:\na. .*\nb. A.*A | A\nc. .*ABBABBA.*\nd. .* A.*A.*A.*A.*","answer":"5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to","support_files":[],"metadata":{"number":"5.4.2","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"What is the maximum number of different strings that can be described by a regular expression with M or operators and no closure operators (parentheses and concatenation are allowed)?","answer":"5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --","support_files":[],"metadata":{"number":"5.4.3","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Draw the NFA corresponding to the pattern ( ( ( A | B ) * | C D * | E F G ) * ) * .","answer":"5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --","support_files":[],"metadata":{"number":"5.4.4","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Draw the digraph of ε-transitions for the NFA from Exercise 5.4.4.","answer":"5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to","support_files":[],"metadata":{"number":"5.4.5","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Give the sets of states reachable by your NFA from EXERCISE 5.4.4 after each character match and susbsequent ε-transitions for the input A B B A C E F G E F G C A A B .","answer":"5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --","support_files":[],"metadata":{"number":"5.4.6","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Write a regular expression for each of the following sets of binary strings:\na. Contains at least three consecutive 1s\nb. Contains the substring 110\nc. Contains the substring 1101100\nd. Does not contain the substring 110","answer":"5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----","support_files":[],"metadata":{"number":"5.4.8","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Write a regular expression for each of the following sets of binary strings:\na. Has at least 3 characters, and the third character is 0\nb. Number of 0s is a multiple of 3\nc. Starts and ends with the same character\nd. Odd length\ne. Starts with 0 and has odd length, or starts with 1 and has even length\nf. Length is at least 1 and at most 3","answer":"5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245","support_files":[],"metadata":{"number":"5.4.10","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Exercise","code_execution":false}} {"question":"Challenging REs. Construct an RE that describes each of the following sets of strings over the binary alphabet:\na. All strings except 11 or 111\nb. Strings with 1 in every odd-number bit position\nc. Strings with at least two 0s and at most one 1\nd. Strings with no two consecutive 1s","answer":"5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.","support_files":[],"metadata":{"number":"5.4.13","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Creative Problem","code_execution":false}} {"question":"Wildcard. Add to NFA the capability to handle wildcards.","answer":"5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]","support_files":[],"metadata":{"number":"5.4.17","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Creative Problem","code_execution":false}} {"question":"Proof. Develop a version of NFA that prints a proof that a given string is in the language recognized by the NFA (a sequence of state transitions that ends in the accept state).","answer":"5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.","support_files":[],"metadata":{"number":"5.4.22","chapter":5,"chapter_title":"Strings","section":5.4,"section_title":"Regular Expressions","type":"Creative Problem","code_execution":false}} {"question":"Given a example of a uniquely decodable code that is not prefix-free.\nAnswer : Any suffix-free code is uniquely decodable.","answer":"5.1.2\n\nTrace for LSD string sort (same model as used in the book):\n\ninput d=1 d=0 output\nno pa ai ai\nis pe al al\nth of co co\nti th fo fo\nfo th go go\nal th is is\ngo ti no no\npe ai of of\nto al pa pa\nco no pe pe\nto fo th th\nth go th th\nai to th th\nof co ti ti\nth to to to\npa is to to","support_files":[],"metadata":{"number":"5.5.2","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Give an example of a uniquely decodable code that is not prefix free or suffix free.\nAnswer : {0011, 011, 11, 1110} or {01, 10, 011, 110}","answer":"5.1.3\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 15, 0):\n\ninput\n0 no\n1 is\n2 th\n3 ti\n4 fo\n5 al\n6 go\n7 pe\n8 to\n9 co\n10 to\n11 th\n12 ai\n13 of\n14 th\n15 pa\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 2\n18 q 0\n19 r 0\n20 s 0\n21 t 6\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 10\n18 q 10\n19 r 10\n20 s 10\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nDistribute and copy back\n0 al\n1 ai\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pe\n9 pa\n10 th\n11 ti\n12 to\n13 to\n14 th\n15 th\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 10\n17 p 10\n18 q 10\n19 r 10\n20 s 16\n21 t 16\n22 u 16\n23 v 16\n24 x 16\n25 w 16\n26 y 16\n27 z 16\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 9, 1);\nsort(a, 10, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\nsort(a, 16, 15, 1);\n\nSorted result\n0 ai\n1 al\n2 co\n3 fo\n4 go\n5 is\n6 no\n7 of\n8 pa\n9 pe\n10 th\n11 th\n12 th\n13 ti\n14 to\n15 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput __ __ output\nno al ai ai ai ai \nis ai al al al al\nth co -- co co co\nti fo co fo fo fo\nfo go fo go go go\nal is go is is is\ngo no is no no no\npe of no of of of\nto pe of -- pa pa\nco pa pe pa pe pe\nto th pa pe -- th\nth ti th -- th th\nai to ti th th th\nof to to ti th ti\nth th to to ti to\npa th th to to to\n -- th th to\n th --","support_files":[],"metadata":{"number":"5.5.3","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Are { 01, 1001, 1011, 111, 1110 } and { 01, 1001, 1011, 111, 1110 } uniquely decodable? If not, find a string with two encodings.","answer":"5.1.4\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n -- -- --\n0 no is ai ai ai ai\n1 is ai co al -- al\n2 th co fo -- al co\n3 ti fo al fo -- fo\n4 fo al go go co go\n5 al go -- co -- is\n6 go -- is -- fo no\n7 pe no -- is -- of\n8 to -- no -- go pa\n9 co to -- no -- pe\n10 to pe pe -- is th\n11 th to of of -- th\n12 ai th pa -- no th\n13 of ti -- pe -- ti\n14 th of th pa of to\n15 pa th ti -- -- to\n pa to th pa \n th th th --\n to th pe\n th -- --\n -- to th\n to th\n ti th\n --\n ti\n --\n to\n to\n --","support_files":[],"metadata":{"number":"5.5.4","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Use RunLength on the file q128x192.bin from the booksite. How many bits are there in the compressed file?","answer":"5.1.5\n\nAccording to ASC II values, indices of chars 'a' through 'z' start at 97.\nBut this trace indices follow the book convention of 'a' starting at 0.\n\nTrace for MSD string sort (same model as used in the book):\n\nTop level of sort(array, 0, 13, 0):\n\ninput\n0 now\n1 is\n2 the\n3 time\n4 for\n5 all\n6 good\n7 people\n8 to\n9 come\n10 to\n11 the\n12 aid\n13 of\n\nd=0\nCount frequencies\n0 0\n1 0\n2 a 2\n3 b 0\n4 c 1\n5 d 0\n6 e 0\n7 f 1\n8 g 1\n9 h 0\n10 i 1\n11 j 0\n12 k 0\n13 l 0\n14 m 0\n15 n 1\n16 o 1\n17 p 1\n18 q 0\n19 r 0\n20 s 0\n21 t 5\n22 u 0\n23 v 0\n24 x 0\n25 w 0\n26 y 0\n27 z 0\n\nTransform counts to indices\n0 0\n1 0\n2 a 2\n3 b 2\n4 c 3\n5 d 3\n6 e 3\n7 f 4\n8 g 5\n9 h 5\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 6\n15 n 7\n16 o 8\n17 p 9\n18 q 9\n19 r 9\n20 s 9\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nDistribute and copy back\n0 all\n1 aid\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 time\n11 to\n12 to\n13 the\n\nIndices at completion of distribute phase\n0 0\n1 2\n2 a 2\n3 b 3\n4 c 3\n5 d 3\n6 e 4\n7 f 5\n8 g 5\n9 h 6\n10 i 6\n11 j 6\n12 k 6\n13 l 6\n14 m 7\n15 n 8\n16 o 9\n17 p 9\n18 q 9\n19 r 9\n20 s 14\n21 t 14\n22 u 14\n23 v 14\n24 x 14\n25 w 14\n26 y 14\n27 z 14\n\nRecursively sort subarrays\nsort(a, 0, 1, 1);\nsort(a, 2, 1, 1);\nsort(a, 2, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 2, 1);\nsort(a, 3, 3, 1);\nsort(a, 4, 4, 1);\nsort(a, 5, 4, 1);\nsort(a, 5, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 5, 1);\nsort(a, 6, 6, 1);\nsort(a, 7, 7, 1);\nsort(a, 8, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 8, 1);\nsort(a, 9, 13, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\nsort(a, 13, 14, 1);\n\nSorted result\n0 aid\n1 all\n2 come\n3 for\n4 good\n5 is\n6 now\n7 of\n8 people\n9 the\n10 the\n11 time\n12 to\n13 to\n\nTrace of recursive calls for MSD string sort (no cutoff for small subarrays, subarrays of size 0 and 1 omitted)\n\ninput ____ ___ output \nnow all aid aid aid aid \nis aid all all all all\nthe come --- come come come\ntime for come for for for\nfor good for good good good\nall is good is is is\ngood now is now now now\npeople of now of of of\nto people of people people people\ncome the people --- --- the\nto time the the the the\nthe to time the the time\naid to to time --- to\nof the to to time to\n ---- the to to\n --- to","support_files":[],"metadata":{"number":"5.5.5","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"How many bits are needed to encode N copies of the symbol a (as a function of N)? N copies of the sequence abc?","answer":"5.1.6\n\nTrace for 3-way string quicksort (same model as used in the book):\n\n ---- --- --- ---\n0 now is aid aid aid aid aid\n1 is aid come all --- --- all\n2 the come for --- all all come\n3 time for all for --- --- for\n4 for all good good come come good\n5 all good ---- come ---- ---- is\n6 good --- is ---- for for now\n7 people now --- is ---- ---- of\n8 to --- now --- good good people\n9 come to --- now ---- ---- the\n10 to people people --- is is the\n11 the to of of --- --- time\n12 aid the --- ------ now now to\n13 of time to people --- --- to\n of the ------ of of\n the time the ------ ------\n to time people people\n the the ------ ------\n --- ---- the the\n to the the\n to ---- ----\n ---- time time\n ---- ----\n to to\n to to\n -- --","support_files":[],"metadata":{"number":"5.5.6","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Give the result of encoding the strings ab, abab, ababab, abababab, ... (strings consisting of N repetitions of ab) with run-length, Huffman, and LZW encoding. What is the compression ratio as a function of N?","answer":"5.1.8\n\nBoth MSD string sort and 3-way string quicksort examine all characters in the N keys.\nThat number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.\nMSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicksort generates 2N empty subarrays (empty subarrays for digits smaller than 'a' and for digits higher than 'a', or empty subarrays for digits smaller than '-1' and for digits equal to '-1', in every pass).\n\nMSD string sort trace (no cutoff for small subarrays, subarrays of size 0 and 1 omitted):\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----\n\n3-way string quicksort trace:\n\ninput ----\na a a a a a a\naa aa ---- aa aa aa aa\naaa aaa aa ---- aaa aaa aaa\naaaa aaaa aaa aaa ---- aaaa aaaa\n... ... aaaa aaaa aaaa ---- ...\n ---- ... ... ... ...\n ---- ---- ---- ----","support_files":[],"metadata":{"number":"5.5.8","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"In the style of the figure in the text, show the Huffman coding tree construction process when you use Huffman for the string \"it was the age of foolishness”. How many bits does the compressed bitstream require?","answer":"5.1.10\n\nThe total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).\n\nThis can be seen with a recurrence relation T(W).\n\nThe base case T(1) is when all the strings have length 1.\nAn example with R = 3 is { \"a\", \"b\", \"c\" }.\nIn the worst case they are in reverse order.\nFor example: { \"c\", \"b\", \"a\" }.\nIn this case we only remove one string from the list in each pass.\nIf we consider N = R^W (in this case, W = 1), the number of comparisons is equal to:\nCharacters examined = Sum[i=0..R] i\nCharacters examined = R * (R + 1) / 2\n\nTo build the worst case for strings of length 2 (T(2)), we take each string from T(1) and append it to the end of each character in R.\nSo for single character strings \"a\", \"b\", \"c\", with R = 3, the two character list is: \"aa\", \"ab\", \"ac\", \"ba\", \"bb\", \"bc\", \"ca\", \"cb\", \"cc\".\nThe list can then be split into R groups: one for each character in R that is a prefix to every string of length W - 1.\nDuring the partitioning phase all strings that start with \"a\" will be in the same partition and the algorithm will do the same process as in T(1) because removing the first character 'a' will lead to the same 1-length strings { \"c\", \"b\", \"a\" } as before.\nThe same thing happens for strings starting with \"b\" and \"c\".\nSo, for R = 3, the algorithm will check 3 * R + 2 * R + R characters in the first position of the strings (which is 3 + 2 + 1 characters times R groups).\nThen it will check the second characters in the strings in each of the R groups.\n\nFor T(W), where W > 2, the list will then again be split into R groups: one for each character in R that is a prefix to every string of length W - 2.\nQuicksort will then remove R strings from the list in each partition.\nIt will then check R * T(W - 1) more characters for each of those groups.\nThis gives the recurrence T(W) = (R^(W - 1) * Sum[i=0..R] R - i) + R * T(W - 1), which simplifies to:\nT(W) = R^(W + 1) + R^W + R * T(W - 1)\n -----------------\n 2\nSolving the recurrence gives us:\nT(W) = W * (R^W) * (R + 1)\n ---------------------\n 2\nSubstituting N = R^W:\nT(W) = W * N * (R + 1)\n -----------------\n 2\nWhich is O(N * W * R).\n\nThanks to dragon-dreamer (https://github.com/dragon-dreamer) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/153\nThanks to GenevaS (https://github.com/GenevaS) for finding a more accurate worst case.\nhttps://github.com/reneargento/algorithms-sedgewick-wayne/issues/245","support_files":[],"metadata":{"number":"5.5.10","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Suppose that all of the symbol frequencies are equal. Describe the Huffman code.","answer":"5.1.13 - Hybrid sort\n\nIdea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.\n\nThis idea will work well for random strings because, in general, the higher the number of keys to be sorted, the higher the number of non-empty subarrays generated on each pass of MSD string sort. Such scenario would work well due to the advantage of having multiway partitioning.\nHowever, MSD string sort will still generate a large number of empty subarrays if there is a large number of equal keys (or a large number of keys with long common prefixes).\n\n3-way string quicksort will avoid the negative effects of large numbers of empty bins not only for smaller arrays, but also for large arrays, while also having the benefit of using less space than MSD string sort since it does not require space for frequency counts or for an auxiliary array. On the other hand, it envolves more data movement than MSD string sort when the number of nonempty subarrays is large because it has to do a series of 3-way partitions to get the effect of the multiway partition. This would not be a problem in the hybrid sort if there were many equal keys in smaller arrays, since 3-way string quicksort would be the algorithm of choice in such situation.\n\nOverall, hybrid sort would be a good choice for random strings. However, a version of hybrid sort that chooses between MSD string sort and 3-way string quicksort based on the percentage of equal keys (choosing MSD string sort if there is a low percentage of equal keys and choosing 3-way string quicksort if there is a high number of equal keys) would be more effective than a version that makes the choice based on the number of keys.","support_files":[],"metadata":{"number":"5.5.13","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Characterize the tricky situation in LZW coding.\nSolution: Whenever it encounters cScSc, where c is a symbol and S is a string, cS is in the dictionary already but cSc is not.","answer":"5.1.17 - In-place key-indexed counting\n\nLSD and MSD sorts that use only a constant amount of extra space are not stable.\n\nCounterexample for LSD sort:\n\nThe array [\"4PGC938\", \"2IYE230\", \"3CIO720\", \"1ICK750\", \"1OHV845\", \"4JZY524\", \"1ICK750\", \"3CIO720\", \"1OHV845\", \"1OHV845\", \"2RLA629\", \"2RLA629\", \"3ATW723\"] after being sorted by in-place LSD becomes:\n[\"1OHV845\", \"1OHV845\", \"1OHV845\", \"1ICK750\", \"1ICK750\", \"2RLA629\", \"2IYE230\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4PGC938\", \"4JZY524\"]\nIf it were sorted by non-in-place LSD the output would be:\n[\"1ICK750\", \"1ICK750\", \"1OHV845\", \"1OHV845\", \"1OHV845\", \"2IYE230\", \"2RLA629\", \"2RLA629\", \"3ATW723\", \"3CIO720\", \"3CIO720\", \"4JZY524\", \"4PGC938\"]\n\nCounterexample for both LSD and MSD sorts:\n\nThe array [\"CAA\" (index 0), \"ABB\" (index 1), \"ABB\" (index 2)] after being sorted by either in-place LSD or in-place MSD becomes:\n[\"ABB\" (original index 2), \"ABB\" (original index 1), \"CAA\" (original index 0)]\nIf it were sorted by non-in-place LSD or MSD the output would be:\n[\"ABB\" (original index 1), \"ABB\" (original index 2), \"CAA\" (original index 0)]","support_files":[],"metadata":{"number":"5.5.17","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Prove the following fact about Huffman codes: If the frequency of symbol i is strictly larger than the frequency of symbol j, then the length of the codeword for symbol i is less than or equal to the length of the codeword for symbol j.","answer":"5.1.22 - Timings\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Average time spent\n Decimal keys Least-Significant-Digit 2.30\n Decimal keys Most-Significant-Digit 0.45\n Decimal keys 3-way string quicksort 0.32\n CA license plates Least-Significant-Digit 1.48\n CA license plates Most-Significant-Digit 0.41\n CA license plates 3-way string quicksort 0.33\n Fixed length words Least-Significant-Digit 2.52\n Fixed length words Most-Significant-Digit 0.28\n Fixed length words 3-way string quicksort 0.35\n Variable length items Most-Significant-Digit 1.80\n Variable length items 3-way string quicksort 0.55\n\nThe experiment results show that for all random string types, LSD sort had the worst results.\nFor random decimal keys, random CA license plates and random variable length items 3-way string quicksort had the best results.\nFor random fixed-length words, MSD had the best running time.\nHaving to always scan all characters in all keys may explain why LSD sort had the slowest running times when sorting all random string types. 3-way string quicksort may have had good results because it does not create a high number of empty subarrays, as MSD sort does, and because it can handle well keys with long common prefixes (which are likely to happen in random decimal keys, random CA license plates and random variable length items).\nRandom fixed-length words are less likely to have long common prefixes (because all their characters are in the range [40, 125]), which may explain why MSD sort had better results than both LSD sort and 3-way string quicksort during their sort.","support_files":[],"metadata":{"number":"5.5.22","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"What would be the result of breaking up a Huffman-encoded string into five-bit characters and Huffman-encoding that string?","answer":"5.1.23 - Array accesses\n\nRunning 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Number of array accesses\n Decimal keys Least-Significant-Digit 40000000\n Decimal keys Most-Significant-Digit 35443947\n Decimal keys 3-way string quicksort 78124405\n CA license plates Least-Significant-Digit 28000000\n CA license plates Most-Significant-Digit 25703588\n CA license plates 3-way string quicksort 82889002\n Fixed length words Least-Significant-Digit 40000000\n Fixed length words Most-Significant-Digit 14841196\n Fixed length words 3-way string quicksort 95310075\n Variable length items Most-Significant-Digit 72121457\n Variable length items 3-way string quicksort 97523400\n\nThe experiment results show that for all random string types, 3-way string quicksort accessed the array more times than LSD and MSD sort; LSD sort accessed the array more times than MSD sort; and MSD sort had the lowest number of array accesses.\nA possible explanation for these results is the fact that 3-way string quicksort accesses the array 4 times for each exchange operation, which leads to more array accesses than both LSD and MSD sorts, that do not make inplace exchanges.\nLSD sort will always access the array 4 * N * W times, where N is the number of strings and W is the length of the strings (which is equivalent to 4 array accesses for each character in the keys) and MSD sort will only access the array while the strings have common prefixes, which explains why MSD sort has the lowest number of array accesses of all sort types.","support_files":[],"metadata":{"number":"5.5.23","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"In the style of the figures in the text, show the encoding trie and the compression and expansion processes when LZW is used for the string\nit was the best of times it was the worst of times","answer":"5.1.24 - Rightmost character accessed\n\nRunning 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Most-Significant-Digit sort was equal to 15.\n\n Random string type | Sort type | Rightmost character accessed\n Decimal keys Most-Significant-Digit 9\n Decimal keys 3-way string quicksort 9\n CA license plates Most-Significant-Digit 6\n CA license plates 3-way string quicksort 6\n Fixed length words Most-Significant-Digit 5\n Fixed length words 3-way string quicksort 5\n Variable length items Most-Significant-Digit 20\n Variable length items 3-way string quicksort 20\n\nIn all experiments the rightmost character position accessed in MSD sort and in 3-way string quicksort was the same, which shows that both algorithms scan the same characters.","support_files":[],"metadata":{"number":"5.5.24","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Exercise","code_execution":false}} {"question":"Long repeats. Estimate the compression ratio achieved by run-length, Huffman, and LZW encoding for a string of length 2N formed by concatenating two copies of a random ASCII string of length N (see EXERCISE 5.5.9), under any assumptions that you think are reasonable.","answer":"5.5.27 - Long repeats\n\nCompressing 2 * 1000 random characters (for N = 1000), with 16000 bits (8 bits per character).\n\n% java -cp algs4.jar:. RunLengthEncoding - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n53736 bits\n\nCompression ratio: 53736 / 16000 = 335%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.Huffman - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n12624 bits\n\nCompression ratio: 12624 / 16000 = 79%\n\n% java -cp algs4.jar:. edu.princeton.cs.algs4.LZW - < 5.5.27_random.txt | java -cp algs4.jar:. BinaryDump 0\n13416 bits\n\nCompression ratio: 13416 / 16000 = 83%","support_files":[],"metadata":{"number":"5.5.27","chapter":5,"chapter_title":"Strings","section":5.5,"section_title":"Data Compression","type":"Creative Problem","code_execution":false}} {"question":"Molecules travel very quickly (faster than a speeding jet) but diffuse slowly because they collide with other molecules, thereby changing their direction. Extend the model to have a boundary shape where two vessels are connected by a pipe containing two different types of particles. Run a simulation and measure the fraction of particles of each type in each vessel as a function of time.","answer":"Results\n\nTime 0\nLEFT VESSEL: 10 particles\nType 1: 10/10 Type 2: 0/10\nRIGHT VESSEL: 10 particles\nType 1: 0/10 Type 2: 10/10\n\nTime 1000\nLEFT VESSEL: 14 particles\nType 1: 9/14 Type 2: 5/14\nRIGHT VESSEL: 6 particles\nType 1: 1/6 Type 2: 5/6\n\nTime 2000\nLEFT VESSEL: 11 particles\nType 1: 6/11 Type 2: 5/11\nRIGHT VESSEL: 9 particles\nType 1: 4/9 Type 2: 5/9\n\nTime 3000\nLEFT VESSEL: 13 particles\nType 1: 7/13 Type 2: 6/13\nRIGHT VESSEL: 6 particles\nType 1: 2/6 Type 2: 4/6\n\nTime 4000\nLEFT VESSEL: 13 particles\nType 1: 7/13 Type 2: 6/13\nRIGHT VESSEL: 7 particles\nType 1: 3/7 Type 2: 4/7\n\nTime 5000\nLEFT VESSEL: 10 particles\nType 1: 6/10 Type 2: 4/10\nRIGHT VESSEL: 10 particles\nType 1: 4/10 Type 2: 6/10\n\nTime 6000\nLEFT VESSEL: 11 particles\nType 1: 6/11 Type 2: 5/11\nRIGHT VESSEL: 9 particles\nType 1: 4/9 Type 2: 5/9\n\nTime 7000\nLEFT VESSEL: 10 particles\nType 1: 5/10 Type 2: 5/10\nRIGHT VESSEL: 10 particles\nType 1: 5/10 Type 2: 5/10\n\nTime 8000\nLEFT VESSEL: 8 particles\nType 1: 3/8 Type 2: 5/8\nRIGHT VESSEL: 12 particles\nType 1: 7/12 Type 2: 5/12\n\nTime 9000\nLEFT VESSEL: 10 particles\nType 1: 3/10 Type 2: 7/10\nRIGHT VESSEL: 10 particles\nType 1: 7/10 Type 2: 3/10\n\nTime 10000\nLEFT VESSEL: 9 particles\nType 1: 5/9 Type 2: 4/9\nRIGHT VESSEL: 11 particles\nType 1: 5/11 Type 2: 6/11\n\nThe system tends to achieve a balance between the number of particles of both types on both vessels.","support_files":[],"metadata":{"number":"6.9","chapter":6,"chapter_title":"Context","section":6.1,"section_title":"Collision Simulation","type":"Exercise","code_execution":false}} {"question":"After running a simulation, negate all velocities and then run the system backward. It should return to its original state! Measure roundoff error by measuring the difference between the final and original states of the system.","answer":"Roundoff error: 0.22176242098152166","support_files":[],"metadata":{"number":"6.10","chapter":6,"chapter_title":"Context","section":6.1,"section_title":"Collision Simulation","type":"Exercise","code_execution":false}} {"question":"Add a method pressure() to Particle that measures pressure by accumulating the number and magnitude of collisions against walls. The pressure of the system is the sum of these quantities. Then add a method pressure() to CollisionSystem and write a client that validates the equation pv = nRT.","answer":"Pressure measured with P V = n R T: 5.480029392202992E-4\nPressure measured with wall collisions: 4.394236724937985E-4\n\nPressure measured with P V = n R T: 3.855098323894351E-4\nPressure measured with wall collisions: 4.389151787833636E-4\n\nPressure measured with P V = n R T: 4.675754466697337E-4\nPressure measured with wall collisions: 4.3342966247778204E-4\n\nPressure measured with P V = n R T: 4.441454588925588E-4\nPressure measured with wall collisions: 4.4036995403253654E-4\n\nPressure measured with P V = n R T: 5.251377268433578E-4\nPressure measured with wall collisions: 4.385114019830638E-4\n\nPressure measured with P V = n R T: 4.931824176831048E-4\nPressure measured with wall collisions: 4.3656839984208926E-4\n\nPressure measured with P V = n R T: 6.345006963980435E-4\nPressure measured with wall collisions: 4.3819347783853905E-4\n\nPressure measured with P V = n R T: 5.26662616889756E-4\nPressure measured with wall collisions: 4.3843233793566013E-4\n\nPressure measured with P V = n R T: 4.024926450876052E-4\nPressure measured with wall collisions: 4.378203542088311E-4\n\nPressure measured with P V = n R T: 6.089323091252579E-4\nPressure measured with wall collisions: 4.3764997179323103E-4\n\nThe pressure results from the P V = n R T formula and from the measurement based on wall collisions are similar, with small differences.","support_files":[],"metadata":{"number":"6.11","chapter":6,"chapter_title":"Context","section":6.1,"section_title":"Collision Simulation","type":"Exercise","code_execution":false}} {"question":"Instrument the priority queue and test Pressure at various temperatures to identify the computational bottleneck. If warranted, try switching to a different priority-queue implementation for better performance at high temperatures.","answer":"Tests done with a random baseline temperature T, 100 * T, 10000 * T, 1000000 * T and 100000000 * T.\nThe standard priority queue was used to test all the temperatures.\nThe index priority queue was also used to test the highest temperatures: 1000000 * T and 100000000 * T.\n\nResults:\n\n**** Standard priority queue tests ****\n\nTesting with temperature: 5.817661439511093E12\nTotal time spent on insert operations: 0.02200\nTotal time spent on deleteMin operations: 0.01300\nTotal time spent on isEmpty operations: 0.00200\nComputational bottleneck: insert operations\n\nTesting with temperature: 8.270951314920601E14\nTotal time spent on insert operations: 0.00700\nTotal time spent on deleteMin operations: 0.01400\nTotal time spent on isEmpty operations: 0.00000\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.2709513149206064E16\nTotal time spent on insert operations: 0.00800\nTotal time spent on deleteMin operations: 0.01500\nTotal time spent on isEmpty operations: 0.00300\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.2709513149206047E18\nTotal time spent on insert operations: 0.01900\nTotal time spent on deleteMin operations: 0.06700\nTotal time spent on isEmpty operations: 0.00300\nComputational bottleneck: delete min operations\n\nTesting with temperature: 8.270951314920604E20\nTotal time spent on insert operations: 0.04700\nTotal time spent on deleteMin operations: 0.12100\nTotal time spent on isEmpty operations: 0.02500\nComputational bottleneck: delete min operations\n\n**** Index priority queue tests ****\n\nTesting with temperature: 6.3274920297362524E18\nTotal time spent on insert operations: 0.00900\nTotal time spent on deleteMin operations: 0.00500\nTotal time spent on isEmpty operations: 0.00000\nTotal time spent on contains operations: 0.00300\nTotal time spent on min operations: 0.00100\nTotal time spent on delete operations: 0.00400\nComputational bottleneck: insert operations\n\nTesting with temperature: 6.327492029736252E20\nTotal time spent on insert operations: 0.00600\nTotal time spent on deleteMin operations: 0.00700\nTotal time spent on isEmpty operations: 0.00000\nTotal time spent on contains operations: 0.00300\nTotal time spent on min operations: 0.00200\nTotal time spent on delete operations: 0.00500\nComputational bottleneck: deleteMin operations\n\nFor the standard priority queue on a lower temperature the computational bottleneck were the insert operations. However, for all higher temperatures, the computational bottleneck were the deleteMin operations.\nFor the index priority queue the computational bottleneck were also both the insert and deleteMin operations. In the first test the computational bottleneck were the insert operations. In the second test, with a higher temperature, the computational bottleneck were the deleteMin operations.","support_files":[],"metadata":{"number":"6.13","chapter":6,"chapter_title":"Context","section":6.1,"section_title":"Collision Simulation","type":"Exercise","code_execution":false}} {"question":"Suppose that, in a three-level tree, we can afford to keep a links in internal memory, between b and 2b links in pages representing internal nodes, and between c and 2c items in pages representing external nodes. What is the maximum number of items that we can hold in such a tree, as a function of a, b, and c?","answer":"The maximum number of items that we can hold in such a tree is achieved when there are \"a\" links in internal memory (the links between the first and second level of the tree), 2b links in pages representing internal nodes (the highest branching possible) and 2c items in pages representing external nodes (the highest number of items per external node).\n\nMaximum number of items = a * 2b * 2c","support_files":[],"metadata":{"number":"6.14","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"Estimate the average number of probes per search in a B-tree for S random searches, in a typical cache system, where the T most-recently-accessed pages are kept in memory (and therefore add 0 to the probe count). Assume that S is much larger than T.","answer":"As seen on Proposition B, a search in a B-tree of order M with N items requires between log M N and log M/2 N probes.\n\nConsidering that:\n1- We are evaluating the example given in Proposition B, with M = 1000 and N less than 62.5 billion, where the number of probes is less than 4. This means that the B-tree has height 3.\n2- The average number of probes per search when the target page is not in memory is 2 (which is 3 / 2 rounded up).\n3- T (the number of most-recently accessed pages) is 5% of S (the number of random searches).\n4- There are already T pages in memory.\n\nAverage number of probes = 0 * 0.05 / (0.05 + 0.95) + 2 * 0.95 / (0.05 + 0.95)\nAverage number of probes = 0 * 0.05 + 2 * 0.95\nAverage number of probes = 2 * 0.95\nAverage number of probes = 1.9\n\nThe average number of probes per search in this B-tree is 1.9.","support_files":[],"metadata":{"number":"6.18","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"Consider the sibling split (or B*-tree) heuristic for B-trees: When it comes time to split a node because it contains M entries, we combine the node with its sibling. If the sibling has k entries with k < M - 1, we reallocate the items giving the sibling and the full node each about (M+k)/2 entries. Otherwise, we create a new node and give each of the three nodes about 2M/3 entries. Also, we allow the root to grow to hold about 4M/3 items, splitting it and creating a new root node with two entries when it reaches that bound. State bounds on the number of probes used for a search or an insertion in a B*-tree of order M with N items. Compare your bounds with the corresponding bounds for B-trees (see PROPOSITION B). Develop an insert implementation for B*-trees.","answer":"6.20 - B* trees\n\nBounds on the number of probes used for a search or an insertion in a B*-tree of order M with N items:\nBetween log(M) N and log(2M/3) N probes.\nThis is because almost all internal nodes of the tree have between 2M / 3 and M - 1 links, since they are formed from a split of a full node with M keys and can only grow in size. \nThe only exception in which an internal node can have less than 2M / 3 links is when a node's child keys are reallocated with the creation of a new child node and its rightmost child does not get allocated enough entries. This happens when there are K keys to be reallocated to C child nodes and K / C < 2M / 3.\n\nAs seen in Proposition B, the bounds on the number of probes used for a search or an insertion in a B-tree of order M with N items is between log(M) N and log(M/2) N probes.\nSince log(2M/3) N < log(M/2) N, B*-trees are more efficient for both search and insert operations. This efficiency comes with a tradeoff that the split() operation, which has a runtime complexity of O(M / 2) in B-trees, changes its runtime complexity to O(M^2).","support_files":[],"metadata":{"number":"6.20","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"Write a program to compute the average number of external pages for a B-tree of order M built from N random insertions into an initially empty tree. Run your program for reasonable values of M and N.","answer":"Results:\n\n Order M | Number of items | AVG Number of External Pages\n 4 100000 42865\n 4 1000000 428592\n 4 10000000 4276006\n 16 100000 9424\n 16 1000000 94288\n 16 10000000 940648\n 64 100000 2277\n 64 1000000 22822\n 64 10000000 227472\n 256 100000 542\n 256 1000000 5650\n 256 10000000 57418\n\nAs expected, the higher the value of the order (M), the lower the number of external pages in the B-tree.\nAlso, when comparing experiments with the same order (M) but with different number of items (N), the higher the number of items, the higher the number of external pages in the B-tree.","support_files":[],"metadata":{"number":"6.21","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"If your system supports virtual memory, design and conduct experiments to compare the performance of B-trees with that of binary search, for random searches in a huge symbol table.","answer":"Results:\n\nNumber of searches | B-tree time | Binary search time\n 1000 0.005 0.001\n 100000 0.082 0.013\n 10000000 6.352 0.910\n\nFor random searches in a huge symbol table (with 10,000,000 entries) binary search has a better performance than B-trees.\n\nReference related to virtual memory in macs:\nhttps://www.howtogeek.com/319151/why-you-shouldnt-turn-off-virtual-memory-on-your-mac/","support_files":[],"metadata":{"number":"6.22","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"For your internal-memory implementation of Page in EXERCISE 6.15, run experiments to determine the value of M that leads to the fastest search times for a B-tree implementation supporting random search operations in a huge symbol table. Restrict your attention to values of M that are multiples of 100.","answer":"Results:\n\n Order M | Number of searches | Total time\n 100 1000 0.005\n 100 100000 0.198\n 100 10000000 19.973\n 200 1000 0.002\n 200 100000 0.195\n 200 10000000 18.331\n 400 1000 0.003\n 400 100000 0.188\n 400 10000000 17.533\n 1000 1000 0.002\n 1000 100000 0.176\n 1000 10000000 16.818\n 1500 1000 0.002\n 1500 100000 0.162\n 1500 10000000 15.784\n 2000 1000 0.003\n 2000 100000 0.205\n 2000 10000000 17.821\n\nThe value of M (order) that leads to the fastest search times for a B-tree doing random search operations in a huge symbol table (with 10,000,000 entries) is 1500.","support_files":[],"metadata":{"number":"6.23","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"Run experiments to compare search times for internal B-trees (using the value of M determined in the previous exercise), linear probing hashing, and red-black trees for random search operations in a huge symbol table.","answer":"Results:\n\nNumber of searches | B-tree time | Linear probing hashing time | Red-Black tree time\n 1000 0.004 0.001 0.002\n 100000 0.173 0.019 0.114\n 10000000 16.659 1.931 11.297\n\nOn the experiments using B-trees with order 1500, linear probing hashing and red-black trees for random searches in a huge symbol table (with 10,000,000 entries), the best search performance by far was achieved by linear probing hashing, which took 1.931 seconds to search 10 million random keys.\nIt was followed by red-black trees, with 11.297 seconds to search 10 million random keys. B-trees had the worst search performance, taking 16.659 seconds to do the same searches.\nSuch results can be explained by the fact that linear probing hashing perform searches in O(1) while B-trees perform searches in O(log(M/2) N) - O(log(750) N) in this case - and red-black trees perform searches in O(lgN).","support_files":[],"metadata":{"number":"6.24","chapter":6,"chapter_title":"Context","section":6.2,"section_title":"B-Trees","type":"Exercise","code_execution":false}} {"question":"Give, in the style of the figure on page 882, the suffixes, sorted suffixes, index() and lcp() tables for the following strings:\na. abacadaba\nb. mississippi\nc. abcdefghij\nd. aaaaaaaaaa","answer":"a. abacadaba\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 abacadaba 0 8 0 a\n1 bacadaba 1 6 1 aba\n2 acadaba 2 0 3 abacadaba\n3 cadaba 3 2 1 acadaba\n4 adaba 4 4 1 adaba\n5 daba 5 7 0 ba\n6 aba 6 1 2 bacadaba\n7 ba 7 3 0 cadaba\n8 a 8 5 0 daba\n\nb. mississippi\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n 0 mississippi 0 10 0 i\n 1 ississippi 1 7 1 ippi\n 2 ssissippi 2 4 1 issippi\n 3 sissippi 3 1 4 ississippi\n 4 issippi 4 0 0 mississippi\n 5 ssippi 5 9 0 pi\n 6 sippi 6 8 1 ppi\n 7 ippi 7 6 0 sippi\n 8 ppi 8 3 2 sissippi\n 9 pi 9 5 1 ssippi\n10 i 10 2 3 ssissippi\n\nc. abcdefghij\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 abcdefghij 0 0 0 abcdefghij\n1 bcdefghij 1 1 0 bcdefghij\n2 cdefghij 2 2 0 cdefghij\n3 defghij 3 3 0 defghij\n4 efghij 4 4 0 efghij\n5 fghij 5 5 0 fghij\n6 ghij 6 6 0 ghij\n7 hij 7 7 0 hij\n8 ij 8 8 0 ij\n9 j 9 9 0 j\n\nd. aaaaaaaaaa\n\nsuffixes sorted suffix array\n i index(i) lcp(i)\n0 aaaaaaaaaa 0 9 0 a\n1 aaaaaaaaa 1 8 1 aa\n2 aaaaaaaa 2 7 2 aaa\n3 aaaaaaa 3 6 3 aaaa\n4 aaaaaa 4 5 4 aaaaa\n5 aaaaa 5 4 5 aaaaaa\n6 aaaa 6 3 6 aaaaaaa\n7 aaa 7 2 7 aaaaaaaa\n8 aa 8 1 8 aaaaaaaaa\n9 a 9 0 9 aaaaaaaaaa","support_files":[],"metadata":{"number":"6.25","chapter":6,"chapter_title":"Context","section":6.3,"section_title":"Suffix Arrays","type":"Exercise","code_execution":false}} {"question":"Identify the problem with the following code fragment to compute all the suffixes for suffix sort:\nsuffix = \"\";\nfor (int i = s.length() - 1; i >= 0; i--)\n{\n suffix = s.charAt(i) + suffix;\n suffixes[i] = suffix;\n}","answer":"The problem with the code fragment is that if the substring() method takes linear time and space (which is the case in Java 7) the loop will take quadratic time and space. This wouldn't be a problem in Java 6, where the substring() method takes constant time and space (which would lead to a linear time and space loop).","support_files":[],"metadata":{"number":"6.26","chapter":6,"chapter_title":"Context","section":6.3,"section_title":"Suffix Arrays","type":"Exercise","code_execution":false}} {"question":"Under the assumptions described in SECTION 1.4. give the memory usage of a SuffixArray object with a string of length N.","answer":"Suffix\n* object overhead -> 16 bytes\n* String reference (text) -> 8 bytes\n* int value (index) -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 8 + 4 + 4 = 32 bytes\n\nSuffixArray\n* object overhead -> 16 bytes\n* Suffix[] (suffixes)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n int value (padding) -> 4 bytes\n Suffix references -> 8N bytes\n N Suffixes -> 32N bytes\nAmount of memory needed: 16 + 16 + 4 + 4 + 8N + 32N = 40N + 40 bytes","support_files":[],"metadata":{"number":"6.29","chapter":6,"chapter_title":"Context","section":6.3,"section_title":"Suffix Arrays","type":"Exercise","code_execution":false}} {"question":"Write a SuffixArray client LCS that take two file-names as command-line arguments, reads the two text files, and finds the longest substring that appears in both in linear time. (In 1970, D. Knuth conjectured that this task was impossible.) Hint: Create a suffix array for s#t where s and t are the two text strings and # is a character that does not appear in either.","answer":"Suffix array with Suffix class:\nRunning time: O(N^2), but on average runs in 2N ln N (as seen in the book, on chapter 6, proposition C). The worst case happens when sorting the suffixes of a string consisting of N copies of the same character, or already sorted suffixes.\nMemory: 40N + 40 bytes (as seen on exercise 6.29)\n\nSuffix array without Suffix class:\nRunning time: O(N * w * logR), where w is the suffix' average length and R is the alphabet size. For suffix arrays this is equal to O(N * N/2 * log256) = O(N^2) character compares. The worst case happens when sorting the suffixes of a string consisting of N copies of the same character. On average it runs in 2N ln N character compares (as seen in the book, on chapter 5, proposition E).\nMemory: \nSuffixArrayNoInnerClass\n* object overhead -> 16 bytes\n* char[] reference (textChars) -> 8 bytes\n* char[] (textChars)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n char items -> 2N\n* int[] reference (indexes) -> 8 bytes\n* int[] (indexes)\n object overhead -> 16 bytes\n int value (length) -> 4 bytes\n padding -> 4 bytes\n int items -> 4N\n* int value (textLength) -> 4 bytes\n* padding -> 4 bytes\nAmount of memory needed: 16 + 8 + 16 + 4 + 4 + 2N + 8 + 16 + 4 + 4 + 4N + 4 + 4 = 6N + 88 bytes\n\nThe running time of the suffix array implementation without Suffix class is better than the running time of the implementation using Suffix class. The former has a worst case of O(N^2) character compares while the latter has a worst case of O(N^2) key compares. Also, on average the suffix array implementation without Suffix class has a runtime of 2N ln N character compares while the implementation using Suffix class has an average runtime of 2N ln N key compares. The difference becomes clearer when dealing with suffixes that have long common prefixes, where the implementation without Suffix class does not have to re-compare such prefixes during the sort.\nIn terms of memory usage, the suffix array implementation without Suffix class uses less memory (6N + 88 bytes) than the implementation using Suffix class (40N + 40 bytes).\nOverall the suffix array implementation without Suffix class is better than the implementation with Suffix class in both running time and memory usage.","support_files":[],"metadata":{"number":"6.30","chapter":6,"chapter_title":"Context","section":6.3,"section_title":"Suffix Arrays","type":"Exercise","code_execution":false}} {"question":"If capacities are positive integers less than M, what is the maximum possible flow value for any st-network with V vertices and E edges? Give two answers, depending on whether or not parallel edges are allowed.","answer":"Maximum possible flow value for any st-network with V vertices and E edges (with positive integer capacities less than M):\nConsider C to be the highest possible edge capacity.\n\n1- Parallel edges not allowed\nMax flow = (V - 2) * C\nIn this case, since parallel edges are not allowed, each vertex other than the source and the target is connected to them through 2 edges of flow and capacity C.\n\n s\nC/C / |C/C \\ C/C\n v v v\n 1 2 3\nC/C \\ |C/C /\n v v v\n t\n\n2- Parallel edges allowed\nMax flow = E * C\nIn this case, with parallel edges allowed, the source vertex can be directly connected to the target vertex through E parallel edges, each with flow and capacity C.\n\n s\n C/C / |C/C \\ C/C\n v v v\n t","support_files":[],"metadata":{"number":"6.36","chapter":6,"chapter_title":"Context","section":6.4,"section_title":"Maxflow","type":"Exercise","code_execution":false}} {"question":"Give an algorithm to solve the maxflow problem for the case that the network forms a tree if the sink is removed.","answer":"If the network forms a tree if the sink is removed this means that there are no directed cycles in the network. In other words, intermediate vertices are not directly connected: for each edge e (v->w), either v or w must be the source or the sink vertex.\nA situation like this would happen:\n\nOriginal network:\n\n s\nc/f / |c/f \\ c/f\n v v v\n 1 2 3\nc/f| |c/f /\n v v /\n 4 5 / c/f\nc/f \\ |c/f/\n v v v\n t\n\nTree formed after removing the sink vertex:\n\n s\n c/f/ |c/f\\ c/f\n v v v\n 1 2 3\nc/f| |c/f\n v v\n 4 5\n\nIn this case the maxflow can be computed with the following algorithm:\n For each vertex adjacent to the source:\n Do a depth first search until reaching the sink vertex. Keep track of the minimum edge capacity on the path.\n Maxflow will be equal to the sum of all the minimum edge capacities computed.\n Return maxflow.","support_files":[],"metadata":{"number":"6.37","chapter":6,"chapter_title":"Context","section":6.4,"section_title":"Maxflow","type":"Exercise","code_execution":false}} {"question":"If true provide a short proof, if false give a counterexample:\na. In any max flow, there is no directed cycle on which every edge carries positive flow\nb. There exists a max flow for which there is no directed cycle on which every edge carries positive flow\nc. If all edge capacities are distinct, the max flow is unique\nd. If all edge capacities are increased by an additive constant, the min cut remains unchanged\ne. If all edge capacities are multiplied by a positive integer, the min cut remains unchanged","answer":"6.38 - True of false\n\na. In any max flow, there is no directed cycle on which every edge carries positive flow.\nFalse.\nCounterexample:\n\n s\n | ^\n2/2| |1/1\n v |\n 1\n |\n |1/1\n v\n t\n\nb. There exists a max flow for which there is no directed cycle on which every edge carries positive flow.\nTrue.\nProof: Let f be a maximum flow and let C be a cycle on which every edge carries positive flow.\nLet g = min(e E C) f(e). In other words, g is equal to the value of the minimum edge flow among the edges in cycle C.\nReducing the flow of each edge in C by g maintains the value of the max flow and sets the flow f(e) of at least one of the edges e E C to zero.\n\nc. If all edge capacities are distinct, the max flow is unique.\nFalse.\nCounterexample:\n\n s\n | 1/1\n |\n v\n 1\n |\n / \\\n2/0 / |\n v |\n 2 | 3/1\n \\ |\n4/0 \\ |\n v v\n t\n\n s\n | 1/1\n |\n v\n 1\n |\n / \\\n2/1 / |\n v |\n 2 | 3/0\n \\ |\n4/1 \\ |\n v v\n t\n\nd. If all edge capacities are increased by an additive constant, the min cut remains unchanged.\nFalse.\nCounterexample:\n\noriginal network:\n\n s\n | 4/3\n v\n 1\n 1/1/ |1/1 \\ 1/1 <- min cut\n v v v\n \\ | /\n1/1 \\ |1/1 / 1/1\n v v v\n t\n\nAfter adding a constant value of 1 to all edge capacities:\n\n s\n | 5/3 <- min cut\n v\n 1\n 2/1/ |2/1 \\ 2/1\n v v v\n \\ | /\n2/1 \\ |2/1 / 2/1\n v v v\n t\n\ne. If all edge capacities are multiplied by a positive integer, the min cut remains unchanged.\nTrue.\nProof: Let g be the positive integer for which every edge capacity is multiplied.\nWhen all edge capacities are multiplied by g the value of every cut also gets multiplied by g.\nThus, the relative order of the cuts does not change and the min cut before the multiplication will remain the min cut after it.\n\nReferences:\nhttp://algo2.iti.kit.edu/sanders/courses/algdat03/sol3.pdf\nhttps://stackoverflow.com/questions/40277603/is-minimum-cut-same-for-the-graph-after-increasing-edge-capacity-by-1-for-all-ed","support_files":[],"metadata":{"number":"6.38","chapter":6,"chapter_title":"Context","section":6.4,"section_title":"Maxflow","type":"Exercise","code_execution":false}} {"question":"Complete the proof of PROPOSITION G: Show that each time an edge is a critical edge, the length of the augmenting path through it must increase by 2.","answer":"Proposition: Each time an edge is a critical edge, the length of the augmenting path through it must increase by 2.\nProof:\nLet df(vertex1, vertex2) be the augmenting path distance from vertex 1 to vertex 2.\n\nWhen edge (u, v) is critical this means that:\ndf(s, v) = df(s, u) + 1 (since augmenting paths are shortest paths)\n\nBefore becoming a critical edge again, (u, v) must be added back by some augmenting path, which must contain it.\nLet df' be the augmenting path distance when (u, v) is added back.\n\ndf'(s, u) = df'(s, v) + 1 (since edge (u, v) was removed, to add it back it is necessary to reach it from vertex v).\ndf'(s, v) + 1 >= df(s, v) + 1 (since df'(s, v) is in an augmenting path found after the augmenting path in which df(s, v) is, it cannot have a distance lower than df(s, v)).\ndf(s, v) + 1 = df(s, u) + 1 + 1 (replace df(s, v) by df(s, u) + 1, according to the above definition).\n\nThis means that df'(s, u) = df(s, u) + 2.\nTherefore, the length of the augmenting path through a re-added critical edge must increase by 2.\n\nReference:\nhttps://www.cs.usfca.edu/~galles/cs673/lecture/lecture18.pdf","support_files":[],"metadata":{"number":"6.39","chapter":6,"chapter_title":"Context","section":6.4,"section_title":"Maxflow","type":"Exercise","code_execution":false}} {"question":"Prove that the shortest-paths problem reduces to linear programming.","answer":"Reduction from shortest paths problem to linear programming:\n\nMethod 1:\nWe consider a system of inequalities and equations that involve the following variables:\nl(u,v) -> variable corresponding to the length of the directed edge u -> v.\nx(u,v) -> indicator variable for whether edge u -> v is in the shortest path. It has value 1 when the edge is, and 0 when the edge is not.\n\nGiven a directed graph G with a source vertex s and a target vertex t.\n\nLinear programming formulation:\n\n Minimize E l(u,v) * x(u,v)\n u->v\n\nSubject to the constraints\n\n E x(s,v) - E x(v,s) = 1\n v v\n\n E x(t,v) - E x(v,t) = -1\n v v\n\nfor every vertex u other than s and t:\n E x(u,v) - E x(v,u) = 0\n v v\n\n x(u,v) >= 0 for every edge u -> v\n\nThe constraints state that the path should start at s, end at t, and either pass through or avoid every other vertex v.\nThis selects the set of edges with minimal length, subject to the constraint that this set forms a path from s to t - represented by the constraints that ensure that for all vertices except s and t the number of incoming and outcoming edges that are part of the path must be the same.\n\nThe solution is easily converted to a solution of the shortest paths problem: the edges u -> v for which x(u,v) is equal to 1 are part of the shortest path and the sum of all their lengths is the length of the shortest path from s to t.\n\nMethod 2:\nWe consider a system of inequalities and equations that involve the following variables:\nd(v) -> variable corresponding to the shortest distance from s to vertex v.\nl(u,v) -> variable corresponding to the length of the directed edge u -> v.\n\nGiven a directed graph G with a set of vertices V, a set of edges E and with a source vertex s and a target vertex t.\n\nLinear programming formulation:\n\n Maximize d(t)\n\nSubject to the constraints\n\n d(s) = 0\n d(v) - d(u) <= l(u,v) for every edge u -> v\n\nThe constraints state that in a shortest path from s to t, d(v) is at most the shortest path distance from s to v. And the value of d(t) will be the shortest path distance from s to t.\nTo find the edges in the shortest path from s to t, the following method can be used:\nPre-process the edges to map each vertex with its incoming edges.\nStarting with vertex t, check which incoming neighbor vertex v has d(v) equal to d(t) - l(v,t).\nAdd the edge v -> t to the shortest path. Replace t with v and do the same check for its incoming neighbors, iterating this process until vertex s is reached.\n\nTo compute the shortest paths from s to every other vertex, the following linear programming formulation can be used:\n\n Maximize E d(v)\n v\n\nSubject to the constraints\n\n d(s) = 0\n d(v) - d(u) <= l(u,v) for every edge u -> v\n\nThe resulting values of d(v) will be the shortest path distances from s to every vertex v.\nTo find the edges in the shortest path from s to any vertex v, the same process mentioned above can be used, replacing vertex t with vertex v.\n\nTo compute the shortest paths from all vertices to every other vertex (all-pairs shortest paths), the following linear programming formulation can be used:\n\nd(u,v) -> variable corresponding to the shortest distance from vertex u to vertex v.\n\n Maximize E d(u,v)\n v\n\nSubject to the constraints\n\n d(v,v) = 0 for every vertex v\n d(u,w) - d(u,v) <= l(v,w) for every vertex u in V and every edge v -> w in E\n\nThe resulting values of d(u,v) will be the shortest path distances from every vertex u to every vertex v.\nTo find the edges in the shortest paths from every vertex u to every vertex v, the same process mentioned above can be used, replacing vertex t with vertex v and vertex s with vertex u.\n\nReferences:\nhttps://en.wikipedia.org/wiki/Shortest_path_problem#Linear_programming_formulation\nhttps://courses.engr.illinois.edu/cs498dl1/sp2015/notes/26-lp.pdf\nhttp://www.cs.yale.edu/homes/aspnes/pinewiki/attachments/LinearProgramming/lp.pdf","support_files":[],"metadata":{"number":"6.50","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Could there be an algorithm that solves an NP-complete problem in an average time of NlogN, if P != NP? Explain your answer.","answer":"Could there be an algorithm that solves an NP-complete problem in an average time of N^(log n), if P != NP? Explain your answer.\n\nYes, there could be, it is not possible to affirm either yes or no.\nAn algorithm of average time N^(log n) does not belong to either P or NP, it is part of an intermediate class of algorithms called quasi-polynomial (QP). Quasi-polynomial time algorithms are algorithms that run slower than polynomial time, yet not so slow as to be exponential time.\nIf P != NP this would mean that there is no polynomial time algorithm that can solve an NP-complete problem.\nIt could still be possible that QP = NP (or not).","support_files":[],"metadata":{"number":"6.51","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that someone discovers an algorithm that is guaranteed to solve the boolean satisfiability problem in time proportional to 1.1^N. Does this imply that we can solve other NP-complete problems in time proportional to 1.1^N?","answer":"Yes, if the algorithm can guarantee to solve the boolean satisfiability problem in time proportional to 1.1^N this implies that it can solve other NP-complete problems in time proportional to 1.1^N.\nThis is because boolean satisfiability is an NP-complete problem and due to that all problems in NP polynomially reduce to it.","support_files":[],"metadata":{"number":"6.52","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"What would be the significance of a program that could solve the integer linear programming problem in time proportional to 1.1^N?","answer":"A program that could solve the integer linear programming problem in time proportional to 1.1^N would signify that it can also solve any other problem in NP in time proportional to 1.1^N (this is because the integer linear programming problem is an NP-complete problem and due to that all problems in NP polynomially reduce to it).\n1.1^N is still exponential running time, so it does not prove anything related to P = NP, but it would mean that we can solve instances of any problem in NP of size up to ~218 efficiently.\n\nReference:\nhttps://www.ics.uci.edu/~eppstein/265/exponential.html","support_files":[],"metadata":{"number":"6.53","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Give a poly-time reduction from vertex cover to 0-1 integer linear inequality satisfiability.","answer":"Poly-time reduction from vertex cover to 0-1 integer linear inequality satisfiability:\n\nWe consider a system of inequalities and equations that involve the following variables:\nx(v) -> binary variable that is equal to 1 if vertex v is selected and 0 otherwise.\n\nGiven a graph G with a set of vertices V and a set of edges E.\n\nLinear programming formulation:\n\n Minimize E x(v)\n veV\n\nSubject to the constraints\n\n x(u) + x(v) >= 1 for every edge u - v in E\n x(v) e {0, 1} for every vertex v in V\n\nVertices with x(v) equal to 1 will be the vertices in the minimum vertex cover.\n\nReference:\nhttps://cs.stackexchange.com/questions/68232/reduction-vertex-cover-to-binary-integer-program-decision-problem","support_files":[],"metadata":{"number":"6.54","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Prove that the problem of finding a Hamiltonian path in a directed graph is NP-complete, using the NP-completeness of the Hamiltonian-path problem for undirected graphs.","answer":"Prove that the problem of finding a Hamiltonian path in a directed graph is NP-complete, using the NP-completeness of the Hamiltonian path problem for undirected graphs.\n\nLet's call the Hamiltonian path problem in undirected graphs HPg and the Hamiltonian path problem in directed graphs HPdg.\n\nReduction from HPg to HPdg:\nReplace every edge v - w in the undirected graph in HPg to two directed edges in the directed graph in HPdg:\nA v -> w directed edge and a w -> v directed edge.\nSolve HPdg.\nThe directed edges selected in the solution to HPdg can be mapped to the edges in the solution to HPg:\nIf either v -> w or w -> v are in HPdg solution, v - w is in HPg solution.\n\nA problem is NP-complete if it is in NP and all problems in NP poly-time reduce to it.\nHPdg is in NP because if given a Hamiltonian path as a solution, it is possible to check if all vertices are visited in polynomial time.\nSince HPg is NP-complete, all problems in NP poly-time reduce to it.\nAs seen above, there is a poly-time reduction from HPg to HPdg. By transitive relation this shows that all problems in NP poly-time reduce to HPdg, and it is, therefore, NP-complete.\n\n All problems in NP\n\n |\n V\n\n Hamiltonian path problem for undirected graphs\n\n |\n V\n\n Hamiltonian path problem for directed graphs","support_files":[],"metadata":{"number":"6.55","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that two problems are known to be NP-complete. Does this imply that there is a poly-time reduction from one to the other?","answer":"Yes, if two problems are known to be NP-complete this implies that there is a poly-time reduction from one to the other.\nThis is because all problems in NP poly-time reduce to any NP-complete problem.\nAll NP-complete problems are in NP, therefore, both problems poly-time reduce from one to the other.","support_files":[],"metadata":{"number":"6.56","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that X is NP-complete, X poly-time reduces to Y, and Y poly-time reduces to X. Is Y necessarily NP-complete?","answer":"Suppose that X is NP-complete, X poly-time reduces to Y, and Y poly-time reduces to X. Is Y necessarily NP-complete?\n\nFor Y to be NP-complete the following conditions must be met:\n1) Y is in NP\n2) Every problem in NP poly-time reduces to Y\n\nCondition 2 is true because X poly-time reduces to Y, and since X is NP-complete, all problems in NP poly-time reduce to it (and transitively to Y).\nNothing is said about condition 1, so Y is not necessarily NP-complete. It may be the case that Y is not in NP because it is not possible to verify if a given solution to it is correct or not in polynomial time. In this case (with condition 2 satisfied but condition 1 not satisfied) Y would be NP-hard, but not NP-complete.\nFor example if X = CIRCUIT-SAT and Y = CO-CIRCUIT-SAT then X and Y are equal to the problem description, but it is unknown whether Y is in NP.\nThis answer is based on the definition of reductions as polynomial-time Turing reductions (and not Karp reductions).\n\nReference:\nhttps://algs4.cs.princeton.edu/66intractability/","support_files":[],"metadata":{"number":"6.57","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that we have an algorithm to solve the decision version of boolean satisfiability, which indicates that there exists an assignment of truth values to the variables that satisfies the boolean expression. Show how to find the assignment.","answer":"Given an algorithm that solves the decision version of boolean satisfiability - which indicates whether there exists an assignment of truth values to the variables that satisfies a boolean expression - the assignment can be found with the following method:\n\nConsider a boolean expression BE composed by a set of distinct variables x1, x2, ..., xn.\n\n1- Use the algorithm to check if it is possible to satisfy BE.\nIf the answer is no, the expression is not satisfiable and there is no possible assignment.\nIf the answer is yes:\n2- Assign the value true to x1 and use the algorithm to check if it is possible to satisfy BE.\n3- If the answer is yes, then x1 is equal to true. Otherwise, x1 is equal to false, so update its value.\n4- Repeat steps 2 and 3 for all other variables.\n\nIn total, all variable assignments can be found in n + 1 runs of the algorithm, where n is number of distinct variables in BE.\n\nReference:\nhttps://en.wikipedia.org/wiki/Boolean_satisfiability_problem#Self-reducibility","support_files":[],"metadata":{"number":"6.58","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that we have an algorithm to solve the decision version of the vertex cover problem, which indicates that there exists a vertex cover of a given size. Show how to solve the optimization version of finding the vertex cover of minimum cardinality.","answer":"Given an algorithm that solves the decision version of the vertex cover problem - which indicates that there exists a vertex cover of a given size - the optimization version of finding the vertex cover of minimum cardinality can be solved with the following method:\n\nConsider a graph G with V vertices and E edges.\n\n1- Using the algorithm, binary search for k, the cardinality of the minimum vertex cover.\n2- Find a vertex v such that G - {v} (removing the vertex and its incident edges) has a vertex cover of size k - 1. Any vertex in any minimum vertex cover will have this property.\n3- Include v in the vertex cover.\n4- Recursively find a minimum vertex cover in G - {v}. The stop condition is when there is no vertex whose removal leads to a smaller vertex cover.\n\nReference:\nhttps://www.cs.princeton.edu/~wayne/kleinberg-tardos/pearson/08Intractability.pdf","support_files":[],"metadata":{"number":"6.59","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Explain why the optimization version of the vertex cover problem is not necessarily a search problem.","answer":"The optimization version of the vertex cover problem is not necessarily a search problem because its output (a vertex cover of minimum cardinality) cannot be certified to be correct in polynomial time. It is possible to certify in polynomial time that the output is a vertex cover, but not that it is a minimum cardinality vertex cover.","support_files":[],"metadata":{"number":"6.60","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that X and Y are two search problems and that X poly-time reduces to Y. Which of the following can we infer?\na. If Y is NP-complete then so is X.\nb. If X is NP-complete then so is Y.\nc. If X is in P, then Y is in P.\nd. If Y is in P, then X is in P.","answer":"If X and Y are two search problems and X poly-time reduces to Y, we can infer that:\n\nb. If X is NP-complete then so is Y.\nThis is because if both X and Y are search problems they are both in NP.\nIf X is NP-complete, then all problems in NP poly-time reduce to it. And if X poly-time reduces to Y, then all problems in NP also poly-time reduce to Y (through X).\nSince Y is both in NP and all problems in NP poly-time reduce to it, Y is NP-complete.\n\nd. If Y is in P, then X is in P.\nIf Y is in P it can be solved in polynomial time. If we can reduce X to Y then we can solve Y in polynomial time and consequently solve X in polynomial time, meaning that X is also in P.\n\nThe following alternatives are wrong:\n\na. If Y is NP-complete then so is X.\nNot necessarily, there may not exist reductions from all problems in NP to X.\n\nc. If X is in P, then Y is in P.\nNot necessarily, Y may be NP-complete and currently it is unknown whether P = NP.","support_files":[],"metadata":{"number":"6.61","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}} {"question":"Suppose that P != NP. Which of the following can we infer?\ne. If X is NP-complete, then X cannot be solved in polynomial time.\nf. If X is in NP, then X cannot be solved in polynomial time.\ng. If X is in NP but not NP-complete, then X can be solved in polynomial time.\nh. If X is in P, then X is not NP-complete.","answer":"If P != NP, we can infer that:\n\na. If X is NP-complete, then X cannot be solved in polynomial time.\nIf P != NP, no NP-complete problem can be solved in polynomial time.\n\nd. If X is in P, then X is not NP-complete.\nIf P != NP, then problems in P can be solved in polynomial time whereas problems NP-complete cannot. So X cannot be both in P and NP-complete.\n\nThe following alternatives are wrong:\n\nb. If X is in NP, then X cannot be solved in polynomial time.\nNot necessarily, X can be in P, which is the class of problems that can be solved in polynomial time.\n\nc. If X is in NP but not NP-complete, then X can be solved in polynomial time.\nNot necessarily, X can be in an intermediate class between P and NP-complete, such as QP (quasi-polynomial). Quasi-polynomial time algorithms are algorithms that run slower than polynomial time, yet not so slow as to be exponential time.","support_files":[],"metadata":{"number":"6.62","chapter":6,"chapter_title":"Context","section":6.5,"section_title":"Reductions and Intractability","type":"Exercise","code_execution":false}}