question stringlengths 34 5.53k | answer stringlengths 21 101k | support_files listlengths 0 6 | metadata unknown |
|---|---|---|---|
Write a program that takes a string on standard input and an integer k as command-line argument and puts on standard output a sorted list of the k-grams found in the string, each followed by its index in the string. | Use a symbol table from each k-gram to all positions where it appears; a plain `ST<String, Integer>` loses duplicate k-grams.
```java
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.RedBlackBST;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class KGrams {
pub... | [] | {
"number": "3.5.15",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Exercise",
"code_execution": false
} |
Multisets. After referring to Exercises 3.5.2 and 3.5.3 and the previous exercise, develop APIs MultiHashSET and MultiSET for multisets (sets that can have equal keys) and implementations SeparateChainingMultiSET and BinarySearchMultiSET for multisets and ordered multisets, respectively. | package chapter3.section5;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 07/08/17.
*/
@SuppressWarnings("unchecked")
public class Exercise18_Multisets {
/**
* API for MultiHashSET
*
* public c... | [] | {
"number": "3.5.18",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
Concordance. Write an ST client Concordance that puts on standard output a concordance of the strings in the standard input stream (see page 498). | package chapter3.section5;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Rene Argento on 08/08/17.
*/
public class Concordance {
private class Concordance {
... | [] | {
"number": "3.5.20",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
Inverted concordance. Write a program InvertedConcordance that takes a concordance on standard input and puts the original string on standard output stream. Note: This computation is associated with a famous story having to do with the Dead Sea Scrolls. The team that discovered the original tablets enforced a secrecy r... | package chapter3.section5;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Rene Argento on 08/08/17.
*/
public class InvertedConcordance {
private class InvertedConcor... | [] | {
"number": "3.5.21",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
Sparse matrices. Develop an API and an implementation for sparse 2D matrices. Support matrix addition and matrix multiplication. Include constructors for row and column vectors. | package chapter3.section5;
import chapter3.section4.SeparateChainingHashTable;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 15/08/17.
*/
public class Exercise23_SparseMatrices {
private interface SparseMatrixAPI {
SparseMatrix sum(SparseMatrix sparseMatrix);
SparseMatr... | [] | {
"number": "3.5.23",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
List. Develop an implementation of the following API:
public class List<Item> implements Iterable<Item>
List() create a list
void addFront(Item item) add item to the front
void addBack(Item item) add item to the back
Item deleteFront() remove from the front
Item deleteBack() remove from the back
void delete(Item ... | package chapter3.section5;
import chapter3.section3.RedBlackBST;
import chapter3.section4.SeparateChainingHashTable;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by Rene Argento on 17/08/17.
*/
public class Exercise27_List {
... | [] | {
"number": "3.5.27",
"chapter": 3,
"chapter_title": "Searching",
"section": 3.5,
"section_title": "Applications",
"type": "Creative Problem",
"code_execution": false
} |
What is the maximum number of edges in a graph with V vertices and no parallel edges? What is the minimum number of edges in a graph with V vertices, none of which are isolated? | The maximum number of edges in a simple undirected graph with `V` vertices is
`V(V - 1) / 2`.
If no vertex may be isolated, the minimum number of edges is `ceil(V / 2)`, not `V - 1`: pair up vertices with one edge per pair, and when `V` is odd use two edges to connect the last three vertices as a path. | [] | {
"number": "4.1.1",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Draw, in the style of the figure in the text (page 524), the adjacency lists built by Graph’s input stream constructor for the file tinyGex2.txt depicted at left. | 4.1.2
adj[]
0 -> 5 -> 2 -> 6
1 -> 4 -> 8 -> 11
2 -> 5 -> 6 -> 0 -> 3
3 -> 10 -> 6 -> 2
4 -> 1 -> 8
5 -> 0 -> 10 -> 2
6 -> 2 -> 3 -> 0
7 -> 8 -> 11
8 -> 1 -> 11 -> 7 -> 4
9 ->
10 -> 5 -> 3
11 -> 8 -> 7 -> 1
| [] | {
"number": "4.1.2",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Consider the four-vertex graph with edges 0-1, 1-2, 2-3, and 3-0. Draw an array of adjacency-lists that could not have been built calling addEdge() for these edges no matter what order. | 4.1.6
The edges form a cycle, so changing the connection order of one of the vertices' adjacency list creates an impossible sequence of connections.
adj[]
0 -> 1 -> 3 (the original was 0 -> 3 -> 1)
1 -> 2 -> 0
2 -> 3 -> 1
3 -> 0 -> 2
| [] | {
"number": "4.1.6",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Show, in the style of the figure on page 533, a detailed trace of the call dfs(0) for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). Also, draw the tree represented by edgeTo[]. | 4.1.9
marked[] adj[]
dfs (0) 0 T 0 5 2 6
1 1 4 8 11
2 2 5 6 0 3
3 3 10 6 2
4 4 1 8
5 5 0 10 2
6 6 2 3 0
7 ... | [] | {
"number": "4.1.9",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Prove that every connected graph has a vertex whose removal (including all adjacent edges) will not disconnect the graph, and write a DFS method that finds such a vertex. Hint: Consider a vertex whose adjacent vertices are all marked. | Every connected graph has at least one vertex whose removal does not disconnect the graph: take any DFS tree and choose a leaf of that DFS tree. Removing a leaf from a tree leaves the tree connected on the remaining vertices; since the original graph contains at least the DFS-tree edges, the original graph with that le... | [] | {
"number": "4.1.10",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Draw the tree represented by edgeTo[] after the call bfs(G, 0) in ALGORITHM 4.2 for the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see Exercise 4.1.2). | 4.1.11
Tree represented by edgeTo[] after call to bfs(G, 0):
0
5 2 6
10 3
| [] | {
"number": "4.1.11",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
What does the BFS tree tell us about the distance from v to w when neither is at the root? | The BFS tree gives exact shortest-path distances only from the root to every vertex. If neither `v` nor `w` is the root, the distance between them in the BFS tree is just the length of one particular `v-w` path, hence an upper bound on their true graph distance. The graph may contain a shorter path using edges that are... | [] | {
"number": "4.1.12",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Suppose you use a stack instead of a queue when running breadth-first search. Does it still compute shortest paths? | 4.1.14
If we use a stack instead of a queue when running breadth-first search, it may not compute shortest paths.
This can be seen in the following graph:
0 (source)
/ \
1 - 2
| |
4 - 3
If the edge 0 - 2 is inserted before the edge 0 - 1:
Using a stack, the distance from 0 to 4 will be 3.
Using a queue, the dis... | [] | {
"number": "4.1.14",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Show, in the style of the figure on page 545, a detailed trace of CC for finding the connected components in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). | 4.1.19
count marked[] id[]
0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11
dfs(0) 0 T 0
dfs(5) 0 T T 0 0
check 0
dfs(10) 0 ... | [] | {
"number": "4.1.19",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Show, in the style of the figures in this section, a detailed trace of Cycle for finding a cycle in the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the Cycle constructor, in the worst case? | 4.1.20
Has Cycle? marked[]
F 0 1 2 3 4 5 6 7 8 9 10 11
dfs(0) T
dfs(5) T T
check 0 F
dfs(10) T T T
check 5 F
... | [] | {
"number": "4.1.20",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Show, in the style of the figures in this section, a detailed trace of TwoColor for finding a two-coloring of the graph built by Graph’s input stream constructor for the file tinyGex2.txt (see EXERCISE 4.1.2). What is the order of growth of the running time of the TwoColor constructor, in the worst case? | 4.1.21
Is 2-colorable? marked[] color[]
T 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11
dfs(0) T F F F F F F F F F F F F
dfs(5) T ... | [] | {
"number": "4.1.21",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Compute the number of connected components in movies.txt, the size of the largest component, and the number of components of size less than 10. Find the eccentricity, diameter, radius, a center, and the girth of the largest component in the graph. Does it contain Kevin Bacon? | 4.1.24
Number of connected components: 33
Size of the largest component: 118774
Number of components of size less than 10: 5
Does the largest component contain Kevin Bacon: Yes
Eccentricity, diameter, radius, center and girth:
The strategy for computing the eccentricity, diameter, radius, center and girth of the lar... | [] | {
"number": "4.1.24",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Determine the amount of memory used by Graph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4. | 4.1.27
Integer
* object overhead -> 16 bytes
* int value -> 4 bytes
* padding -> 4 bytes
Amount of memory needed: 16 + 4 + 4 = 24 bytes
Node
* object overhead -> 16 bytes
* extra overhead for reference to the enclosing instance -> 8 bytes
* Item reference (item) -> 8 bytes
* Node reference (next) -> 8 bytes
Amount of... | [] | {
"number": "4.1.27",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Two graphs are isomorphic if there is a way to rename the vertices of one to make it identical to the other. Draw all the nonisomorphic graphs with two, three, four, and five vertices. | 4.1.28
Non-isomorphic graphs:
There are 2 non-isomorphic graphs with 2 vertices:
o o
o-o
There are 4 non-isomorphic graphs with 3 vertices:
o
o o
o
o-o
o-o-o
o
/ \
o-o
There are 11 non-isomorphic graphs with 4 vertices:
o o o o
o-o o o
o-o-o o
o-o-o-o
o-o o-o
o
|
o
/ \
o o
o
/ \
o---o o
o-... | [] | {
"number": "4.1.28",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Exercise",
"code_execution": false
} |
Eulerian and Hamiltonian cycles. Consider the graphs defined by the following four sets of edges:
0-1 0-2 0-3 1-3 1-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8
0-1 0-2 0-3 1-3 0-3 2-5 5-6 3-6 4-7 4-8 5-8 5-9 6-7 6-9 8-8
0-1 1-2 1-3 0-3 0-4 2-5 2-9 3-6 4-7 4-8 5-8 5-9 6-7 6-9 7-8
4-1 7-9 6-2 7-3 5-0 0-2 0-8 1-6 3-9 6-3 2-... | 4.1.30 - Eulerian and Hamiltonian cycles
An Eulerian cycle (or Eulerian circuit) is a path which starts and ends at the same vertex and includes every edge exactly once.
A Hamiltonian cycle is a path which starts and ends at the same vertex and includes every vertex exactly once (except for the source, which is visite... | [] | {
"number": "4.1.30",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Graph enumeration. How many different undirected graphs are there with V vertices and E edges (and no parallel edges)? | For an undirected graph with V labeled vertices and no parallel edges, each possible edge is determined by an unordered pair of vertices.
If self-loops are not allowed, there are binomial(V, 2) possible edges, so the number of graphs with exactly E edges is
binomial(binomial(V, 2), E)
If self-loops are allowed, ... | [] | {
"number": "4.1.31",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Odd cycles. Prove that a graph is two-colorable (bipartite) if and only if it contains no odd-length cycle. | 4.1.33 - Odd cycles
A graph is two-colorable (bipartite) if and only if it contains no odd-length cycle.
Proof:
1- Proving that a graph with an odd-length cycle cannot be bipartite:
If a graph G is bipartite with vertex sets V1 and V2, every step along a walk takes you either from V1 to V2 or from V2 to V1. To end up... | [] | {
"number": "4.1.33",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Biconnectedness. A graph is biconnected if every pair of vertices is connected by two disjoint paths. An articulation point in a connected graph is a vertex that would disconnect the graph if it (and its adjacent edges) were removed. Prove that any graph with no articulation points is biconnected. Hint: Given a pair of... | Assume the connected graph has no articulation point. For any two vertices `s` and `t`, take a simple path `P` from `s` to `t`. If an internal vertex `v` of `P` were present on every `s-t` path, then removing `v` would separate `s` from `t`, making `v` an articulation point. Since there are no articulation points, no i... | [] | {
"number": "4.1.35",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.1,
"section_title": "Undirected Graphs",
"type": "Creative Problem",
"code_execution": false
} |
What is the maximum number of edges in a digraph with V vertices and no parallel edges? What is the minimum number of edges in a digraph with V vertices, none of which are isolated? | The maximum number of edges in a simple digraph with `V` vertices and no parallel edges is
`V(V - 1)`,
because each ordered pair of distinct vertices may appear once.
If "not isolated" means every vertex has total degree at least 1, the minimum number of directed edges is `ceil(V / 2)`: one directed edge covers two ... | [] | {
"number": "4.2.1",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Draw, in the style of the figure in the text (page 524), the adjacency lists built by Digraph’s input stream constructor for the file tinyDGex2.txt depicted at left. | 4.2.2
adj[]
0 -> 6 -> 5
1 ->
2 -> 0 -> 3
3 -> 10 -> 6
4 -> 1
5 -> 10 -> 2
6 -> 2
7 -> 8 -> 11
8 -> 1 -> 4
9 ->
10 -> 3
11 -> 8
| [] | {
"number": "4.2.2",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Develop a test client for Digraph. | package chapter4.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 19/10/17.
*/
public class Exercise6 {
public static void main(String[] args) {
Digraph digraph = new Digraph(5);
digraph.addEdge(0, 1);
digraph.addEdge(0, 2);
digraph.addEdge(0, 3)... | [] | {
"number": "4.2.6",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Write a method that checks whether or not a given permutation of a DAG’s vertices is a topological order of that DAG. | package chapter4.section2;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Rene Argento on 21/10/17.
*/
// Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting a more efficient solution:
// https://github.com/reneargento/algorithms-se... | [] | {
"number": "4.2.9",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Given a DAG, does there exist a topological order that cannot result from applying a DFS-based algorithm, no matter in what order the vertices adjacent to each vertex are chosen? Prove your answer. | No. Every topological order of a DAG can be produced as the reverse postorder of DFS for a suitable choice of the order in which DFS starts vertices.
Let `v1, v2, ..., vV` be any topological order. Run the outer DFS loop in the reverse order `vV, ..., v2, v1`. In a DAG, every edge goes from an earlier vertex in the to... | [] | {
"number": "4.2.10",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Describe a family of sparse digraphs whose number of directed cycles grows exponentially in the number of vertices. | 4.2.11
A family of sparse digraphs whose number of directed cycles grows exponentially in the number of vertices is the following:
Take an n-cycle and make every edge a parallel edge. Now there are 2^n cycles.
Example:
o -> o
^ |
| v
o <- o
becomes
o -> o
^^->||
|| ||
||<-vv
o <- o
Another possibility, to... | [] | {
"number": "4.2.11",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
How many edges are there in the transitive closure of a digraph that is a simple directed path with V vertices and V–1 edges? | In a simple directed path with vertices v0 -> v1 -> ... -> v(V-1), vertex vi can reach exactly the vertices vj with j > i.
The transitive closure therefore has one directed edge vi -> vj for every ordered pair with i < j. The number of such pairs is
(V - 1) + (V - 2) + ... + 1 = V(V - 1) / 2
So the transitive cl... | [] | {
"number": "4.2.12",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Prove that the strong components in G^R are the same as in G. | 4.2.14
The strong components in Gr are the same as in G.
Proof:
For each strong component in G, every pair of vertices u and v has a path that can go from vertex u to vertex v and another path that can go from vertex v to vertex u.
Reversing each edge direction in Gr maintains these paths, since the only modification... | [] | {
"number": "4.2.14",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Exercise",
"code_execution": false
} |
Topological sort and BFS. Explain why the following algorithm does not necessarily produce a topological order: Run BFS, and label the vertices by increasing distance to their respective source. | 4.2.19 - Topological sort and BFS
The algorithm does not necessarily produce a topological order because some vertices closer to the source may be preceded by vertices further from the source in a topological order.
Example:
Consider the graph:
0 -> 1 -> 2 -> 3 -> 4 -> 5
| /
v ... | [] | {
"number": "4.2.19",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Directed Eulerian cycle. An Eulerian cycle is a directed cycle that contains each edge exactly once. Write a graph client Euler that finds an Eulerian cycle or reports that no such tour exists. Hint: Prove that a digraph G has a directed Eulerian cycle if and only if G is connected and each vertex has its indegree equa... | package chapter4.section2;
import chapter1.section3.Stack;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
/**
* Created by Rene Argento on 23/10/17.
*/
//Based on https://algs4.cs.princeton.edu/42digraph/DirectedEulerianCycle.java.html
@SuppressWarnings("unchecked")
public class Euler {
priv... | [] | {
"number": "4.2.20",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
LCA of a DAG. Given a DAG and two vertices v and w, find the lowest common ancestor (LCA) of v and w. The LCA of v and w is an ancestor of v and w that has no descendants that are also ancestors of v and w. Computing the LCA is useful in multiple inheritance in programming languages, analysis of genealogical data (find... | package chapter4.section2;
import chapter1.section3.Queue;
import chapter3.section5.HashSet;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by Rene Argento on 24/10/17.
*/
// Thanks to pharrukh (https://github.com/pharrukh) for suggesting to move part of the sources computing to the D... | [] | {
"number": "4.2.21",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Hamiltonian path in DAGs. Given a DAG, design a linear-time algorithm to determine whether there is a directed path that visits each vertex exactly once. | package chapter4.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 25/10/17.
*/
public class Exercise32_HamiltonianPathInDAGs {
// A DAG has a Hamiltonian path if and only if there is a directed edge between each pair of consecutive vertices
// in its topological order
pu... | [] | {
"number": "4.2.24",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Digraph enumeration. Show that the number of different V-vertex digraphs with no parallel edges is 2^(V^2). (How many digraphs are there that contain V vertices and E edges?) Then compute an upper bound on the percentage of 20-vertex digraphs that could ever be examined by any computer, under the assumptions that every... | With V labeled vertices and no parallel edges, there are V^2 possible directed edges if self-loops are allowed: one possible edge (v, w) for each ordered pair of vertices.
Each possible edge is either present or absent, so the number of V-vertex digraphs is
```text
2^(V^2)
```
If the digraph must contain exactly E e... | [] | {
"number": "4.2.27",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
DAG enumeration. Give a formula for the number of V-vertex DAGs with E edges. | For a fixed topological order of the V vertices, only edges that point forward in that order are allowed. There are V(V - 1) / 2 such possible edges, so the fixed-order count is:
```text
binomial(V(V - 1) / 2, E)
```
For labeled DAGs where the topological order is not fixed, that expression is not exact because a DAG... | [] | {
"number": "4.2.28",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Queue-based topological sort. Develop a topological sort implementation that maintains a vertex-indexed array that keeps track of the indegree of each vertex. Initialize the array and a queue of sources in a single pass through all the edges, as in EXERCISE 4.2.7. Then, perform the following operations until the source... | package chapter4.section2;
import chapter1.section3.Queue;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 27/10/17.
*/
public class Exercise39_QueueBasedTopologicalSort {
private int[] ranks;
// O(V + E)
public int[] topologicalSort(Digraph digraph) {
DirectedCycle dir... | [] | {
"number": "4.2.30",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Euclidean digraphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanDigraph for graphs whose vertices are points in the plane, so that you can work with graphical representations. | package chapter4.section2;
import chapter1.section3.Bag;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import util.DrawUtilities;
import util.DrawUtilities.Coordinate;
import java.awt.*;
/**
* Created by Rene Argento on 26/10/17.
*/
@SuppressWarnings("unchecked")
public class Exercis... | [] | {
"number": "4.2.31",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.2,
"section_title": "Directed Graphs",
"type": "Creative Problem",
"code_execution": false
} |
Prove that you can rescale the weights by adding a positive constant to all of them or by multiplying them all by a positive constant without affecting the MST. | 4.3.1
It is possible to rescale the weights by adding a positive constant to all of them or multiplying them all by a positive constant without affecting the MST.
Proof by contradiction:
Consider that after adding a positive constant to all weights (or multiplying them all by a positive constant) the new MST' is diff... | [] | {
"number": "4.3.1",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Draw all of the MSTs of the following graph, with all edge weights equal. The graph has vertices `1..8` and edges:
`1-2, 1-3, 2-4, 3-4, 4-5, 3-6, 4-7, 5-8, 6-7, 7-8`. | 4.3.2
MSTs:
1-2
|
3-4-5
|
6-7-8
1-2
|
3-4-5
|
6-7-8
1 2
| |
3-4-5
|
6-7-8
1-2
| |
3-4 5
|
6-7-8
1-2
|
3-4-5
|
6-7-8
1-2
|
3-4-5
|
6-7-8
1 2
| |
3-4-5
|
6-7-8
1-2
| |
3-4 5
|
6-7-8
1-2
|
3 4-5
| |
6-7-8
1-2
|
3 4-5
| |
6-7-8
1 2
| |
3 4-5
| |
6-7-8
... | [] | {
"number": "4.3.2",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Give the MST of the weighted graph obtained by deleting vertex 7 from tinyEWG.txt (see page 604). | 4.3.6
MST
Vertex1 Vertex2 Weight
0 2 0.26
2 3 0.17
1 3 0.29
1 5 0.32
4 5 0.35
6 2 0.40
| [] | {
"number": "4.3.6",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Implement the constructor for EdgeWeightedGraph that reads a graph from the input stream, by suitably modifying the constructor from Graph (see page 526). | package chapter4.section3;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import util.Constants;
/**
* Created by Rene Argento on 07/11/17.
*/
public class Exercise9 {
public class EdgeWeightedGraphWithInputStreamConstructor extends EdgeWeightedGraph {
public EdgeWeightedGraph... | [] | {
"number": "4.3.9",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Develop an EdgeWeightedGraph implementation for dense graphs that uses an adjacency-matrix (two-dimensional array of weights) representation. Disallow parallel edges. | package chapter4.section3;
import chapter1.section3.Bag;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 07/11/17.
*/
public class Exercise10 {
public class EdgeWeightedGraphAdjacencyMatrix {
private final int vertices;
private int edges... | [] | {
"number": "4.3.10",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Determine the amount of memory used by EdgeWeightedGraph to represent a graph with V vertices and E edges, using the memory-cost model of SECTION 1.4. | 4.3.11
Edge
* object overhead -> 16 bytes
* int value (vertex1) -> 4 bytes
* int value (vertex2) -> 4 bytes
* double value (weight) -> 8 bytes
Amount of memory needed: 16 + 4 + 4 + 8 = 32 bytes
Node
* object overhead -> 16 bytes
* extra overhead for reference to the enclosing instance -> 8 bytes
* Item reference (ite... | [] | {
"number": "4.3.11",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Suppose that a graph has distinct edge weights. Does its shortest edge have to belong to the MST? Can its longest edge belong to the MST? Does a min-weight edge on every cycle have to belong to the MST? Prove your answer to each question or give a counterexample. | Considering a graph with distinct edge weights:
* The lightest edge must belong to the MST. It is the unique minimum-weight edge across the cut that separates one of its endpoints from the rest of the graph, so the cut property forces it into every MST.
* The heaviest edge can belong to the MST. Example: triangle `A-... | [] | {
"number": "4.3.12",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Given an MST for an edge-weighted graph G, suppose that an edge in G that does not disconnect G is deleted. Describe how to find an MST of the new graph in time proportional to E. | 4.3.14
There are 2 possible cases when an edge from G is deleted.
1- Case 1: The deleted edge is not part of the given MST (this can be checked in linear time)
In this case the MST of the new graph remains the same as the original MST.
The only situations in which an MST would change would be if a new edge was added ... | [] | {
"number": "4.3.14",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Suppose that you use a priority-queue implementation that maintains a sorted list. What would be the order of growth of the worst-case running time for Prim’s algorithm and for Kruskal’s algorithm for graphs with V vertices and E edges? When would this method be appropriate, if ever? Defend your answer. | A sorted-list priority queue makes `delete-min` cheap but makes insertion and key updates expensive.
For lazy Prim's algorithm, edges are inserted into the priority queue. There can be `Theta(E)` insertions, each costing `Theta(E)` in the worst case to keep the list sorted, so the worst-case running time is `Theta(E^2... | [] | {
"number": "4.3.19",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
True or false: At any point during the execution of Kruskal’s algorithm, each vertex is closer to some vertex in its subtree than to any vertex not in its subtree. Prove your answer. | 4.3.20
At any point during the execution of Kruskal's algorithm, each vertex is closer to some vertex in its subtree than to any vertex not in its subtree.
True. Since Kruskal's algorithm adds edges to an MST by order of weight/length, if there is an edge e = v-w of length 1 and there is an edge f = v-z of length 2, ... | [] | {
"number": "4.3.20",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Provide an implementation of edges() for PrimMST (page 622). | This method belongs inside `PrimMST`, where `edgeTo[]` is available. Enqueue every non-null edge; vertex 0 usually has no incoming MST edge.
```java
public Iterable<Edge> edges() {
Queue<Edge> mst = new Queue<Edge>();
for (int v = 0; v < edgeTo.length; v++) {
if (edgeTo[v] != null) mst.enqueue(edgeTo[v... | [] | {
"number": "4.3.21",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Exercise",
"code_execution": false
} |
Reverse-delete algorithm. Develop an implementation that computes the MST as follows: Start with a graph containing all of the edges. Then repeatedly go through the edges in decreasing order of weight. For each edge, check if deleting that edge will disconnect the graph; if not, delete it. Prove that this algorithm com... | // Exercise24_ReverseDeleteAlgorithm.java
package chapter4.section3;
import chapter1.section3.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by Rene Argento on 09/11/17.
*/
public class Exercise24_... | [] | {
"number": "4.3.24",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
Animations. Write a client program that does dynamic graphical animations of MST algorithms. Run your program for mediumEWG.txt to produce images like the figures on page 621 and page 624. | // Exercise27_Animations_Kruskal.java
package chapter4.section3;
import chapter1.section3.Queue;
import chapter1.section5.UnionFind;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;
import util.Constants;
im... | [] | {
"number": "4.3.27",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
Space-efficient data structures. Develop an implementation of the lazy version of Prim’s algorithm that saves space by using lower-level data structures for EdgeWeightedGraph and for MinPQ instead of Bag and Edge. Estimate the amount of memory saved as a function of V and E, using the memory-cost model of SECTION 1.4 (... | // Exercise28_SpaceEfficientDataStructures.java
package chapter4.section3;
import chapter1.section3.Bag;
import chapter1.section3.Queue;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import static chapter4.section3.Exercise28_SpaceEfficientDataSt... | [] | {
"number": "4.3.28",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
Euclidean weighted graphs. Modify your solution to EXERCISE 4.1.37 to create an API EuclideanEdgeWeightedGraph for graphs whose vertices are points in the plane, so that you can work with graphical representations. | package chapter4.section3;
import chapter1.section3.Bag;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.awt.*;
/**
* Created by Rene Argento on 11/11/17.
*/
@SuppressWarnings("unchecked")
public class Exercise30_EuclideanWeightedGraphs {
public class EuclideanEdgeWeig... | [] | {
"number": "4.3.30",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
MST weights. Develop implementations of weight() for LazyPrimMST, PrimMST, and KruskalMST, using a lazy strategy that iterates through the MST edges when the client calls weight().Then develop alternate implementations that use an eager strategy that maintains a running total as the MST is computed. | package chapter4.section3;
import chapter1.section3.Queue;
import chapter1.section5.UnionFind;
import chapter2.section4.IndexMinPriorityQueue;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 11/11/17.
*/
public class Exercise31_MSTWeights {
p... | [] | {
"number": "4.3.31",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
Certification. Write an MST and EdgeWeightedGraph client check() that uses the following cut optimality conditions implied by PROPOSITION J to verify that a proposed set of edges is in fact an MST: A set of edges is an MST if it is a spanning tree and every edge is a minimum-weight edge in the cut defined by removing t... | A correct certification client must check four things:
1. every proposed MST edge is actually an edge of the graph,
2. the proposed edges are acyclic,
3. the proposed edges connect all vertices, and
4. for every proposed edge `e`, after removing `e` from the proposed tree, no crossing graph edge is lighter than `e`.
... | [] | {
"number": "4.3.33",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.3,
"section_title": "Minimum Spanning Trees",
"type": "Creative Problem",
"code_execution": false
} |
True or false: Adding a constant to every edge weight does not change the solution to the single-source shortest-paths problem. | 4.4.1
False. Adding a constant to every edge weight will add more weight to the paths that are composed of more edges, possibly changing the solution to the single-source shortest-paths problem.
| [] | {
"number": "4.4.1",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Provide an implementation of toString() for EdgeWeightedDigraph. | package chapter4.section4;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import util.Constants;
/**
* Created by Rene Argento on 29/11/17.
*/
public class Exercise2 {
public class EdgeWeightedDigraphWithInConstructor extends EdgeWeightedDigraph {
public EdgeWeightedDigraphWit... | [] | {
"number": "4.4.2",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Give a trace that shows the process of computing the SPT of the digraph defined in EXERCISE 4.4.5 with the eager version of Dijkstra’s algorithm. | 4.4.6
Shortest-paths tree
0
edgeTo[]
0
1
2
3
4
5
6
7
distTo[]
0 0.00
1
2
3
4
5
6
7
Shortest-paths tree
0
/
v
4
edgeTo[]
0
1
2
3
4 0->4 0.38
5
6
7
distTo[]
0 0.00
1
2
3
4 0.38
5
6
7
Shortest-paths tree
5
^
| 0
| /
|v
4
edgeTo[]
0
1
2
3
4 0->... | [] | {
"number": "4.4.6",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
The table below, from an old published road map, purports to give the length of the shortest routes connecting the cities. It contains an error. Correct the table. Also, add a table that shows how to achieve the shortest routes.
```text
Providence Westerly New London Norwich
Providence - 5... | 4.4.9
The error is in the length of the shortest path between Norwich and Westerly. It cannot be 101 because there is a shorter path (Norwich -> New London -> Westerly) of length 30.
Corrected table
Providence Westerly New London Norwich
Providence - 53 54 48
Westerly ... | [] | {
"number": "4.4.9",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Consider the edges in the digraph defined in EXERCISE 4.4.4 to be undirected edges such that each edge corresponds to equal-weight edges in both directions in the edge-weighted digraph. Answer EXERCISE 4.4.6 for this corresponding edge-weighted digraph. | 4.4.10
Shortest-paths tree
0
edgeTo[]
0
1
2
3
4
5
6
distTo[]
0 0.00
1
2
3
4
5
6
Shortest-paths tree
2
^
/
0
edgeTo[]
0
1
2 0->2 0.26
3
4
5
6
distTo[]
0 0.00
1
2 0.26
3
4
5
6
Shortest-paths tree
2
^
/
0
/
v
4
edgeTo[]
0
1
2 0->2 0.26
3
4 ... | [] | {
"number": "4.4.10",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Use the memory-cost model of SECTION 1.4 to determine the amount of memory used by EdgeWeightedDigraph to represent a graph with V vertices and E edges. | 4.4.11
DirectedEdge
* object overhead -> 16 bytes
* int value (vertex1) -> 4 bytes
* int value (vertex2) -> 4 bytes
* double value (weight) -> 8 bytes
Amount of memory needed: 16 + 4 + 4 + 8 = 32 bytes
Node
* object overhead -> 16 bytes
* extra overhead for reference to the enclosing instance -> 8 bytes
* Item refere... | [] | {
"number": "4.4.11",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Adapt the DirectedCycle and Topological classes from SECTION 4.2 to use the EdgeWeightedDigraph and DirectedEdge APIs of this section, thus implementing EdgeWeightedCycleFinder and EdgeWeightedTopological classes. | package chapter4.section4;
import chapter1.section3.Stack;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 02/12/17.
*/
public class Exercise12 {
public class EdgeWeightedCycleFinder {
private boolean visited[];
private DirectedEdge[] edgeTo;
private Stack<Direct... | [] | {
"number": "4.4.12",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Show the paths that would be discovered by the two strawman approaches described on page 668 for the example tinyEWDn.txt shown on that page. | 4.4.14
Strawman I
Most negative edge weight = -1.40
New edge weights after adding 1.40 to all weights:
4->5 1.75
5->4 1.75
4->7 1.77
5->7 1.68
7->5 1.68
5->1 1.72
0->4 1.78
0->2 1.66
7->3 1.79
1->3 1.69
2->7 1.74
6->2 0.20
3->6 1.92
6->0 0.00
6->4 0.15
Paths discovered:
Shortest-paths tree
0
edgeTo[]
0
... | [] | {
"number": "4.4.14",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Find the lowest-weight cycle (best arbitrage opportunity) in the rates example from the text:
```text
USD 1 0.741 0.657 1.061 1.005
EUR 1.349 1 0.888 1.433 1.366
GBP 1.521 1.126 1 1.614 1.538
CHF 0.942 0.698 0.619 1 0.953
CAD 0.995 0.732 0.650 1.049 1
```
Edge weights are `-ln(rate... | 4.4.19
The lowest-weight cycle (best arbitrage opportunity) is the following:
EUR 1.366 -> CAD
CAD 0.995 -> USD
USD 0.741 -> EUR
| [] | {
"number": "4.4.19",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Find a currency-conversion table online or in a newspaper. Use it to build an arbitrage table. Note: Avoid tables that are derived (calculated) from a few values and that therefore do not give sufficiently accurate conversion information to be interesting. Extra credit: Make a killing in the money-exchange market! | 4.4.20
Based on: http://www.xe.com/currencyconverter/
Date: 2017-12-03 22:00 UTC
Currency-conversion table
USD EUR GBP INR AUD
USD 1.00000 0.84279 0.74426 64.5471 1.31644
EUR 1.18653 1.00000 0.88309 76.5871 1.56199
GBP 1.34361 1.13239 1.00000 86.7263 1.76878
INR 0.01549 0.01306 0.01153 1.00000... | [] | {
"number": "4.4.20",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Show, in the style of the trace in the text, the process of computing the SPT with the Bellman-Ford algorithm for the edge-weighted digraph of EXERCISE 4.4.5. | 4.4.21
Entries in queue for each pass have a * next to them.
The other entries in queue are for the next pass.
Shortest-paths tree
0
/
v
4
queue
0 *
4
edgeTo[]
0
1
2
3
4 0->4 0.38
5
6
7
distTo[]
0 0.00
1
2
3
4 0.38
5
6
7
Shortest-paths tree
5
^
| 7 0
| ^ |
|... | [] | {
"number": "4.4.21",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Exercise",
"code_execution": false
} |
Multisource shortest paths. Develop an API and implementation that uses Dijkstra’s algorithm to solve the multisource shortest-paths problem on edge-weighted digraphs with positive edge weights: given a set of sources, find a shortest-paths forest that enables implementation of a method that returns to clients the shor... | package chapter4.section4;
import chapter1.section3.Queue;
import chapter3.section5.HashSet;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 07/12/17.
*/
public class Exercise24_MultisourceShortestPaths {
public interface DijkstraMultisourceSPAPI {
double distTo(int vertex);
... | [] | {
"number": "4.4.24",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
Shortest paths in Euclidean graphs. Adapt our APIs to speed up Dijkstra’s algorithm in the case where it is known that vertices are points in the plane. | package chapter4.section4;
import chapter1.section3.Bag;
import chapter1.section3.Stack;
import chapter2.section4.IndexMinPriorityQueue;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import util.DrawUtilities;
import util.DrawUtilities.Coordinate;
import java.awt.*;
/**
* Created by R... | [] | {
"number": "4.4.27",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
Longest paths in DAGs. Develop an implementation AcyclicLP that can solve the longest-paths problem in edge-weighted DAGs, as described in PROPOSITION T. | package chapter4.section4;
import chapter1.section3.Stack;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 08/12/17.
*/
public class Exercise28_LongestPathsInDAGs {
public class AcyclicLP {
private AcyclicSP acyclicSP;
public AcyclicLP(EdgeWeightedDigraph edgeWeightedDi... | [] | {
"number": "4.4.28",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
All-pairs shortest path in graphs with no negative cycles. Articulate an API like the one implemented on page 656 for the all-pairs shortest-paths problem in graphs with no negative cycles. Develop an implementation that runs a version of Bellman-Ford to identify weights pi[v] such that for any edge v->w, the edge weig... | package chapter4.section4;
import chapter1.section3.Stack;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 09/12/17.
*/
// Johnson's algorithm
public class Exercise30_AllPairsShortestPathsDigraphsWithoutNegativeCycles {
public interface AllPairsShortestPathsDigraphsWithoutNegativeCyclesI... | [] | {
"number": "4.4.30",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
All-pairs shortest path on a line. Given a weighted line graph (undirected connected graph, all vertices of degree 2, except two endpoints which have degree 1), devise an algorithm that preprocesses the graph in linear time and can return the distance of the shortest path between any two vertices in constant time. | package chapter4.section4;
import chapter1.section3.Queue;
import chapter4.section3.Edge;
import chapter4.section3.EdgeWeightedGraph;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 09/12/17.
*/
public class Exercise31_AllPairsShortestPathsOnALine {
public class AllPairsShortestPathsOnAL... | [] | {
"number": "4.4.31",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
Shortest path in a grid. Given an N-by-N matrix of positive integers, find the shortest path from the (0, 0) entry to the (N-1, N-1) entry, where the length of the path is the sum of the integers in the path. Repeat the problem but assume you can only move right and down. | package chapter4.section4;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 10/12/17.
*/
public class Exercise33_ShortestPathInAGrid {
public Iterable<DirectedEdge> shortestPathInGridAll4Directions(double[][] matrix) {
EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigr... | [] | {
"number": "4.4.33",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
Bitonic shortest path. Given a digraph, find a bitonic shortest path from s to every other vertex (if one exists). A path is bitonic if there is an intermediate vertex v such that the edges on the path from s to v are strictly increasing and the edges on the path from v to t are strictly decreasing. The path should be ... | package chapter4.section4;
import chapter2.section4.PriorityQueueResize;
import chapter3.section4.SeparateChainingHashTable;
import edu.princeton.cs.algs4.StdOut;
import java.util.*;
/**
* Created by Rene Argento on 10/12/17.
*/
// If we didn't need a simple path (if repeated vertices were allowed), it would be po... | [] | {
"number": "4.4.35",
"chapter": 4,
"chapter_title": "Graphs",
"section": 4.4,
"section_title": "Shortest Paths",
"type": "Creative Problem",
"code_execution": false
} |
Give a trace for LSD string sort for the keys
no is th ti fo al go pe to co to th ai of th pa | 5.1.2
Trace for LSD string sort (same model as used in the book):
input d=1 d=0 output
no pa ai ai
is pe al al
th of co co
ti th fo fo
fo th go go
al th is is
go ti no no
pe ai of of
to al pa pa
co no pe ... | [] | {
"number": "5.1.2",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Give a trace for MSD string sort for the keys
no is th ti fo al go pe to co to th ai of th pa | 5.1.3
According to ASC II values, indices of chars 'a' through 'z' start at 97.
But this trace indices follow the book convention of 'a' starting at 0.
Trace for MSD string sort (same model as used in the book):
Top level of sort(array, 0, 15, 0):
input
0 no
1 is
2 th
3 ti
4 fo
5 al
6 go
7 pe
8 to
9 co
10... | [] | {
"number": "5.1.3",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Give a trace for 3-way string quicksort for the keys
no is th ti fo al go pe to co to th ai of th pa | 5.1.4
Trace for 3-way string quicksort (same model as used in the book):
-- -- --
0 no is ai ai ai ai
1 is ai co al -- al
2 th co fo -- al co
3 ti fo al fo -- fo
4 fo al go ... | [] | {
"number": "5.1.4",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Give a trace for MSD string sort for the keys
now is the time for all good people to come to the aid of | 5.1.5
According to ASC II values, indices of chars 'a' through 'z' start at 97.
But this trace indices follow the book convention of 'a' starting at 0.
Trace for MSD string sort (same model as used in the book):
Top level of sort(array, 0, 13, 0):
input
0 now
1 is
2 the
3 time
4 for
5 all
6 good
7 people
8 ... | [] | {
"number": "5.1.5",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Give a trace for 3-way string quicksort for the keys
now is the time for all good people to come to the aid of | 5.1.6
Trace for 3-way string quicksort (same model as used in the book):
---- --- --- ---
0 now is aid aid aid aid aid
1 is aid come all --- --- all
2 the come for --- all all come
3 time f... | [] | {
"number": "5.1.6",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Give the number of characters examined by MSD string sort and 3-way string quicksort for a file of N keys a, aa, aaa, aaaa, aaaaa, . . . | 5.1.8
Both MSD string sort and 3-way string quicksort examine all characters in the N keys.
That number is equal to 1 + 2 + ... + N = (N^2 + N) / 2 characters.
MSD string sort, however, generates (R - 1) * N empty subarrays (an empty subarray for all digits in R other than 'a', in every pass) while 3-way string quicks... | [] | {
"number": "5.1.8",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
What is the total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W), in the worst case? | 5.1.10
The total number of characters examined by 3-way string quicksort when sorting N fixed-length strings (all of length W) in the worst case is O(N * W * R).
This can be seen with a recurrence relation T(W).
The base case T(1) is when all the strings have length 1.
An example with R = 3 is { "a", "b", "c" }.
In ... | [] | {
"number": "5.1.10",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Exercise",
"code_execution": false
} |
Hybrid sort. Investigate the idea of using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins. | 5.1.13 - Hybrid sort
Idea: using standard MSD string sort for large arrays, in order to get the advantage of multiway partitioning, and 3-way string quicksort for smaller arrays, in order to avoid the negative effects of large numbers of empty bins.
This idea will work well for random strings because, in general, the... | [] | {
"number": "5.1.13",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Creative Problem",
"code_execution": false
} |
In-place key-indexed counting. Develop a version of key-indexed counting that uses only a constant amount of extra space. Prove that your version is stable or provide a counterexample. | // Exercise17_InPlaceKeyIndexedCounting.java
package chapter5.section1;
import edu.princeton.cs.algs4.StdOut;
import util.ArrayUtil;
import java.util.StringJoiner;
/**
* Created by Rene Argento on 13/01/18.
*/
public class Exercise17_InPlaceKeyIndexedCounting {
private class Element implements Comparable<Elem... | [] | {
"number": "5.1.17",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Creative Problem",
"code_execution": false
} |
Timings. Compare the running times of MSD string sort and 3-way string quicksort, using various key generators. For fixed-length keys, include LSD string sort. | 5.1.22 - Timings
Running 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays used in Mo... | [] | {
"number": "5.1.22",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Experiment",
"code_execution": false
} |
Array accesses. Compare the number of array accesses used by MSD string sort and 3-way string sort, using various key generators. For fixed-length keys, include LSD string sort. | 5.1.23 - Array accesses
Running 10 experiments with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small subarrays use... | [] | {
"number": "5.1.23",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Experiment",
"code_execution": false
} |
Rightmost character accessed. Compare the position of the rightmost character accessed for MSD string sort and 3-way string quicksort, using various key generators. | 5.1.24 - Rightmost character accessed
Running 1 experiment with 1000000 strings for random decimal keys (with fixed-length of 10 characters), random CA license plates, random fixed-length words (with fixed-length of 10 characters) and random variable length items (with given values 'A' and 'B'). The cutoff for small s... | [] | {
"number": "5.1.24",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.1,
"section_title": "String Sorts",
"type": "Experiment",
"code_execution": false
} |
Draw the TST that results when the keys
no is th ti fo al go pe to co to th ai of th pa
are inserted in that order into an initially empty TST. | 5.2.2
Ternary search trie after insertion of keys:
no is th ti fo al go pe to co to th ai of th pa
Empty TST:
Insert: no
n
/|\
o
/|\
Insert: is
n
/ | \
i o
/|\ /|\
s
/|\
Insert: th
n
/ | \
i o t
/|\ /|\ /|\
s h
/|\ /|\
Insert: ti
n
/ ... | [] | {
"number": "5.2.2",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Exercise",
"code_execution": false
} |
Draw the R-way trie that results when the keys
now is the time for all good people to come to the aid of
are inserted in that order into an initially empty trie (do not draw null links). | 5.2.3
R-way trie after insertion of keys:
now is the time for all good people to come to the aid of
Empty trie:
O
Insert: now
O
|
n
|
o
|
w
Insert: is
O
/ \
i n
| |
s o
|
w
Insert: the
O
/ | \
i n t
| | |
s o h
| |
w e
Insert: time
O
/ | \
i n t
| | /|
s o h i
|... | [] | {
"number": "5.2.3",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Exercise",
"code_execution": false
} |
Draw the TST that results when the keys
now is the time for all good people to come to the aid of
are inserted in that order into an initially empty TST. | 5.2.4
Ternary search trie after insertion of keys:
now is the time for all good people to come to the aid of
Empty TST:
Insert: now
n
/|\
o
/|\
w
/|\
Insert: is
n
/ | \
i o
/|\ /|\
s w
/|\ /|\
Insert: the
n
/ | \
i o t
/|\ /|\ /|\
s w h
/|\ /|\ /|\
... | [] | {
"number": "5.2.4",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Exercise",
"code_execution": false
} |
Develop nonrecursive versions of TrieST and TST. | package chapter5.section2;
import chapter1.section3.Queue;
import chapter1.section3.Stack;
import edu.princeton.cs.algs4.StdOut;
import java.util.StringJoiner;
/**
* Created by Rene Argento on 26/01/18.
*/
// Thanks to joe63 (https://github.com/joe63) for reporting a bug on the longestPrefixOf() method.
// https:/... | [] | {
"number": "5.2.5",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Exercise",
"code_execution": false
} |
Implement the following API, for a StringSET data type:
public class StringSET
StringSET() create a string set
void add(String key) put key into the set
void delete(String key) remove key from the set
boolean contains(String key) is key in the set?
boolean isEmpty() is the set empty?
int size() number of keys in the se... | package chapter5.section2;
import chapter3.section4.SeparateChainingHashTable;
import edu.princeton.cs.algs4.StdOut;
import java.util.*;
/**
* Created by Rene Argento on 31/01/18.
*/
public class Exercise6 {
public interface StringSETAPI {
void add(String key);
void delete(String key);
... | [] | {
"number": "5.2.6",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Exercise",
"code_execution": false
} |
Ordered operations for tries. Implement the floor(), ceil(), rank(), and select() (from our standard ordered ST API from Chapter 3) for TrieST. | package chapter5.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 23/01/18.
*/
public class Exercise8_OrderedOperationsForTries {
public class TrieOrdered<Value> extends Trie<Value> {
// Returns the highest key in the symbol table smaller than or equal to key.
p... | [] | {
"number": "5.2.8",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Creative Problem",
"code_execution": false
} |
Size. Implement very eager size() (that keeps in each node the number of keys in its subtree) for TrieST and TST. | package chapter5.section2;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 22/01/18.
*/
public class Exercise10_Size {
@SuppressWarnings("unchecked")
public static class TrieWithSize<Value> extends Trie<Value> {
private NodeWithSize root = new NodeWithSize();
privat... | [] | {
"number": "5.2.10",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Creative Problem",
"code_execution": false
} |
Hybrid TST with R2-way branching at the root. Add code to TST to do multiway branching at the first two levels, as described in the text. | package chapter5.section2;
import chapter1.section3.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.StringJoiner;
/**
* Created by Rene Argento on 05/02/18.
*/
public class Exercise13_HybridTSTWithR2BranchingAtTheRoot {
@SuppressWarnings("unchecked")
public class HybridTernarySearchTrie<Valu... | [] | {
"number": "5.2.13",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Creative Problem",
"code_execution": false
} |
Spell checking. Write a TST client SpellChecker that takes as command-line argument the name of a file containing a dictionary of words in the English language, and then reads a string from standard input and prints out any word that is not in the dictionary. Use a string set. | package chapter5.section2;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import util.Constants;
import util.FileUtil;
/**
* Created by Rene Argento on 08/02/18.
*/
public class Exercise17_SpellChecking {
private void spellChecker(String dictionaryFileName) {
String filePath... | [] | {
"number": "5.2.17",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Creative Problem",
"code_execution": false
} |
Typing monkeys. Suppose that a typing monkey creates random words by appending each of 26 possible letter with probability p to the current word and finishes the word with probability 1 - 26p. Write a program to estimate the frequency distribution of the lengths of words produced. If "abc" is produced more than once, c... | package chapter5.section2;
import chapter3.section4.SeparateChainingHashTable;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import util.Constants;
/**
* Created by Rene Argento on 17/02/18.
*/
public class Exercise22_TypingMonkeys {
public double[] getFrequencyDistribution(int... | [] | {
"number": "5.2.22",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Creative Problem",
"code_execution": false
} |
Duplicates (revisited again). Redo Exercise 3.5.30 using StringSET (see Exercise 5.2.6) instead of HashSET. Compare the running times of the two approaches. Then use Dedup to run the experiments for N = 10^7, 10^8, and10^9, repeat the experiments for random long values and discuss the results. | 5.2.23 - Duplicates (revisited again)
Results:
Method | Data structure | Values type | Values Generated | Max Value | Time spent
Array index count Array Integer 1000 500 0.01
Array index count Array Integer ... | [] | {
"number": "5.2.23",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Experiment",
"code_execution": false
} |
Spell checker. Redo Exercise 3.5.31, which uses the file dictionary.txt from the booksite and the BlackFilter client on page 491 to print all misspelled words in a text file. Compare the performance of TrieST and TST for the file war.txt with this client and discuss the results. | // Exercise24_SpellChecker.java
package chapter5.section2;
import chapter3.section5.HashSet;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Stopwatch;
import util.Constants;
import util.FileUtil;
/**
* Created by Rene Argento on 18/02/18.
*/
public class Exerci... | [] | {
"number": "5.2.24",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.2,
"section_title": "Tries",
"type": "Experiment",
"code_execution": false
} |
Give the dfa[][] array for the Knuth-Morris-Pratt algorithm for the pattern A A A A A A A A A, and draw the DFA, in the style of the figures in the text. | 5.3.2
pattern: A A A A A A A A A
j 0
pat.charAt(j) A
A 1
dfa[][j] B 0
C 0
… 0
j A
0 —> 1
/ ^
/ \
-B,C,…-
X
j 0 1
pat.charAt(j) A A
A 1 2
dfa[][j] B 0 0
C 0 0
... | [] | {
"number": "5.3.2",
"chapter": 5,
"chapter_title": "Strings",
"section": 5.3,
"section_title": "Substring Search",
"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.