question stringlengths 34 5.53k | answer stringlengths 21 101k | support_files listlengths 0 6 | metadata unknown |
|---|---|---|---|
About how many compares are required, on the average, to find the smallest of N items using select()? | 2.5.7
On the average, to find the smallest of N items using select(), it is required 2N + 2 * lnN + (2N - 2) * ln(N / (N - 1)) compares.
This follows from proposition U in the book that says that the average number of compares to find the kth item in a shuffled array is ~2N + 2k * ln(N / k) + 2(N - k) * ln(N / (N - k)... | [] | {
"number": "2.5.7",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
Write a program Frequency that reads strings from standard input and prints the number of times each string occurs, in descending order of frequency. | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
import java.util.*;
/**
* Created by Rene Argento on 09/04/17.
*/
public class Exercise8 {
private class StringFrequency implements Comparable<StringFrequency>{
String string;
int frequency;
StringFrequency(String string... | [] | {
"number": "2.5.8",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
Develop a data type that allows you to write a client that can sort stock-volume records such as the following by volume:
```text
1-Oct-28 3500000
2-Oct-28 3850000
3-Oct-28 4060000
```
Each input line contains a date and a volume; the natural order of the data type should be by volume. | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 09/04/17.
*/
public class Exercise9 {
class VolumesPerDay implements Comparable<VolumesPerDay>{
private String date;
private long volume;
VolumesPerDay(String dat... | [] | {
"number": "2.5.9",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 09/04/17.
*/
public class Exercise10 {
class Version implements Comparable<Version>{
private String version;
Version(String version) {
String[] versionSplit = version.split("\\.");
... | [] | {
"number": "2.5.10",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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, a... | package chapter2.section5;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
/**
* Created by Rene Argento on 10/04/17.
*/
//The resulting solution is guaranteed to be within 33% of ... | [] | {
"number": "2.5.13",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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("\\."... | package chapter2.section5;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 10/04/17.
*/
public class Exercise14_SortByReverseDomain {
private class Domain implements Comparable<Domain>{
String domainName;
Str... | [] | {
"number": "2.5.14",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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 fro... | 2.5.15 - Spam campaign
I would sort the email list by the reverse domain.
Then I would choose emails among the same domain to serve as sender and receiver and repeat this process for each domain.
| [] | {
"number": "2.5.15",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 12/04/17.
*/
public class Exercise20_IdleTime {
private class Job implements Comparable<Job> {
private int startTime;
private int endTime;
Job(int startTime, int... | [] | {
"number": "2.5.20",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
Sampling for selection. Investigate the idea of using sampling to improve selection. Hint: Using the median may not always be helpful. | 2.5.23 - Sampling for selection
Sampling improves selection in cases where the element searched is one of the smallest or highest values in the array.
For example, when searching for the 2nd smallest element in an array of size 10^9, selecting one of the smallest elements as the pivot in the initial steps will yield b... | [] | {
"number": "2.5.23",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
Stable priority queue. Develop a stable priority-queue implementation (which returns duplicate keys in the same order in which they were inserted). | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 15/04/17.
*/
//Based on http://algs4.cs.princeton.edu/25applications/StableMinPQ.java.html
@SuppressWarnings("unchecked")
public class Exercise24_StablePriorityQueue {
public enum Orientation {
MAX, MIN;
... | [] | {
"number": "2.5.24",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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 compa... | package chapter2.section5;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
import java.util.Comparator;
/**
* Created by Rene Argento on 15/04/17.
*/
public class Exercise25_PointsInThePlane {
static class Point2D implements Comparable<Point2D> {
... | [] | {
"number": "2.5.25",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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. | Choose the anchor `p` with minimum y-coordinate, breaking ties by x-coordinate. Sort every other point by the polar angle it makes with `p`, then connect the points in that order and finally connect the last point back to `p`.
```java
Point2D[] points = readPoints();
Arrays.sort(points, Point2D.Y_ORDER.thenComparing(P... | [] | {
"number": "2.5.26",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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 o... | A direct insertion-sort version keeps the input array fixed and sorts an index array instead.
```java
public class Insertion {
public static int[] indirectSort(Comparable[] a) {
int n = a.length;
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
... | [] | {
"number": "2.5.27",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
import java.io.File;
import java.util.Arrays;
/**
* Created by Rene Argento on 16/04/17.
*/
public class Exercise28_SortFilesByName {
// Parameter example: [any file path]
public static void main(String[] args) {
String directoryPath... | [] | {
"number": "2.5.28",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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 list... | package chapter2.section5;
import edu.princeton.cs.algs4.StdOut;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* Created by Rene Argento on 16/04/17.
*/
// Thanks to ckwastra (... | [] | {
"number": "2.5.29",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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. | True.
Suppose the columns are sorted before the row sort, so row `i` is componentwise no larger than row `i+1`: for every column `j`, `a[i][j] <= a[i+1][j]`. Sorting a row just replaces that row by its order statistics. If every element of one row is componentwise no larger than the corresponding element of the next r... | [] | {
"number": "2.5.30",
"chapter": 2,
"chapter_title": "Sorting",
"section": 2.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
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. | 3.1.6
The put() method will be called once for every word.
The get() method will be called once for every word, except on the first time a word in being inserted in the symbol table.
Calls to put() = W
Calls to get() = W - D
Thanks to faame (https://github.com/faame) for suggesting a better answer.
https://github.co... | [] | {
"number": "3.1.6",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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? | For each of the 1,000 possible keys, the probability it appears at least once in `N` independent draws is
`1 - (999/1000)^N`.
By linearity of expectation, the expected number of distinct keys is
`1000 * (1 - (999/1000)^N)`.
| N | expected distinct keys |
|---:|---:|
| 10 | 9.955 |
| 10^2 | 95.208 |
| 10^3 | 632.305... | [] | {
"number": "3.1.7",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
What is the most frequently used word of ten letters or more in Tale of Two Cities? | 3.1.8
Most frequently used word of ten letters or more in Tale of Two Cities: Monseigneur Frequency: 47
| [] | {
"number": "3.1.8",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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. | // Exercise9.java
package chapter3.section1;
import edu.princeton.cs.algs4.StdOut;
import util.FileUtil;
/**
* Created by Rene Argento on 23/04/17.
*/
public class Exercise9 {
public static void main(String[] args) {
String filePath = args[0];
new Exercise9().readBookAndGetLastWordInserted(file... | [] | {
"number": "3.1.9",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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? | 3.1.10
key value first
E 0 E0 0 compares
A 1 A1 E0 1 compare
S 2 S2 A1 E0 2 compares
Y 3 Y3 S2 A1 E0 3 compares
Q 4 Q4 Y3 S... | [] | {
"number": "3.1.10",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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? | Final keys in the table are:
`A E I N O Q S T U Y`
Using the textbook `BinarySearchST.put()` implementation, the ranks/comparisons for the insertions `E A S Y Q U E S T I O N` are:
| key | compares |
|---|---:|
| E | 0 |
| A | 2 |
| S | 2 |
| Y | 2 |
| Q | 3 |
| U | 4 |
| E | 4 |
| S | 4 |
| T | 4 |
| I | 4 |
| O | ... | [] | {
"number": "3.1.11",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.1.13
For an application that does 10^3 put() operations and 10^6 get() operations I would use a binary search symbol table implementation.
The 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 b... | [] | {
"number": "3.1.13",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.1.14
For an application that does 10^6 put() operations and 10^3 get() operations I would use a sequential search symbol table implementation.
The 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.
For the get() operation, the wo... | [] | {
"number": "3.1.14",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.1.15
Searches Percentage of total time spent on insertions
1000 0.00%
1000000 6.10%
1000000000 96.26%
The average insertion cost is N, so the total insertion cost for N keys is ... | [] | {
"number": "3.1.15",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
Prove that the rank() method in BinarySearchST is correct. | 3.1.18
The rank() method in BinarySearchST always starts the search in the middle of the array if it has an odd number of elements.
If the array has an even number of elements, the rank() method starts the search on the left of the two middle elements.
After comparing the middle element with the search key, if it is s... | [] | {
"number": "3.1.18",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.1.20
Proposition B. Binary search in an ordered array with N keys uses no more than lg N + 1 compares for a search (successful or unsuccessful).
Proof: Let C(N) be the number of compares to search for a key in a symbol table of size N.
We have C(0) = 0, C(1) = 1, and for N > 0 we can write a recurrence relationshi... | [] | {
"number": "3.1.20",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Exercise",
"code_execution": false
} |
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... | 3.1.21 - Memory usage
* BinarySearchST
object overhead -> 16 bytes
Key[] reference (keys) -> 8 bytes
Value[] reference (values) -> 8 bytes
int value (size) -> 4 bytes
padding -> 4 bytes
Key[]
object overhead -> 16 bytes
int value (length) -> 4 bytes
padding -> 4 bytes
N Key re... | [] | {
"number": "3.1.21",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Creative Problem",
"code_execution": false
} |
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). | 3.1.23 - Analysis of binary search
As 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.
A number N has exactly lg N + 1 bits. This is because shifting 1 bit to the right reduces the number by half (rounded down).
For example:
N Bit ... | [] | {
"number": "3.1.23",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Creative Problem",
"code_execution": false
} |
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. | 3.1.27 - Small tables
Building the binary search symbol table requires N calls to put().
Every put() operation makes a call to rank() and does a search, an operation with order of growth O(lg N).
Assuming that we can choose the order of the keys to insert, we can create the table in a sorted order, starting with the s... | [] | {
"number": "3.1.27",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.1,
"section_title": "Symbol Tables",
"type": "Creative Problem",
"code_execution": false
} |
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). | package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 09/05/17.
*/
public class Exercise6 {
private class BinarySearchTree<Key extends Comparable<Key>, Value>{
private class Node ... | [] | {
"number": "3.2.6",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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), an... | package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 16/05/17.
*/
// Thanks to ckwastra (https://github.com/ckwastra) for fixing the internal path length computation.
// https://github.com/ren... | [] | {
"number": "3.2.7",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 27/05/17.
*/
// Thanks to ckwastra (https://github.com/ckwastra) for suggesting a O(1) solution.
// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/277
public class Exercise8 {
public static void ... | [] | {
"number": "3.2.8",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | There are Catalan-number many BST shapes: `C_2 = 2`, `C_3 = 5`, `C_4 = 14`, `C_5 = 42`, and `C_6 = 132`.
A compact exact way to draw every shape is to use the recursive notation `X(left,right)`, with `.` for an empty subtree. The following generator prints all shapes for each requested `N`:
```java
import java.util.A... | [] | {
"number": "3.2.9",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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 appr... | package chapter3.section2;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 28/05/17.
*/
public class TestBST {
public static void main(String[] args) {
/** Test type
* 0- Keys()
* 1- Min()
* 2- Max()
* 3- F... | [] | {
"number": "3.2.10",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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.) | 3.2.11
We can build different shapes of trees of height N with all combinations of right and left links on nodes with children.
Example with N = 4:
Insertion order: 1 2 3 4
1
2
3
4
Insertion order: 1 2 4 3
1
2
4
3
Insertion order: 1 4 3 2
1
4
3
2
Insertion order: 1 4 2 3
1
4
2
3
Insertion orde... | [] | {
"number": "3.2.11",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
Give nonrecursive implementations of get() and put() for BST. | package chapter3.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 30/05/17.
*/
// Thanks to faame (https://github.com/faame) for suggesting an improvement to the put() method.
// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/228
public class Exercise13 {
priva... | [] | {
"number": "3.2.13",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
Give nonrecursive implementations of min(), max(), floor(), ceiling(), rank(), and select(). | package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Created by Rene Argento on 31/05/17.
*/
public class Exercise14 {
private class BinarySearchTree<Key extends Comparable<Key>, Value> exte... | [] | {
"number": "3.2.14",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
Give the sequences of nodes examined when the methods in BST are used to compute each of the following quantities for this tree:
```text
E
/ \
D Q
/ \
J T
\ /
M S
```
a. floor("Q")
b. select(5)
c. ceiling("Q")
d. rank("J")
e. size("D", "T")
f. keys("D", "T... | 3.2.15
a. floor("Q") - E Q
b. select(5) - E Q
c. ceiling("Q") - E Q
d. rank("J") - E Q J
e. size("D", "T") - E D Q J M T S
f. keys("D", "T") - E D Q J M T S
| [] | {
"number": "3.2.15",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | 3.2.18
Initial tree
E
A S
Q Y
I U
O T
N
Delete A
E
S
Q Y
I U
O T
N
Delete E
S
Q Y
... | [] | {
"number": "3.2.18",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | 3.2.20
Proposition: The running time of the two-argument keys() in a BST is at most proportional to the tree height plus the number of keys in the range.
Proof: The two-argument keys() method in a BST works in the following way:
1- It searches the tree until it finds the element which is equal or higher than the lowe... | [] | {
"number": "3.2.20",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section2;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by Rene Argento on 02/06/17.
*/
// Thanks to Daniel Bedrenko (https://github.com/dbedrenko) for correcting and suggesting a better implementation
// for this exercise: https://github.com/reneargen... | [] | {
"number": "3.2.21",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
Is delete() commutative? (Does deleting x, then y give the same result as deleting y, then x?) | 3.2.23
No, delete() is not commutative.
Counterexample:
Tree:
A
B D
C
1- Delete A, then B
C
B D
C
D
2- Delete B, then A
A
D
C
D
C
Thanks to faame (https://github.com/faame) for reporting an issue with the counterexample.
https://github.com/reneargento/al... | [] | {
"number": "3.2.23",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Exercise",
"code_execution": false
} |
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 ... | 3.2.27 - Memory usage
* BST
object overhead -> 16 bytes
Node reference (root) -> 8 bytes
Node
object overhead -> 16 bytes
extra overhead for reference to the enclosing instance -> 8 bytes
Key reference (key) -> 8 bytes
Value reference (value) -> 8 bytes
Node reference (left) -> 8... | [] | {
"number": "3.2.27",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | Since the previous order check has passed, an inorder traversal visits equal keys consecutively. Keep the previous key seen during that traversal and fail as soon as the same key appears twice.
```java
private Key previousKey;
public boolean hasNoDuplicates(Node x) {
previousKey = null;
return hasNoDuplicates... | [] | {
"number": "3.2.31",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | The certification should compose the three preceding checks in the order required by their preconditions: first verify that subtree counts describe a binary tree, then verify ordering, then run the duplicate-key check that assumes the keys are already in inorder order.
```java
public boolean isBST(Node x) {
if (x ... | [] | {
"number": "3.2.32",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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)). | package chapter3.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 04/06/17.
*/
public class Exercise33_SelectRankCheck {
private boolean checkRankAndSelect(BinarySearchTree<Integer, String> binarySearchTree) {
int size = binarySearchTree.size();
//Check rank
... | [] | {
"number": "3.2.33",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
Threading. Your goal is to support an extended API ThreadedST that supports the following additional operations in constant time:
Key next(Key key) key that follows key (null if key is the maximum)
Key prev(Key key) key that precedes key (null if key is the minimum)
To do so, add fields pred and succ to Node that conta... | package chapter3.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 04/06/17.
*/
@SuppressWarnings("unchecked")
public class Exercise34_Threading {
private class DoublyThreadedBST<Key extends Comparable<Key>, Value> extends BinarySearchTree<Key, Value> {
private class Nod... | [] | {
"number": "3.2.34",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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 γ ≈ .57... | 3.2.35 - Refined analysis
Proposition: The average number of compares for a successful search in a tree built from N random keys approaches the limit 2ln N + 2y - 3 ~= 1.39 lg N - 1.85 as N increases, where y = .57721... is Euler's constant.
Proof:
The number of compares used for a search hit ending at a given node... | [] | {
"number": "3.2.35",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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)? | 3.2.36 - Iterator
Yes, it is 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).
This can be done using a stack.
1- Add the root of the tree and all of its left children on the stack (as long as they are in the searched ... | [] | {
"number": "3.2.36",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 10/06/17.
*/
public class Exercise37_LevelOrderTraversal {
private void printLevel(BinarySearchTree.Node node) {
Queue<BinarySearchTree.Node> queue = new Queue<>();
... | [] | {
"number": "3.2.37",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.2,
"section_title": "Binary Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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.
Exercise 3.3.5 trees:
```text
3.3.5
N = 7
( )
() ( ) ( )
()
() ()
() () () ()
N = 8
( )
( ) ( ) ( )
()
() ()
() () () ( )
N = 9
... | 3.3.6
N = 7
( )
() ( ) ( )
Probability of this tree being the result: 4 / 7 = 0.57
()
() ()
() () () ()
Probability of this tree being the result: 3 / 7 = 0.43
N = 8
( )
( ) ( ) ( )
Probability of this tree being the result: (4 / 7) * (2 / 8) = 1 / 7 = 0.14
()
() ()
() () () ( )
P... | [] | {
"number": "3.3.6",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Draw diagrams like the one at the top of page 428 for the other five cases in the bottom diagram on that page. Use keys in sorted order `a < b < c < d < e`, and cover these insertion cases:
1. insertion into the root 3-node,
2. insertion into the left child of a 2-node parent,
3. insertion into the right child of a 2-... | 3.3.7
1- root
abc
less than a between a and b between b and c greater than c
b
a c
less than a between a and b between b and c greater than c
2- parent is a 2-node (left)
... | [] | {
"number": "3.3.7",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Show all possible ways that one might represent a 4-node with three 2-nodes bound together with red links (not necessarily left-leaning). | 3.3.8
Unique representations (not considering the order of the nodes):
A
B
C
A
C
B
B
A C
C
A
B
C
B
A
| [] | {
"number": "3.3.8",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Which of the following candidate trees are red-black BSTs?
The candidates are the four textbook diagrams (i)–(iv) from Exercise 3.3.9 (Sedgewick & Wayne, Section 3.3). Identify which are valid red-black BSTs and briefly justify your answer. | 3.3.9
(iii) and (iv)
(i) is not balanced
(ii) is not ordered (F cannot be on the left side of E)
| [] | {
"number": "3.3.9",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | 3.3.10
Insert E (B)E
A (B)E
(R)A
S (B)E
(R)A (R)S
S (R)E
(B)A (B)S
S (B)E
(B)A (B)S
Y (B)E
(B)A (B)S
(R)Y
Y (B)E
... | [] | {
"number": "3.3.10",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
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. | 3.3.11
Insert Y (B)Y
L (B)Y
(R)L
P (B)Y
(R)L
(R)P
P (B)Y
(R)P
(R)L
P (B)P
(R)L (R)Y
P (R)P
(B)L (B)Y
P (B)P
(B)L (B... | [] | {
"number": "3.3.11",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
True or false: If you insert keys in increasing order into a red-black BST, the tree height is monotonically increasing. | 3.3.13
True.
The following visualization shows 255 keys inserted into a red-black BST in ascending order.
[visualization](https://algs4.cs.princeton.edu/33balanced/media/red-black-255ascending.mov)
from
[source](https://algs4.cs.princeton.edu/33balanced/)
| [] | {
"number": "3.3.13",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
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). | 3.3.14
Insert A (B)A
B (B)A
(R)B
B (B)B
(R)A
C (B)B
(R)A (R)C
C (R)B
(B)A (B)C
C (B)B
(B)A (B)C
D (B)B
(B)A (B)C
... | [] | {
"number": "3.3.14",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
For left-leaning red-black BSTs, answer Exercises 3.3.13 and 3.3.14 for the case when the keys are inserted in descending order: show the rotations/color flips and state whether the tree height is monotonically increasing. | 3.3.15
If keys are inserted in decreasing order into a red-black BST, the tree height is NOT monotonically increasing.
Insert K (B)K
Insert J (B)K
(R)J
Insert I (B)K
(R)J
(R)I
Insert I (B)J
(R)I (R)K
Insert I (R)J
... | [] | {
"number": "3.3.15",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Draw all the structurally different red-black BSTs with N keys, for N from 2 up to 10 (see Exercise 3.3.5). | 3.3.18
N = 2
(B)N
(R)N
N = 3
(B)N
(B)N (B)N
N = 4
(B)N
(B)N (B)N
(R)N
N = 5
(B)N
(B)N (B)N
(R)N (R)N
(B)N
(R)N (B)N
(B)N (B)N
N = 6
(B)N
(R)N (B)N
(B)N (B)N (R)N
(B)N
(R)N (B)N
(B)N (B)N
(R)N
N = 7
... | [] | {
"number": "3.3.18",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Compute the internal path length in a perfectly balanced BST of N nodes, when N is a power of 2 minus 1. | 3.3.20
For a perfectly balanced BST of N nodes, when N is a power of 2 minus 1, the internal path lengths are:
P = 1 -> 2^1 - 1 = 1 node -> Internal path length: 0 -> Which is 2^0 * 0
P = 2 -> 2^2 - 1 = 3 nodes -> Internal path length: 2 -> Which is 2^0 * 0 + 2^1 * 1
P = 3 -> 2^3 - 1 = 7 nodes -> Internal path length... | [] | {
"number": "3.3.20",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
Create a test client TestRB.java, based on your solution to Exercise 3.2.10. | package chapter3.section3;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 19/06/17.
*/
public class Exercise21 {
public static void main(String[] args) {
/** Test type
* 0- Keys()
* 1- Min()
* 2- Max()
* 3... | [] | {
"number": "3.3.21",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Exercise",
"code_execution": false
} |
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 exp... | // Exercise23_23TreesWithoutBalance.java
package chapter3.section3;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 24/06/17.
*/
public class Exercise23_23TreesWithoutBalanc... | [] | {
"number": "3.3.23",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter3.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 28/06/17.
*/
public class Exercise27_AllowRightLeaningRedLinks {
private class RedBlackTopDown234RightLeaningBST<Key extends Comparable<Key>, Value> extends Exercise25_TopDown234Trees.RedBlackTopDown234BST<Key, Va... | [] | {
"number": "3.3.27",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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). | package chapter3.section3;
import edu.princeton.cs.algs4.StdDraw;
/**
* Created by Rene Argento on 18/06/17.
*/
public class Exercise31_TreeDrawing {
public class RedBlackBSTDrawable<Key extends Comparable<Key>, Value> extends RedBlackBST<Key, Value> {
private class Node {
Key key;
... | [] | {
"number": "3.3.31",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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 giv... | // Exercise32_AVLTrees.java
package chapter3.section3;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 29/06/17.
*/
// Based on http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/AVLTreeST.java.html
// Thank... | [] | {
"number": "3.3.32",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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... | package chapter3.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 29/06/17.
*/
@SuppressWarnings("unchecked")
public class Exercise33_Certification {
private class RedBlackBSTCertification<Key extends Comparable<Key>, Value> extends RedBlackBST<Key, Value> {
public boole... | [] | {
"number": "3.3.33",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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 112 such trees, respectively. (Hint: Use a symbol table.) | package chapter3.section3;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by Rene Argento on 01/07/17.
*/
@SuppressWarnings("unchecked")... | [] | {
"number": "3.3.34",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
2-3 trees. Write a program TwoThreeST.java that uses two node types to implement 2-3 search trees directly. | package chapter3.section3;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 02/07/17.
*/
@SuppressWarnings("unchecked")
public class Exercise35_23Trees {
private static class TwoThreeST<Key extends Comparable<K... | [] | {
"number": "3.3.35",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | Search is the direct multiway-search generalization. In a node containing `k` sorted keys (`1 <= k <= 7`), compare the search key with the node keys, return if equal, otherwise follow one of the `k + 1` child links determined by the interval containing the key.
Insertion is the B-tree insertion algorithm for order 8. ... | [] | {
"number": "3.3.36",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | 3.3.37 - Memoryless
It can be seen that red-black BSTs are not memoryless by observing the following example:
Inserting keys in the order N, G, D, F, E, O, L, K, M generates the red-black tree:
(B)G
(B)E (B)N
(B)D (B)F (R)L (B)O
(B)K (B)M
Tree after inserting min... | [] | {
"number": "3.3.37",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter3.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 19/06/17.
*/
public class Exercise39_DeleteTheMinimum {
private class RedBlackBSTDeleteMin<Key extends Comparable<Key>, Value> extends RedBlackBST<Key, Value> {
public void deleteMin() {
if (i... | [] | {
"number": "3.3.39",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | package chapter3.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 21/06/17.
*/
public class Exercise40_DeleteTheMaximum {
private class RedBlackBSTDeleteMax<Key extends Comparable<Key>, Value> extends RedBlackBST<Key, Value> {
public void deleteMax() {
if (... | [] | {
"number": "3.3.40",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
Delete. Implement the delete() operation for red-black BSTs, combining the methods of the previous two exercises with the delete() operation for BSTs. | package chapter3.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 22/06/17.
*/
public class Exercise41_Delete {
private class RedBlackBSTDelete<Key extends Comparable<Key>, Value> extends RedBlackBST<Key, Value> {
public void delete(Key key) {
if (isEmpty())... | [] | {
"number": "3.3.41",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.3,
"section_title": "Balanced Search Trees",
"type": "Creative Problem",
"code_execution": false
} |
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. | 3.4.6
Proposition: With keys that are t-bit integers, for a hash function with prime M, each key bit has the property that there exist two keys differing only in that bit that have different hash values.
Proof: Consider the hash function k % M where k is an integer and M is a prime number.
Every time that we modify ... | [] | {
"number": "3.4.6",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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? | 3.4.7
If and only if a and M are coprime, the change will mix up the bits sufficiently well that a nonprime M can be used.
Proof:
1- (a * k) % M = hash
2- This means that a * k = M * q + hash, which is equivalent to hash = a * k - M * q, where q is a natural number.
3- Now let's consider that a and M are not coprime.... | [] | {
"number": "3.4.7",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.4.8
As we have seen on exercise 2.5.31, probability theory says that after generating N random values, the number of distinct values is about M(1 - e^(-a)) where M = the maximum value generated - 1 (in this case, the hash table length - 1), N = number of keys generated and a = N / M.
In this case M = N, so the hash... | [] | {
"number": "3.4.8",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
Implement an eager delete() method for SeparateChainingHashST. | package chapter3.section4;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 20/07/17.
*/
@SuppressWarnings("unchecked")
public class Exercise9 {
private class SeparateChainingHashTableWithDelete<Key, Value> extends SeparateChainingHashTable<Key, Value> {
public void delete(Key ke... | [] | {
"number": "3.4.9",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.4.10
M = 16
key hash value
E 7 0
0 null 8 null
1 null 9 null
2 null 10 null
3 null 11 null
4 null 12 null
5 null 13 null
6 null 14 null
7 E0 15 null
key hash value
A 11 1
0 null 8 null
1 null 9 null
2 null 10 null
3 null 11 A1
4 null 12 null
... | [] | {
"number": "3.4.10",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.4.11
key hash value
E 3 0
0 null 2 null
1 null 3 E0
key hash value
A 3 1
0 A1 2 null
1 null 3 E0
Doubles hash table size and M becomes 8
0 null 4 null
1 null 5 null
2 null 6 null
3 null 7 null
Reinsert A1
key hash value
A 3 1
0 null 4 null
1 null... | [] | {
"number": "3.4.11",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
Which of the following scenarios leads to expected linear running time for a random search hit in a linear-probing hash table?
a. All keys hash to the same index.
b. All keys hash to different indices.
c. All keys hash to an even-numbered index.
d. All keys hash to different even-numbered indices. | Only scenario (a) necessarily leads to expected linear running time for a random search hit: if all keys hash to the same table index, they form one contiguous cluster, and a random hit probes a linear number of positions on average.
Scenario (b) is the best case. Scenario (d) is not necessarily linear, because differ... | [] | {
"number": "3.4.13",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
Which of the following scenarios leads to expected linear running time for a search miss in a linear-probing hash table, assuming the search key is equally likely to hash to each table position?
a. All keys hash to the same index.
b. All keys hash to different indices.
c. All keys hash to an even-numbered index.
d. Al... | Scenario (a) necessarily gives expected linear time for a search miss: all keys form one large cluster, and misses that hash into or before that cluster scan a linear number of entries.
Scenario (c) can also be linear when the even-index restriction creates a linear-size cluster, but it is not guaranteed solely from t... | [] | {
"number": "3.4.14",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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? | 3.4.15
In the worst case all keys hash to the same index.
The exercise description does not mention the initial hash table size. This is important to compute the number of compares in a hash table with array resizing. This exercise answer assumes that the initial hash table size is N and its size is expanded with doub... | [] | {
"number": "3.4.15",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section4;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 21/07/17.
*/
@SuppressWarnings("unchecked")
public class Exercise18 {
private class SeparateChainingHashTableResize<Key, Value> extends SeparateChainingHashTable<Key, Value>{
private int averageListSize;
... | [] | {
"number": "3.4.18",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section4;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 21/07/17.
*/
// Thanks to faame (https://github.com/faame) for fixing a bug in the compare count in this exercise.
// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/236
public class Exercise20 {
... | [] | {
"number": "3.4.20",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section4;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by Rene Argento on 21/07/17.
*/
public class Exercise21 {
private class LinearProbingHashTableAvgSearchMissCost<Key, Value> extends LinearProbingHashTable<Key, Value> {
LinearProbing... | [] | {
"number": "3.4.21",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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. | 3.4.23
Given R = 256 and M = 255, we shall prove that the hash of all strings with the same collection of chars is the same.
In fact, we can prove the proposition that hash(string) = (sum of chars) % 255 for all strings by induction on string
length.
For any string with only one char, the proposition holds trivially.... | [] | {
"number": "3.4.23",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Exercise",
"code_execution": false
} |
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 an... | Because 11 mod 3 and 17 mod 3 are both 2, the two hash functions are identical for this table size. Double probing therefore degenerates to ordinary separate chaining with one candidate chain.
Using A=1, B=2, ..., Z=26, the final chains are:
0: O, I, U
1: N, T, Q, E
2: Y, S, A
If new keys are inserted at the front o... | [] | {
"number": "3.4.27",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Creative Problem",
"code_execution": false
} |
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 ... | package chapter3.section4;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* Created by Rene Argento on 24/07/17.
*/
// Based on http://www.keithschwarz.com/interesting/code/cuckoo-hashm... | [] | {
"number": "3.4.31",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Creative Problem",
"code_execution": false
} |
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:
public int hashCode() {
int hash = 0;
for (int i = 0; i < length(); i ++)
hash = (hash * 31) + charAt(i);
return hash;
}
Strong hint: Aa and BB have t... | The two strings `"Aa"` and `"BB"` have the same Java `String.hashCode()` value and the same length. Therefore any concatenation of equal-length blocks chosen from `{ "Aa", "BB" }` also has the same hash as any other concatenation with the same number of blocks.
To get at least `2^N` strings of length exactly `2^N`, us... | [] | {
"number": "3.4.32",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Creative Problem",
"code_execution": false
} |
Bad hash function. Consider the following hashCode() implementation for String, which was used in early versions of Java:
public int hashCode() {
int hash = 0;
int skip = Math.max(1, length()/8);
for (int i = 0; i < length(); i += skip)
hash = (hash * 37) + charAt(i);
return hash;
}
Explain why you think the d... | 3.4.33 - Bad hash function
I think the designers chose this implementation because it multiplies the hash value by a prime number several times. By skipping max(1, 1/8) chars in every iteration, it guarantees that the multiplication will only happen a constant number of time, improving the performance of the hash func... | [] | {
"number": "3.4.33",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.4,
"section_title": "Hash Tables",
"type": "Creative Problem",
"code_execution": false
} |
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.) | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 03/08/17.
*/
@SuppressWarnings("unchecked")
public class Exercise6 {
private class HashSETint {
private int keysSize;
private int siz... | [] | {
"number": "3.5.6",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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.) | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 05/08/17.
*/
public class Exercise7 {
private class SETint {
private static final boolean RED = true;
private static f... | [] | {
"number": "3.5.7",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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(). | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 05/08/17.
*/
public class Exercise8 {
@SuppressWarnings("unchecked")
private class LinearProbingHashTableDuplicateKeys<Key, Value> {
priv... | [] | {
"number": "3.5.8",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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(). | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 05/08/17.
*/
public class Exercise9 {
/**
* This tree has the following property:
*
* Let x be a node in the binary sea... | [] | {
"number": "3.5.9",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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(). | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 05/08/17.
*/
public class Exercise10 {
/**
* This tree has the following property:
*
* Let x be a node in the red-black... | [] | {
"number": "3.5.10",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
Develop a MultiSET class that is like SET, but allows equal keys and thus implements a mathematical multiset. | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 06/08/17.
*/
public class Exercise11 {
/**
* This tree has the following property:
*
* Let x be a node in the red-black... | [] | {
"number": "3.5.11",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
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. | package chapter3.section5;
import chapter3.section3.RedBlackBST;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import util.Constants;
/**
* Created by Rene Argento on 06/08/17.
*/
public class RangeLookupCSV {
// Parameters example: 0: csv_file.txt... | [] | {
"number": "3.5.13",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
Develop and test a static method invert() that takes as argument an ST<String, Bag<String>> and produces as return value the inverse of the given symbol table (a symbol table of the same type). | package chapter3.section5;
import chapter1.section3.Bag;
import chapter3.section3.RedBlackBST;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 06/08/17.
*/
public class Exercise14 {
private static RedBlackBST<String, Bag<String>> invert(RedBlackBST<String, Bag<String>> symbolTable) {
... | [] | {
"number": "3.5.14",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"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.