Skip to content

Commit 5126438

Browse files
committed
Updated solutions
1 parent 5719a04 commit 5126438

File tree

44 files changed

+293
-246
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+293
-246
lines changed

Chp. 01 - Arrays and Strings/_1_1_Is_Unique/IsUnique.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,5 @@ public static boolean uniqueCharacters(String str) {
3030
// Follow-up Question: What if we're not allowed to use additional data structures?
3131
//
3232
// Answer: Can do brute-force solution by comparing all pairs
33-
// Time Complexity: O(n^2), but since strings above NUM_ASCII_CHARS=256 immediately
34-
// return false, time complexity becomes O(1)
33+
// Time Complexity: O(1) since String is max 256 characters. Without this bound it would be O(n^2)
3534
// Space Complexity: O(1)

Chp. 01 - Arrays and Strings/_1_3_URLify/URLify.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,6 @@ public static void replaceWhitespace(char[] sentence, int trueLength) {
2626
}
2727
}
2828
}
29+
30+
// Time Complexity: O(n)
31+
// Space Complexity: O(1)

Chp. 01 - Arrays and Strings/_1_4_Palindrome_Permutation/PalindromePermutation.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
package _1_4_Palindrome_Permutation;
22

3-
import java.util.HashMap;
3+
import java.util.*;
44

55
public class PalindromePermutation {
66

77
private static final int NUM_LOWERCASE_LETTERS = 26;
88

99
public static boolean palPerm(String str) {
1010
str = str.toLowerCase().replaceAll("\\s", "");
11-
HashMap<Character, Integer> map = new HashMap<>(NUM_LOWERCASE_LETTERS);
11+
Map<Character, Integer> map = new HashMap<>(NUM_LOWERCASE_LETTERS);
1212
for (int i = 0; i < str.length(); i++) {
1313
Character ch = str.charAt(i);
1414
if (Character.isLetter(ch)) {

Chp. 01 - Arrays and Strings/_1_5_One_Away/OneAway.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,5 @@ private static Boolean oneEditInsert(String s1, String s2) {
5353
}
5454
}
5555

56-
// Time Complexity: O(n+m)
56+
// Time Complexity: O(n + m)
5757
// Space Complexity: O(1)

Chp. 01 - Arrays and Strings/_1_9_String_Rotation/StringRotation.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,7 @@ public static boolean isRotation(String s1, String s2) {
1111
}
1212

1313
// Time/Space Complexities are same as .contains() function
14+
// If .contains() is implemented using the "KMP algorithm" then we will have:
15+
//
16+
// Time Complexity: O(n)
17+
// Space Complexity: O(1)

Chp. 02 - Linked Lists/_2_1_Remove_Dups/RemoveDups.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package _2_1_Remove_Dups;
22

3-
import java.util.HashSet;
3+
import java.util.*;
44
import common.Node;
55

66
public class RemoveDups {
77
static void removeDuplicates(Node head) {
8-
HashSet<Integer> set = new HashSet<>();
8+
Set<Integer> set = new HashSet<>();
99
set.add(head.data);
1010
Node n = head;
1111
while (n.next != null) {

Chp. 02 - Linked Lists/_2_4_Partition/Partition.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010
// 2) Create 2 SLLs from SLL. Connect them. O(n) Use if swapping data not allowed
1111

1212
public class Partition {
13-
/* Solution 1 */
13+
// Solution 1
1414
public static Node partition(Node head, int x) {
1515
Node curr = head;
1616
Node p = head;
1717
while (curr != null) {
1818
if (curr.data < x) {
19-
/* Swap DATA values */
19+
// Swap DATA values
2020
int temp = p.data;
2121
p.data = curr.data;
2222
curr.data = temp;
@@ -28,7 +28,7 @@ public static Node partition(Node head, int x) {
2828
return head;
2929
}
3030

31-
/* Solution 2 */
31+
// Solution 2
3232
public static Node partition2(Node n, int x) {
3333
Node head1 = null;
3434
Node head2 = null;

Chp. 03 - Stacks and Queues/_3_1_Three_in_One/ThreeInOne.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package _3_1_Three_in_One;
22

3-
// Use "int[] heads = {-1,-1,-1}" and simply implement arrayOffset(int stackNum) , push/pop/peek
3+
// Use "int[] heads = {-1,-1,-1}" and simply implement arrayOffset(int stackNum), push/pop/peek
44

55
public class ThreeInOne {
66
private final int numStacks = 3;
@@ -22,7 +22,7 @@ public void push(int value, int stackNum) throws Exception {
2222

2323
public int pop(int stackNum) throws Exception {
2424
if (heads[stackNum] == -1) {
25-
throw new Exception("No elements to pop");
25+
throw new Exception("No element to pop");
2626
}
2727
int offset = arrayOffset(stackNum) + heads[stackNum];
2828
heads[stackNum]--;
@@ -31,7 +31,7 @@ public int pop(int stackNum) throws Exception {
3131

3232
public int peek(int stackNum) throws Exception {
3333
if (heads[stackNum] == -1) {
34-
throw new Exception("No elements to pop");
34+
throw new Exception("No element to pop");
3535
}
3636
int offset = arrayOffset(stackNum) + heads[stackNum];
3737
return array[offset];
@@ -45,7 +45,7 @@ private int arrayOffset(int stackNum) {
4545
return stackSize * stackNum;
4646
}
4747

48-
/* Added for testing */
48+
// Added for testing
4949
public void print() {
5050
for (int stackNum = 0; stackNum <= 2; stackNum++) {
5151
System.out.print("\nStack #" + stackNum + ": ");
@@ -60,3 +60,6 @@ public void print() {
6060
// 2) The array is allowed to wrap around on itself (so will need to use % operator)
6161
// 3) They made a new class called "StackData" to keep track of a bunch of information about each stack instead of just "head"
6262
}
63+
64+
// Time Complexity: O(1) for push(), pop(), peek(), isEmpty(), arrayOffset()
65+
// Space Complexity: O(1) for push(), pop(), peek(), isEmpty(), arrayOffset(). O(n) permanent storage needed for "array"

Chp. 03 - Stacks and Queues/_3_4_Queue_via_Stacks/QueueViaStacks.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,6 @@ private void shiftStacks() {
5050
}
5151
}
5252

53-
// Time/Space Complexity
54-
//
5553
// Time Complexity: O(1) _amortized_ time for `push()`, `pop()`, `peek()`, `empty()`,
5654
// as each element is only moved from `stack1` to `stack2` at most once.
5755
// Space Complexity: O(1) for each element being put into our queue.

Chp. 03 - Stacks and Queues/__Intro_Queue/Queue.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ public Node peek() {
3434
return head;
3535
}
3636
}
37+
38+
// Time Complexity: O(1) for add(), remove(), peek().
39+
// Space Complexity: O(1) for add(), remove(), peek(). O(1) to store each Node permanently.

Chp. 03 - Stacks and Queues/__Intro_Stack/Stack.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,6 @@ public Node peek() {
2525
return top;
2626
}
2727
}
28+
29+
// Time Complexity: O(1) for push(), pop(), peek().
30+
// Space Complexity: O(1) for push(), pop(), peek(). O(1) to store each Node permanently.

Chp. 04 - Trees and Graphs/_4_01_Route_Between_Nodes/RouteBetweenNodes.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package _4_01_Route_Between_Nodes;
22

3-
import java.util.ArrayDeque;
3+
import java.util.*;
44
import common.GraphNode;
55

66
// Algorithm: run BFS from start node and see if we arrive at end node
@@ -11,7 +11,7 @@ public static boolean routeExists(GraphNode start, GraphNode end) {
1111
return true;
1212
}
1313

14-
ArrayDeque<GraphNode> deque = new ArrayDeque<>(); // use deque as a queue
14+
Deque<GraphNode> deque = new ArrayDeque<>(); // use deque as a queue
1515
start.visit();
1616
deque.add(start);
1717

Chp. 04 - Trees and Graphs/_4_05_Validate_BST/ValidateBST.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ private static boolean isBST(TreeNode node, int min, int max) {
1919
}
2020

2121
// Time Complexity: O(n) since we visit every node
22-
// Space Complexity: O(n) if unbalanced tree, O(log n) if it's balanced. That's the depth of the recursion
22+
// Space Complexity: O(log n) if tree is balanced, O(n) otherwise, since that's the depth of the recursion

Chp. 04 - Trees and Graphs/_4_06_Successor/Successor.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,7 @@ private static TreeNode properParent(TreeNode node) {
4141
}
4242

4343
// Finding Successor of a Node is useful when deleting a node in a binary *search* tree,
44-
// since that's a node we can put in place of the deleted node
44+
// since that's a node we can put in place of the deleted node
45+
46+
// Time Complexity: O(n)
47+
// Space Complexity: O(1)

Chp. 04 - Trees and Graphs/_4_07_Build_Order/BuildOrder.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package _4_07_Build_Order;
22

3-
import java.util.ArrayDeque;
3+
import java.util.*;
44

55
// From Jeff Erickson's Algorithms.pdf, Section 19.5 Topological Sort
66

77
public class BuildOrder {
88
// Converts our inconveniently formatted input into a graph
9-
public static ArrayDeque<Node> topoSort(String[] projects, String[][] dependencies) throws Exception {
9+
public static Deque<Node> topoSort(String[] projects, String[][] dependencies) throws Exception {
1010
Graph graph = new Graph();
1111
for (String project : projects) {
1212
graph.addNode(project);
@@ -19,19 +19,19 @@ public static ArrayDeque<Node> topoSort(String[] projects, String[][] dependenci
1919
return topoSort(graph);
2020
}
2121

22-
private static ArrayDeque<Node> topoSort(Graph graph) throws Exception {
22+
private static Deque<Node> topoSort(Graph graph) throws Exception {
2323
Node source = new Node("Source");
2424
for (Node node : graph.nodes) {
2525
source.addDirectedNeighbor(node);
2626
}
2727

28-
ArrayDeque<Node> result = new ArrayDeque<>();
28+
Deque<Node> result = new ArrayDeque<>();
2929
topoSortDFS(source, result);
3030
result.removeFirst(); // removes the source node we created
3131
return result;
3232
}
3333

34-
private static void topoSortDFS(Node n, ArrayDeque<Node> result) throws Exception {
34+
private static void topoSortDFS(Node n, Deque<Node> result) throws Exception {
3535
n.status = Visited.ACTIVE;
3636
for (Node neighbor : n.neighbors) {
3737
if (neighbor.status == Visited.NEW) {
Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,57 @@
11
package _4_09_BST_Sequences;
22

3-
import java.util.ArrayList;
4-
import java.util.ArrayDeque;
3+
import java.util.*;
54
import common.TreeNode;
65

76
public class BSTSequences {
8-
public static ArrayList<ArrayDeque<Integer>> allSequences(TreeNode node) {
9-
ArrayList<ArrayDeque<Integer>> results = new ArrayList<>();
7+
public static List<Deque<Integer>> allSequences(TreeNode node) {
8+
List<Deque<Integer>> results = new ArrayList<>();
109

1110
if (node == null) {
1211
results.add(new ArrayDeque<Integer>()); // crucial. So the code labeled "weave lists" works properly
1312
return results;
1413
}
1514

16-
ArrayDeque<Integer> prefix = new ArrayDeque<>();
15+
Deque<Integer> prefix = new ArrayDeque<>();
1716
prefix.add(node.data);
1817

19-
/* Recursive Cases */
20-
ArrayList<ArrayDeque<Integer>> leftSeq = allSequences(node.left);
21-
ArrayList<ArrayDeque<Integer>> rightSeq = allSequences(node.right);
18+
// Recursive Cases
19+
List<Deque<Integer>> leftSeq = allSequences(node.left);
20+
List<Deque<Integer>> rightSeq = allSequences(node.right);
2221

23-
/* Weave lists */
24-
for (ArrayDeque<Integer> left : leftSeq) {
25-
for (ArrayDeque<Integer> right : rightSeq) {
22+
// Weave lists
23+
for (Deque<Integer> left : leftSeq) {
24+
for (Deque<Integer> right : rightSeq) {
2625
weaveLists(left, right, results, prefix);
2726
}
2827
}
2928

3029
return results;
3130
}
3231

33-
private static void weaveLists(ArrayDeque<Integer> list1, ArrayDeque<Integer> list2,
34-
ArrayList<ArrayDeque<Integer>> results, ArrayDeque<Integer> prefix) {
35-
/* Base Case */
32+
private static void weaveLists(Deque<Integer> list1, Deque<Integer> list2,
33+
List<Deque<Integer>> results, Deque<Integer> prefix) {
34+
// Base Case
3635
if (list1.isEmpty() || list2.isEmpty()) {
37-
ArrayDeque<Integer> result = new ArrayDeque<>(prefix);
38-
result.addAll(list1);
39-
result.addAll(list2);
40-
results.add(result);
41-
return;
36+
Deque<Integer> result = new ArrayDeque<>(prefix);
37+
result.addAll(list1);
38+
result.addAll(list2);
39+
results.add(result);
40+
return;
4241
}
43-
44-
/* Use 1st entry in list1 */
42+
43+
// Use 1st entry in list1
4544
Integer temp = list1.removeFirst();
4645
prefix.addLast(temp);
4746
weaveLists(list1, list2, results, prefix);
4847
prefix.removeLast();
4948
list1.addFirst(temp);
50-
51-
/* Use 1st entry in list2 */
49+
50+
// Use 1st entry in list2
5251
temp = list2.removeFirst();
5352
prefix.addLast(temp);
5453
weaveLists(list1, list2, results, prefix);
5554
prefix.removeLast();
5655
list2.addFirst(temp);
57-
}
56+
}
5857
}

Chp. 04 - Trees and Graphs/_4_09_BST_Sequences/Tester.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package _4_09_BST_Sequences;
22

3-
import java.util.ArrayDeque;
4-
import java.util.ArrayList;
3+
import java.util.*;
54

65
import common.TreeNode;
76

@@ -11,8 +10,8 @@ public static void main(String[] args) {
1110
TreeNode root = new TreeNode(2);
1211
root.left = new TreeNode(1);
1312
root.right = new TreeNode(3);
14-
ArrayList<ArrayDeque<Integer>> results = BSTSequences.allSequences(root);
15-
for (ArrayDeque<Integer> result : results) {
13+
List<Deque<Integer>> results = BSTSequences.allSequences(root);
14+
for (Deque<Integer> result : results) {
1615
System.out.println(result);
1716
}
1817
}

Chp. 04 - Trees and Graphs/_4_10_Check_Subtree/CheckSubtree.java

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,26 @@
33
import common.TreeNode;
44

55
public class CheckSubtree {
6-
76
public static boolean containsTree(TreeNode t1, TreeNode t2) {
8-
if (t2 == null) { // the empty tree is always a subtree. We do this
9-
// check here to avoid doing it every time in subTree.
10-
return true;
11-
}
12-
return subTree(t1, t2);
7+
StringBuffer sb1 = new StringBuffer();
8+
StringBuffer sb2 = new StringBuffer();
9+
10+
getPreorder(t1, sb1);
11+
getPreorder(t2, sb2);
12+
13+
return sb1.indexOf(sb2.toString()) != -1;
1314
}
1415

15-
public static boolean subTree(TreeNode t1, TreeNode t2) {
16-
if (t1 == null) {
17-
return false;
18-
}
19-
20-
if (matchTree(t1, t2)) {
21-
return true;
22-
}
23-
24-
return subTree(t1.left, t2) || subTree(t1.right, t2);
25-
}
26-
27-
public static boolean matchTree(TreeNode p, TreeNode q) {
28-
if (p == null && q == null) {
29-
return true;
30-
} else if (p == null || q == null) {
31-
return false;
32-
}
33-
if (p.data != q.data) {
34-
return false;
16+
private static void getPreorder(TreeNode node, StringBuffer sb) {
17+
if (node == null) {
18+
sb.append("X"); // Add X representing null
19+
return;
3520
}
36-
return matchTree(p.left, q.left) && matchTree(p.right, q.right);
21+
sb.append("#" + node.data); // Add separator and root
22+
getPreorder(node.left, sb); // Add left
23+
getPreorder(node.right, sb); // Add right
3724
}
3825
}
3926

40-
// Runtimes:
41-
// Let t1 have n nodes and t2 have m nodes
42-
//
43-
// Time Complexity:
44-
// - O(nm) worst case, but average case is much better since matchTree() usually returns
45-
// false immediately, so it's O(n + km) where k is number of occurrences of T2's root in T1
46-
// - Also, even when we do call matchTree, it is likely to not match very soon in its search
47-
//
48-
// Space Complexity: O(log(n) + log(m)). Which is great.
27+
// Time Complexity: O(m + n) if we can assume .indexOf() uses KMP algorithm.
28+
// Space Complexity: O(m + n)

Chp. 04 - Trees and Graphs/_4_10_Check_Subtree/Tester.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@ public static void main(String[] args) {
1111
TreeNode tree3 = new TreeNode(5);
1212
System.out.println("Contains tree? (should be false): " + CheckSubtree.containsTree(tree1, tree2));
1313
System.out.println("Contains tree? (should be false): " + CheckSubtree.containsTree(tree1, tree3));
14-
System.out.println("Contains tree? (should be true): " + CheckSubtree.containsTree(tree1, tree1));
14+
System.out.println("Contains tree? (should be true ): " + CheckSubtree.containsTree(tree1, tree1));
1515
}
1616
}

0 commit comments

Comments
 (0)