question stringlengths 34 5.53k | answer stringlengths 21 101k | support_files listlengths 0 6 | metadata unknown |
|---|---|---|---|
Add a method isFull() to:
/******************************************************************************
* Compilation: javac FixedCapacityStackOfStrings.java
* Execution: java FixedCapacityStackOfStrings
* Dependencies: StdIn.java StdOut.java
*
* Stack of strings implementation with a fixed-size array.
... | /******************************************************************************
* Compilation: javac FixedCapacityStackOfStrings.java
* Execution: java FixedCapacityStackOfStrings
* Dependencies: StdIn.java StdOut.java
*
* Stack of strings implementation with a fixed-size array.
*
* % more tobe.txt
* ... | [
"https://algs4.cs.princeton.edu/13stacks/tobe.txt"
] | {
"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"
]
} |
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 [(]). | /******************************************************************************
* Compilation: javac Parentheses.java
* Execution: java Parentheses
* Dependencies: In.java Stack.java
*
* Reads in a text file and checks to see if the parentheses are balanced.
*
* % java Parentheses
* [()]{}{[()()]()}
... | [] | {
"number": "1.3.4",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Parentheses.java",
"params": [
"<<< \"[(])\"",
"<<< \"[()]{}{[()()]()}\""
],
"dependencies": [
"In.java",
"Stack.java"
]
} |
Add a method peek() that returns the most recently inserted item on the stack (without popping it) to:
/******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: h... | /******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic stack, implemented using a singly linke... | [
"https://algs4.cs.princeton.edu/13stacks/tobe.txt"
] | {
"number": "1.3.7",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Stack.java",
"params": [
"< tobe.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
Write a filter Program InfixToPostfix.java that converts an arithmetic expression from infix to postfix. | /******************************************************************************
* Compilation: javac InfixToPostfix.java
* Execution: java InfixToPostFix
* Dependencies: Stack.java StdIn.java StdOut.java
*
* Reads in a fully parenthesized infix expression from standard input
* and prints an equivalent po... | [] | {
"number": "1.3.10",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/InfixToPostfix.java",
"params": [
"<<EOF\n( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\nEOF",
"<<EOF\n( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )\nEOF"
],
"dependencies": [
"Stack.java",
"StdIn.j... |
Write a program EvaluatePostfix.java that that takes a postfix expression from standard input, evaluates it, and prints the value. | /******************************************************************************
* Compilation: javac EvaluatePostfix.java
* Execution: java EvaluatePostfix < file.txt
* Dependencies: Stack.java StdIn.java StdOut.java
*
* Evaluates postfix expresions using a stack.
*
* Windows users: replace [Ctrl-d] wit... | [] | {
"number": "1.3.11",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/EvaluatePostfix.java",
"params": [
"<<EOF\n3 4 5 + *\nEOF",
"<<EOF\n1 2 3 4 5 * + 6 * * +\nEOF",
"<<EOF\n7 16 16 16 * * * 5 16 16 * * 3 16 * 1 + + +\nEOF",
"<<EOF\n7 16 * 5 + 16 * 3 + 16 * 1 +\nEOF"
]... |
Develop a class ResizingArrayQueueOfStrings that implements the queue abstraction with a fixed-size array,
and then extend your implementation
to use array resizing
to remove the size restriction. | /******************************************************************************
* Compilation: javac ResizingArrayQueue.java
* Execution: java ResizingArrayQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Queue implementation wi... | [
"https://algs4.cs.princeton.edu/13stacks/tobe.txt"
] | {
"number": "1.3.14",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java",
"params": [
"< tobe.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
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... | /******************************************************************************
* Compilation: javac Josephus.java
* Execution: java Josephus m n
* Dependencies: Queue.java
*
* Solves the Josephus problem.
*
* % java Josephus 2 7
* 1 3 5 0 4 2 6
*
****************************************************... | [] | {
"number": "1.3.37",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Josephus.java",
"params": [
"2 7"
],
"dependencies": [
"Queue.java"
]
} |
Develop classes QuickUnionUF.java that implement quick-union. | /******************************************************************************
* Compilation: javac QuickUnionUF.java
* Execution: java QuickUnionUF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt
* https://algs4.cs.princeton.e... | [
"https://algs4.cs.princeton.edu/15uf/tinyUF.txt",
"https://algs4.cs.princeton.edu/15uf/mediumUF.txt"
] | {
"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"
]
} |
Develop classes QuickFindUF.java that implement quick-find. | /******************************************************************************
* Compilation: javac QuickFindUF.java
* Execution: java QuickFindUF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt
* https://algs4.cs.princeton.edu... | [
"https://algs4.cs.princeton.edu/15uf/tinyUF.txt",
"https://algs4.cs.princeton.edu/15uf/mediumUF.txt"
] | {
"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"
]
} |
Transaction sort test client. Write a class SortTransactions.java that consists of a static method main() that reads a sequence of transactions from standard
input, sorts them, and prints the result on standard output. | /******************************************************************************
* Compilation: javac SortTransactions.java
* Execution: java SortTransactions < input.txt
* Dependencies: StdOut.java
* Data file: https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt
*
* % java SortTransactions < tra... | [
"https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt"
] | {
"number": "2.1.22",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/21elementary/SortTransactions.java",
"params": [
"< tinyBatch.txt"
],
"dependencies": [
"StdOut.java"
]
} |
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 | /******************************************************************************
* Compilation: javac InsertionX.java
* Execution: java InsertionX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt
* https://algs4.cs.princet... | [
"https://algs4.cs.princeton.edu/21elementary/tiny.txt",
"https://algs4.cs.princeton.edu/21elementary/words3.txt"
] | {
"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"
]
} |
Insertion sort without exchanges. Develop an implementation InsertionX.java of insertion sort that moves larger items to the right one position rather
than doing full exchanges. | /******************************************************************************
* Compilation: javac InsertionX.java
* Execution: java InsertionX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt
* https://algs4.cs.princet... | [
"https://algs4.cs.princeton.edu/21elementary/tiny.txt",
"https://algs4.cs.princeton.edu/21elementary/words3.txt"
] | {
"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"
]
} |
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.java that
does not use a static array. | /******************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22me... | [
"https://algs4.cs.princeton.edu/22mergesort/tiny.txt",
"https://algs4.cs.princeton.edu/22mergesort/words3.txt"
] | {
"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"
]
} |
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 | /******************************************************************************
* Compilation: javac MergeX.java
* Execution: java MergeX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22... | [
"https://algs4.cs.princeton.edu/22mergesort/tiny.txt",
"https://algs4.cs.princeton.edu/22mergesort/words3.txt"
] | {
"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"
]
} |
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 | /******************************************************************************
* Compilation: javac Inversions.java
* Execution: java Inversions < input.txt
* Dependencies: StdIn.java StdOut.java
*
* Read array of n integers and count number of inversions in n log n time.
*
*****************************... | [
"https://algs4.cs.princeton.edu/14analysis/16Kints.txt",
"https://algs4.cs.princeton.edu/14analysis/1Kints.txt",
"https://algs4.cs.princeton.edu/14analysis/2Kints.txt",
"https://algs4.cs.princeton.edu/14analysis/32Kints.txt",
"https://algs4.cs.princeton.edu/14analysis/4Kints.txt",
"https://algs4.cs.prince... | {
"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"
]... |
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. | /******************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22me... | [
"https://algs4.cs.princeton.edu/22mergesort/tiny.txt",
"https://algs4.cs.princeton.edu/22mergesort/words3.txt"
] | {
"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"
]
} |
Write a program Sort2distinct.java that sorts an array that is known to contain just two distinct key values. | /******************************************************************************
* Compilation: javac Sort2distinct.java
* Execution: java Sort2distinct binary-string
* Dependencies: StdOut.java
*
* Partitions the array of specified as the command-line.
* Assumes there are at most 2 distinct elements.
*... | [] | {
"number": "2.3.5",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/Sort2distinct.java",
"params": [
"01001111011100111011011101001100",
"10110111001101111100001011011011",
"10110100010000111011000111110000",
"01110100010010011010011111001001",
"110001010010010111... |
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 pu... | /******************************************************************************
* Compilation: javac QuickBest.java
* Execution: java QuickBest n
* Dependencies: StdOut.java
*
* Generate a best-case input of size n for standard quicksort.
*
* % java QuickBest 3
* BAC
*
* % java QuickBest 7
* DACB... | [] | {
"number": "2.3.16",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/QuickBest.java",
"params": [
"3",
"7",
"15"
],
"dependencies": [
"StdOut.java"
]
} |
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 l... | /******************************************************************************
* Compilation: javac QuickBentleyMcIlroy.java
* Execution: java QuickBentleyMcIlroy < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt
* https:/... | [
"https://algs4.cs.princeton.edu/23quicksort/tiny.txt",
"https://algs4.cs.princeton.edu/23quicksort/words3.txt"
] | {
"number": "2.3.22",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/QuickBentleyMcIlroy.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
]
} |
Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap. | For a 1-based heap array `pq[1..n]`, scan every internal node and check only its children. That visits each parent-child edge once, so the running time is linear.
```java
public static boolean isMinHeap(Comparable[] pq, int n) {
for (int k = 1; k <= n / 2; k++) {
int left = 2 * k;
int right = left ... | [
"https://algs4.cs.princeton.edu/24pq/tinyPQ.txt"
] | {
"number": "2.4.15",
"code_execution": false
} |
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 p... | /******************************************************************************
* Compilation: javac CubeSum.java
* Execution: java CubeSum n
* Dependencies: MinPQ.java
*
* Print out integers of the form a^3 + b^3 in sorted order, where
* 0 <= a <= b <= n.
*
* % java CubeSum 12
* 0 = 0^3 + 0^3
* 1... | [] | {
"number": "2.4.25",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/24pq/CubeSum.java",
"params": [
"4",
"12"
],
"dependencies": [
"MinPQ.java"
]
} |
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. | /******************************************************************************
* Compilation: javac Interval1D.java
* Execution: java Interval1D
* Dependencies: StdOut.java
*
* 1-dimensional interval data type.
*
******************************************************************************/
package ed... | [] | {
"number": "2.5.27",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Interval1D.java",
"params": [
""
],
"dependencies": [
"StdOut.java"
]
} |
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. | /******************************************************************************
* Compilation: javac FileSorter.java
* Execution: java FileSorter directory-name
* Dependencies: StdOut.java
*
* Prints out all of the files in the given directory in
* sorted order.
*
* % java FileSorter .
*
***********... | [] | {
"number": "2.5.28",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/25applications/FileSorter.java",
"params": [
"."
],
"dependencies": [
"StdOut.java"
]
} |
Write a client
program GPA.java that creates a symbol table mapping letter grades to numerical
scores, as in the table below, then reads from standard input a list of letter
grades and computes and prints the GPA (the average of the numerical
scores of the corresponding grades). A+ A A- B+ B B- C... | /******************************************************************************
* Compilation: javac GPA.java
* Execution: java GPA < input.txt
* Dependencies: ST.java
*
* Create a symbol table mapping letter grades to numerical
* scores, then read a list of letter grades from standard input,
* and pri... | [] | {
"number": "3.1.1",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/GPA.java",
"params": [
"<<EOF\nA- B+ B+ B-\nEOF"
],
"dependencies": [
"ST.java"
]
} |
Develop a symbol-table implementation ArrayST.java that uses an (unordered) array as the underlying data structure to implement our basic symbol table API. | /******************************************************************************
* Compilation: javac ArrayST.java
* Execution: java ArrayST < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
*
* Symbol table implementation with uno... | [
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] | {
"number": "3.1.2",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/ArrayST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
Implement size(), delete(), and keys() for SequentialSearchST.java. | /******************************************************************************
* Compilation: javac SequentialSearchST.java
* Execution: java SequentialSearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation w... | [
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] | {
"number": "3.1.5",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/SequentialSearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
Implement the delete() method for BinarySearchST.java. | /******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with bina... | [
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] | {
"number": "3.1.16",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
Implement the floor() method for BinarySearchST.java . | /******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with bina... | [
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] | {
"number": "3.1.17",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
Certification. Add assert statements to BinarySearchST.java to check algorithm invariants and data structure integrity after every
insertion and deletion. For example, every index i should always be equal to rank(select(i)) and the array should
always be in order. | /******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with bina... | [
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] | {
"number": "3.1.30",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
]
} |
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). | Use the same convention as the textbook implementation: an empty tree has height -1 and a one-node tree has height 0.
Recursive implementation:
```java
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));... | [
"https://algs4.cs.princeton.edu/32bst/tinyST.txt"
] | {
"number": "3.2.6",
"code_execution": false
} |
Give nonrecursive implementations of get() , put() , and keys() for BST. | /******************************************************************************
* Compilation: javac NonrecursiveBST.java
* Execution: java NonrecursiveBST < input.txt
* Dependencies: StdOut.java StdIn.java
*
* A symbol table implemented with a binary search tree using
* iteration instead of recursion f... | [
"https://algs4.cs.princeton.edu/32bst/tinyST.txt"
] | {
"number": "3.2.13",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/32bst/NonrecursiveBST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
]
} |
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 t... | /******************************************************************************
* Compilation: javac PerfectBalance.java
* Execution: java PerfectBalance < input.txt
* Dependencies: StdOut.java
*
* Read sequence of strings from standard input (no duplicates),
* and insert into a BST so that BST is perfec... | [] | {
"number": "3.2.25",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/32bst/PerfectBalance.java",
"params": [
"<<EOF\nP E R F C T B I N A R Y S R H\nEOF"
],
"dependencies": [
"StdOut.java"
]
} |
Subtree count check. Write a recursive method isSizeConsistent() in BST.java that takes a Node as argument and returns true if the subtree count field N is consistent in the data structure rooted at that node, false otherwise. | /******************************************************************************
* Compilation: javac BST.java
* Execution: java BST
* Dependencies: StdIn.java StdOut.java Queue.java
* Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt
*
* A symbol table implemented with a binary search tree.
... | [
"https://algs4.cs.princeton.edu/32bst/tinyST.txt"
] | {
"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"
]
} |
Select/rank check. Write a method isRankConsistent() in BST.java 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)) . | /******************************************************************************
* Compilation: javac BST.java
* Execution: java BST
* Dependencies: StdIn.java StdOut.java Queue.java
* Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt
*
* A symbol table implemented with a binary search tree.
... | [
"https://algs4.cs.princeton.edu/32bst/tinyST.txt"
] | {
"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"
]
} |
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. | /******************************************************************************
* Compilation: javac Graph.java
* Execution: java Graph input.txt
* Dependencies: Bag.java Stack.java In.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt
* https://algs4.cs.prince... | [
"https://algs4.cs.princeton.edu/41graph/mediumG.txt",
"https://algs4.cs.princeton.edu/41graph/largeG.txt",
"https://algs4.cs.princeton.edu/41graph/tinyG.txt"
] | {
"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"
]
} |
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. | /******************************************************************************
* Compilation: javac BreadthFirstPaths.java
* Execution: java BreadthFirstPaths G s
* Dependencies: Graph.java Queue.java Stack.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/41graph/tinyCG.txt
* ... | [
"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"
] | {
"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"
]
} |
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). | /******************************************************************************
* Compilation: javac BaconHistogram.java
* Execution: java BaconHistogram input.txt delimiter actor
* Dependencies: SymbolGraph.java Graph.java In.java BreadthFirstPaths.java
* Data files: https://algs4.cs.princeton.edu/41grap... | [
"https://algs4.cs.princeton.edu/41graph/movies.txt"
] | {
"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"
]
} |
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. | /******************************************************************************
* Compilation: javac Digraph.java
* Execution: java Digraph filename.txt
* Dependencies: Bag.java In.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/42digraph/tinyDG.txt
* https://algs4.cs.princet... | [
"https://algs4.cs.princeton.edu/42digraph/largeDG.txt",
"https://algs4.cs.princeton.edu/42digraph/tinyDG.txt",
"https://algs4.cs.princeton.edu/42digraph/mediumDG.txt"
] | {
"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"
]
} |
Implement the constructor for EdgeWeightedGraph.java that reads an edge-weighted graph from an input stream. | /******************************************************************************
* Compilation: javac EdgeWeightedGraph.java
* Execution: java EdgeWeightedGraph filename.txt
* Dependencies: Bag.java Edge.java In.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* ... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
Implement toString() for EdgeWeightedGraph.java. | /******************************************************************************
* Compilation: javac EdgeWeightedGraph.java
* Execution: java EdgeWeightedGraph filename.txt
* Dependencies: Bag.java Edge.java In.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* ... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
Provide an implementation of edges() for PrimMST.java . | /******************************************************************************
* Compilation: javac PrimMST.java
* Execution: java PrimMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Queue.java
* IndexMinPQ.java UF.java In.java StdOut.java
* Data files: https://algs4.cs.... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
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. | /******************************************************************************
* Compilation: javac PrimMST.java
* Execution: java PrimMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Queue.java
* IndexMinPQ.java UF.java In.java StdOut.java
* Data files: https://algs4.cs.... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
Minimum spanning forest. Develop versions of Kruskal's algorithms that compute
the minimum spanning forest of an edge-weighted graph that
is not necessarily connected. | /******************************************************************************
* Compilation: javac KruskalMST.java
* Execution: java KruskalMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java
* UF.java In.java StdOut.java
* Data files: https://algs4.c... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
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 ... | /******************************************************************************
* Compilation: javac KruskalMST.java
* Execution: java KruskalMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Queue.java MinPQ.java
* UF.java In.java StdOut.java
* Data files: https://algs4.c... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
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 t... | /******************************************************************************
* Compilation: javac BoruvkaMST.java
* Execution: java BoruvkaMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Bag.java
* UF.java In.java StdOut.java
* Data files: https://algs4.cs.princeton.ed... | [
"https://algs4.cs.princeton.edu/43mst/mediumEWG.txt",
"https://algs4.cs.princeton.edu/43mst/tinyEWG.txt",
"https://algs4.cs.princeton.edu/43mst/largeEWG.txt"
] | {
"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"
]
} |
Provide an implementation of toString() for EdgeWeightedDigraph.java. | /******************************************************************************
* Compilation: javac EdgeWeightedDigraph.java
* Execution: java EdgeWeightedDigraph digraph.txt
* Dependencies: Bag.java DirectedEdge.java
* Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt
* https:/... | [
"https://algs4.cs.princeton.edu/44sp/largeEWD.txt",
"https://algs4.cs.princeton.edu/44sp/tinyEWD.txt",
"https://algs4.cs.princeton.edu/44sp/mediumEWD.txt"
] | {
"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"
]
} |
Adapt the Topological classes from Section 4.2 to use the EdgeweightedDigraph and DirectedEdge APIs of this section, thus implementing Topological.java. | /******************************************************************************
* Compilation: javac Topological.java
* Execution: java Topological filename.txt delimiter
* Dependencies: Digraph.java DepthFirstOrder.java DirectedCycle.java
* EdgeWeightedDigraph.java EdgeWeightedDirectedCycle.... | [
"https://algs4.cs.princeton.edu/42digraph/jobs.txt"
] | {
"number": "4.4.12",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/44sp/Topological.java",
"params": [
"jobs.txt \"/\""
],
"dependencies": [
"DepthFirstOrder.java",
"Digraph.java",
"DirectedCycle.java",
"EdgeWeightedDigraph.java",
"EdgeWeightedDirectedCycle.java"
... |
Longest paths in DAGs. Develop an implementation AcyclicLP.java that can solve the longest-paths problem in edge-weighted DAGs. | /******************************************************************************
* Compilation: javac AcyclicLP.java
* Execution: java AcyclicLP V E
* Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java
* Data files: https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt
*
* Computes lo... | [
"https://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt"
] | {
"number": "4.4.28",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/44sp/AcyclicLP.java",
"params": [
"tinyEWDAG.txt 5"
],
"dependencies": [
"DirectedEdge.java",
"EdgeWeightedDigraph.java",
"In.java",
"Stack.java",
"StdOut.java",
"Topological.java"
]
} |
Give the value of each of the following expressions:
a. ( 0 + 15 ) / 2
b. 2.0e-6 * 100000000.1
c. true && false || true && true | 1.1.1
a) 7
b) 200.0000002
c) true
| [] | {
"number": "1.1.1",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Give the type and value of each of the following expressions:
a. (1 + 2.236)/2
b. 1 + 2 + 3 + 4.0
c. 4.1 >= 4
d. 1 + 2 + "3" | 1.1.2
a) 1.618 -> double
b) 10.0 -> double
c) true -> boolean
d) 33 -> String
| [] | {
"number": "1.1.2",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
What (if anything) is wrong with each of the following statements?
a. if (a > b) then c = 0;
b. if a > b { c = 0; }
c. if (a > b) c = 0;
d. if (a > b) c = 0 else b = 0; | 1.1.4
a) No such keyword as "then" in Java language
b) Missing Parentheses on if conditional
c) Nothing wrong
d) Missing semicolon after the "then" clause
| [] | {
"number": "1.1.4",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
What does the following program print?
int f = 0;
int g = 1;
for (int i = 0; i <= 15; i++)
{
StdOut.println(f);
f = f + g;
g = f - g;
} | 1.1.6
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
| [] | {
"number": "1.1.6",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Give the value printed by each of the following code fragments:
a. double t = 9.0;
while (Math.abs(t - 9.0/t) > .001)
t = (9.0/t + t) / 2.0;
StdOut.printf("%.5f\n", t);
b. int sum = 0;
for (int i = 1; i < 1000; i++)
for (int j = 0; j < i; j++)
sum++;
StdOut.println(sum);
c. int sum = 0;
for (int i = 1; i < 1000... | 1.1.7
a) 3.00009
b) 499500
c) 10000
| [] | {
"number": "1.1.7",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
What do each of the following print?
a. System.out.println('b');
b. System.out.println('b' + 'c');
c. System.out.println((char) ('a' + 4));
Explain each outcome. | 1.1.8
a) b -> converts the char "b" to String and prints it
b) 197 -> sums the char codes of "b" and "c", converts to String and prints it
c) e -> sums the char code of "a" with 4, converts it to char and prints it
| [] | {
"number": "1.1.8",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
What is wrong with the following code fragment?
int[] a;
for (int i = 0; i < 10; i++)
a[i] = i * i; | 1.1.10
The array was not initialized and will generate a compile-time error.
| [] | {
"number": "1.1.10",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
What does the following code fragment print?
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = 9 - i;
for (int i = 0; i < 10; i++)
a[i] = a[a[i]];
for (int i = 0; i < 10; i++)
System.out.println(a[i]); | 1.1.12
0
1
2
3
4
4
3
2
1
0
| [] | {
"number": "1.1.12",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Give the value of exR1(6):
public static String exR1(int n)
{
if (n <= 0) return "";
return exR1(n-3) + n + exR1(n-2) + n;
} | 1.1.16
311361142246
| [] | {
"number": "1.1.16",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Criticize the following recursive function:
public static String exR2(int n)
{
String s = exR2(n-3) + n + exR2(n-2) + n;
if (n <= 0) return "";
return s;
} | 1.1.17
The function never stops because it keeps calling itself on the first line, until a StackOverflowError occurs.
| [] | {
"number": "1.1.17",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Consider the following recursive function:
public static int mystery(int a, int b)
{
if (b == 0) return 0;
if (b % 2 == 0) return mystery(a+a, b/2);
return mystery(a+a, b/2) + a;
}
What are the values of mystery(2, 25) and mystery(3, 11)? Given positive integers a and b, describe what value mystery(a, b) computes.... | 1.1.18
mystery(2,25) is equal to 50
mystery(3,11) is equal to 33
mystery(a,b) computes a * b
mystery2(2,25) is equal to 33554432
mystery2(3,11) is equal to 177147
mystery2(a,b) computes a^b
| [] | {
"number": "1.1.18",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Run the following program on your computer:
public class Fibonacci
{
public static long F(int N)
{
if (N == 0) return 0;
if (N == 1) return 1;
return F(N-1) + F(N-2);
}
public static void main(String[] args)
{
for (int N = 0; N < 100; N++)
StdOut.println(N + " " + F(N));
}
}
What is the largest value of N ... | // Exercise19.java
package chapter1.section1;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
// Thanks to pmfer2016 (https://github.com/pmfer2016) for reporting that the int type is not enough for
// holding all the Fibonacci values.
// https://github.com/reneargento/algorithms-sedgewick-way... | [] | {
"number": "1.1.19",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Use mathematical induction to prove that Euclid’s algorithm computes the greatest common divisor of any pair of nonnegative integers p and q. | Euclid's algorithm is correct because the invariant gcd(p, q) = gcd(q, p % q) holds at every recursive step.
Let p = aq + r, where r = p % q and 0 <= r < q. Any integer d that divides both p and q also divides r = p - aq. Conversely, any integer d that divides both q and r also divides p = aq + r. Therefore the common... | [] | {
"number": "1.1.25",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Exercise",
"code_execution": false
} |
Binomial distribution. Estimate the number of recursive calls that would be used by the code
public static double binomial(int N, int k, double p)
{
if ((N == 0) || (k < 0)) return 1.0;
return (1.0 - p)*binomial(N-1, k) + p*binomial(N-1, k-1);
}
to compute binomial(100, 50). Develop a better implementation that is ... | The plain recursive implementation makes an enormous number of calls because it recomputes the same subproblems. For the code as written, the call count T(N, k) satisfies
T(N, k) = 1 + T(N - 1, k) + T(N - 1, k - 1), with base cases T(0, k) = 1 and T(N, k < 0) = 1.
For binomial(100, 50), this is 1,566,368,110,549,409,... | [] | {
"number": "1.1.27",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Creative Problem",
"code_execution": false
} |
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 ... | 1.1.34 - Filtering
Print the maximum and minimum numbers -> Could be implemented as a filter
Print the median of the numbers -> Requires saving all values
Print the Kth smallest value, for K less than 100 -> Could be implemented as a filter with an array of size K
Print the sum of the squares of the numbers -> Could b... | [] | {
"number": "1.1.34",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Creative Problem",
"code_execution": false
} |
Dice simulation. The following code computes the exact probability distribution for the sum of two dice:
int SIDES = 6;
double[] dist = new double[2*SIDES+1];
for (int i = 1; i <= SIDES; i++)
for (int j = 1; j <= SIDES; j++)
dist[i+j] += 1.0;
for (int k = 2; k <= 2*SIDES; k++)
dist[k] /= 36.0;
The value dist[i] i... | 1.1.35 - Dice simulation
N has to be 6.000.000 before my empirical results match the exact results to three decimal places.
| [] | {
"number": "1.1.35",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Experiment",
"code_execution": false
} |
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. | `BruteForceSearch` should time linear search on the unsorted whitelist and binary search on a sorted copy of the same whitelist, using every key from `largeT.txt`.
```java
import edu.princeton.cs.algs4.BinarySearch;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.S... | [] | {
"number": "1.1.38",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.1,
"section_title": "Basic Programming Model",
"type": "Experiment",
"code_execution": false
} |
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. | package chapter1.section2;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by Rene Argento
*/
// Thanks to thiendao1407 (https://github.com/thiendao1407) for suggesting a correct solution to th... | [] | {
"number": "1.2.1",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter1.section2;
import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Exercise2 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
Interval1D[] intervals = new Interval1D[n];
... | [] | {
"number": "1.2.2",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
What does the following code fragment print?
String string1 = "hello";
String string2 = string1;
string1 = "world";
StdOut.println(string1);
StdOut.println(string2); | 1.2.4
Prints:
world
hello
| [] | {
"number": "1.2.4",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
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 string... | package chapter1.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise6 {
public static void main(String[] args) {
String s1 = "abc";
String t1 = "def";
StdOut.println("Is circular Shift 1: " + isCircularShift(s1, t1) + " Expected: false... | [] | {
"number": "1.2.6",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
What does the following recursive function return?
public static String mystery(String s)
{
int N = s.length();
if (N <= 1) return s;
String a = s.substring(0, N/2);
String b = s.substring(N/2, N);
return mystery(b) + mystery(a);
} | 1.2.7
Returns the reverse of the provided String.
Example: mystery("abcde") returns edcba
| [] | {
"number": "1.2.7",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
Suppose that a[] and b[] are each integer arrays consisting of millions of integers. What does the follow code do? Is it reasonably efficient?
int[] t = a; a = b; b = t; | 1.2.8
The code swaps a[] and b[] values.
It is very efficient because it only changes the references, instead of copying millions of elements,
with a complexity of O(1).
| [] | {
"number": "1.2.8",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
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 ... | ```java
import edu.princeton.cs.algs4.StdDraw;
public class VisualCounter {
private final int maxOperations;
private final int maxAbsoluteValue;
private int operations;
private int count;
public VisualCounter(int n, int max) {
maxOperations = n;
maxAbsoluteValue = Math.abs(max);
... | [] | {
"number": "1.2.10",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
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. | One simple implementation is Sakamoto's day-of-week algorithm. It handles leap years correctly, including century years.
```java
public String dayOfTheWeek() {
String[] name = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
int[] monthOffset = {0, 3, 2, 5, ... | [] | {
"number": "1.2.12",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Exercise",
"code_execution": false
} |
Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division.
public class Rational
Rational(int numerator, int denominator)
Rational plus(Rational b) // sum of this number and b
Rational minus(Rational b) // difference of this numb... | ```java
public final class Rational {
private final long numerator;
private final long denominator;
public Rational(long numerator, long denominator) {
if (denominator == 0) throw new IllegalArgumentException("denominator is zero");
if (denominator < 0) {
numerator = -numerator;... | [] | {
"number": "1.2.16",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Creative Problem",
"code_execution": false
} |
Robust implementation of rational numbers. Use assertions to develop an implementation of Rational (see Exercise 1.2.16) that is immune to overflow. | Use the same immutable representation as Exercise 1.2.16, but assert that every intermediate arithmetic operation fits in a `long` before constructing the result.
```java
public Rational plus(Rational b) {
long left = Math.multiplyExact(numerator, b.denominator);
long right = Math.multiplyExact(b.numerator, de... | [] | {
"number": "1.2.17",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Creative Problem",
"code_execution": false
} |
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():
public class Accumulator
{
private double m;
private double s;
private int N;
public void addDataValue(d... | package chapter1.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise18_VarianceForAccumulator {
private double m;
private double s;
private int N;
public void addDataValue(double x) {
N++;
s = s + 1.0 * (N - 1) / N * (x - m) * (x -... | [] | {
"number": "1.2.18",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Creative Problem",
"code_execution": false
} |
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.
| type | format | example |
|-----------... | // Exercise19_1_Parsing.java
package chapter1.section2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise19_1_Parsing {
private final int month;
... | [] | {
"number": "1.2.19",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.2,
"section_title": "Data Abstraction",
"type": "Creative Problem",
"code_execution": false
} |
Add a method isFull() to FixedCapacityStackOfStrings. | package chapter1.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise1 { //FixedCapacityStackOfStrings
private String[] a;
private int n;
public Exercise1(int cap) {
a = new String[cap];
}
public boolean isEmpty() {
return n ==... | [] | {
"number": "1.3.1",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Give the output printed by java Stack for the input
it was - the best - of times - - - it was - the - - | 1.3.2 it was - the best - of times - - - it was - the - -
The output printed is:
was best times of the was the it
(1 left on stack)
| [] | {
"number": "1.3.2",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
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 [(]). | package chapter1.section3;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Parentheses {
public static void main(String[] args) {
String input = StdIn.readAll().trim();
StdOut.println(isBalanced(input));
}
privat... | [] | {
"number": "1.3.4",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
What does the following code fragment do to the queue q?
Stack<String> stack = new Stack<String>();
while (!q.isEmpty())
stack.push(q.dequeue());
while (!stack.isEmpty())
q.enqueue(stack.pop()); | 1.3.6
It inverts the order of the queue values
| [] | {
"number": "1.3.6",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Add a method peek() to Stack that returns the most recently inserted item on the stack (without popping it). | package chapter1.section3;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise7<Item> {
private Node first;
private int n;
private class Node {
Item item;
Node next;
}
public boolean isEmpty() {... | [] | {
"number": "1.3.7",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Give the contents and size of the array for DoublingStackOfStrings with the input
it was - the best - of times - - - it was - the - - | Contents: `it`. The backing array size is 2, because the final pop leaves one item after the array was last doubled to length 2. | [] | {
"number": "1.3.8",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Write a filter InfixToPostfix that converts an arithmetic expression from infix to postfix. | A standard shunting-yard filter converts infix tokens to postfix while preserving precedence.
```java
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class InfixToPostfix {
private static int precedence(String op) {
if (op.equals("+") ... | [] | {
"number": "1.3.10",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter1.section3;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise12 {
private static Stack<String> copy(Stack<String> stack) {
Stack<String> temp = new Stack<>();
Stack<String> copy = new Stack<>();
... | [] | {
"number": "1.3.12",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
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. | public static Date[] readDates() {
Queue<Date> queue = new Queue<>();
while (!StdIn.isEmpty()) {
queue.enqueue(new Date(StdIn.readString()));
}
Date[] dates = new Date[queue.size()];
for (int i = 0; i < dates.length; i++) {
dates[i] = queue.dequeue();
}
return dates;
}
| [] | {
"number": "1.3.16",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Do Exercise 1.3.16 for Transaction. | public static Transaction[] readTransactions() {
Queue<Transaction> queue = new Queue<>();
while (!StdIn.isEmpty()) {
queue.enqueue(new Transaction(StdIn.readLine()));
}
Transaction[] transactions = new Transaction[queue.size()];
for (int i = 0; i < transactions.length; i++) {
trans... | [] | {
"number": "1.3.17",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment?
x.next = x.next.next; | 1.3.18
Deletes from the list the node the comes after x.
| [] | {
"number": "1.3.18",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Give a code fragment that removes the last node in a linked list whose first node is first. | package chapter1.section3;
import java.util.Iterator;
import java.util.StringJoiner;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento
*/
public class Exercise19<Item> implements Iterable<Item> {
private class Node {
Item item;
Node next;
}
private int size;
priv... | [] | {
"number": "1.3.19",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
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). | public static void insertAfter(Node first, Node second) {
if (first == null || second == null) {
return;
}
second.next = first.next;
first.next = second;
}
The method uses the node references directly, so it works even when the list contains duplicate item values.
| [] | {
"number": "1.3.25",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
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. | public static int max(Node first) {
int max = 0;
for (Node x = first; x != null; x = x.next) {
if (x.item > max) {
max = x.item;
}
}
return max;
}
This returns 0 for an empty list and otherwise scans the list once.
| [] | {
"number": "1.3.27",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Exercise",
"code_execution": false
} |
Random bag. A random bag stores a collection of items and supports the following API:
public class RandomBag<Item> implements Iterable<Item>
RandomBag() // create an empty random bag
boolean isEmpty() // is the bag empty?
int size() // number of items in the bag
void add(Item item) // add an item
Write a class RandomB... | package chapter1.section3;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.StringJoiner;
/**
* Created by Rene Argento on 8/16/16.
*/
public class Exercise34_RandomBag<Item> implements Iterable<Item> {
private Item[] array;
private... | [] | {
"number": "1.3.34",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Creative Problem",
"code_execution": false
} |
Random queue. A random queue stores a collection of items and supports the following API:
public class RandomQueue<Item>
RandomQueue() // create an empty random queue
boolean isEmpty() // is the queue empty?
void enqueue(Item item) // add an item
Item dequeue() // remove and return a random item (sample without replace... | package chapter1.section3;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by Rene Argento on 8/16/16.
*/
@SuppressWarnings("unchecked")
public class Exercise35_RandomQueue {
public class RandomQueue<Item> {
private Item[] items;
private int size;
... | [] | {
"number": "1.3.35",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Creative Problem",
"code_execution": false
} |
Delete kth element. Implement a class that supports the following API:
public class GeneralizedQueue<Item>
GeneralizedQueue() // create an empty queue
boolean isEmpty() // is the queue empty?
void insert(Item x) // add an item
Item delete(int k) // delete and return the kth least recently inserted item
First, develop a... | // Exercise38_1_DeleteKthElement.java
package chapter1.section3;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
import java.util.StringJoiner;
/**
* Created by Rene Argento on 8/21/16.
*/
@SuppressWarnings("unchecked")
public class Exercise38_1_DeleteKthElement<Item> implements Iterable<Item>{
... | [] | {
"number": "1.3.38",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Creative Problem",
"code_execution": false
} |
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). | 1.3.46 - Forbidden triple for stack generability
Suppose 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".
Thus, when "c" is pushed, both "a" and "b" are on the stack. Therefore, "a" cannot be popped before "b".
When pushing items in the order 0, 1,... | [] | {
"number": "1.3.46",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.3,
"section_title": "Bags, Queues, and Stacks",
"type": "Creative Problem",
"code_execution": false
} |
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. | 1.4.1
Counting argument:
When choosing the first element there are N possibilities.
When choosing the second element there are N - 1 possibilities.
When choosing the third element there are N - 2 possibilities.
This is a total of N(N - 1)(N - 2). If the order of items mattered, this would be the result.
However, the... | [] | {
"number": "1.4.1",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.4,
"section_title": "Analysis of Algorithms",
"type": "Exercise",
"code_execution": false
} |
Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow. | package chapter1.section4;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import java.math.BigInteger;
/**
* Created by Rene Argento on 9/27/16.
*/
public class Exercise2 {
public static int count(int[] array) {
//Count triples that sum to 0.
int length = array.length;... | [] | {
"number": "1.4.2",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.4,
"section_title": "Analysis of Algorithms",
"type": "Exercise",
"code_execution": false
} |
Develop a table like the one on page 181 for TwoSum. | 1.4.4
Statement in Block Time in seconds Frequency Total time
D t0 x(depends on input) t0x
C t1 N^2/2 - N/2 t1(N^2/2 - N/2)
B t2 N t2N
... | [] | {
"number": "1.4.4",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.4,
"section_title": "Analysis of Algorithms",
"type": "Exercise",
"code_execution": false
} |
Give the order of growth (as a function of N) of the running times of each of the following code fragments:
a. int sum = 0;
for (int n = N; n > 0; n /= 2)
for(int i = 0; i < n; i++)
sum++;
b. int sum = 0;
for (int i = 1; i < N; i *= 2)
for (int j = 0; j < i; j++)
sum++;
c. int sum = 0;
for (int i = 1; i < N; i *... | 1.4.6
a. O(N)
b. O(N)
c. O(N log(N))
Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for mentioning the correct answer to the question in letter a.
https://github.com/reneargento/algorithms-sedgewick-wayne/issues/9
| [] | {
"number": "1.4.6",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.4,
"section_title": "Analysis of Algorithms",
"type": "Exercise",
"code_execution": false
} |
Analyze ThreeSum under a cost model that counts arithmetic operations (and comparisons) involving the input numbers. | 1.4.7
With a cost model that counts arithmetic operations (and comparisons) involving input numbers, the main "if" from
ThreeSum involves 4 operations instead of 1.
if (a[i] + a[j] + a[k] == 0)
One operation for the if check; one operation to sum a[i] and a[j]; one operation to sum the result with a[k]
and one opera... | [] | {
"number": "1.4.7",
"chapter": 1,
"chapter_title": "Fundamentals",
"section": 1.4,
"section_title": "Analysis of Algorithms",
"type": "Exercise",
"code_execution": false
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.