Skip to content

Commit 23b0d55

Browse files
committed
Updated solutions
1 parent 5126438 commit 23b0d55

File tree

17 files changed

+110
-114
lines changed

17 files changed

+110
-114
lines changed
Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
package _8_03_Magic_Index;
22

33
public class MagicIndex {
4-
/* Part 1 - Use standard Binary Search: O(log n) time on sorted array. Only works if no duplicate numbers */
4+
// Part 1 - Use standard Binary Search: O(log n) time on sorted array. Only works if no duplicate numbers
55
public static Integer magicFast(int[] sortedArray) {
6-
return magicFast(sortedArray, 0, sortedArray.length - 1);
7-
}
6+
int lo = 0;
7+
int hi = sortedArray.length - 1;
88

9-
private static Integer magicFast(int[] sortedArray, int start, int end) {
10-
if (start > end) {
11-
return null;
12-
}
13-
int midIndex = (start + end) / 2;
14-
int midValue = sortedArray[midIndex];
15-
if (midValue == midIndex) {
16-
return midIndex;
17-
} else if (midValue > midIndex) {
18-
return magicFast(sortedArray, start, midIndex - 1);
19-
} else {
20-
return magicFast(sortedArray, midIndex + 1, end);
9+
while (lo <= hi) {
10+
int midIndex = (lo + hi) / 2;
11+
int midValue = sortedArray[midIndex];
12+
if (midValue == midIndex) {
13+
return midIndex;
14+
} else if (midValue > midIndex) {
15+
hi = midIndex - 1;
16+
} else {
17+
lo = midIndex + 1;
18+
}
2119
}
20+
return null;
2221
}
2322

24-
/* Part 2 - If integers in sorted array are NOT UNIQUE. O(n) runtime */
23+
// Part 2 - If integers in sorted array are NOT UNIQUE. O(n) runtime, O(n) space complexity.
2524
public static Integer magicFast2(int[] sortedArray) {
2625
return magicFast2(sortedArray, 0, sortedArray.length - 1);
2726
}
@@ -36,15 +35,17 @@ private static Integer magicFast2(int[] sortedArray, int start, int end) {
3635
return midIndex;
3736
}
3837

39-
/* Search Left. If we find the result, return it. */
38+
// Search Left. If we find the result, return it.
4039
int leftIndex = Math.min(midValue, midIndex - 1); // see algorithm in book for explanation if this line is confusing.
4140
Integer left = magicFast2(sortedArray, start, leftIndex);
4241
if (left != null) {
4342
return left;
4443
}
4544

46-
/* Search Right (Since we couldn't find it in left) */
45+
// Search Right (Since we couldn't find it in left)
4746
int rightIndex = Math.max(midValue, midIndex + 1);
4847
return magicFast2(sortedArray, rightIndex, end);
4948
}
49+
50+
// For Part 2, an alternate solution is to just loop through the array in search of the value for O(n) time, O(1) space complexity
5051
}

Chp. 10 - Sorting and Searching/_10_04_Sorted_Search_No_Size/SortedSearchNoSize.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,5 @@ public static int binarySearch(Listy listy, int value, int start, int end) {
2525
}
2626
}
2727

28-
// Time Complexity: O(log n)
29-
28+
// Time Complexity: O(log n)
29+
// Space Complexity: O(1)

Chp. 10 - Sorting and Searching/_10_10_Rank_from_Stream/RankFromStream.java

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@
77
// Array O(n) due to shifting O(log n) using binary search
88
// Linked List O(n) O(n) since we can't do binary search on linked list
99
// HashMap O(1) O(n) since HashMap doesn't help us find rank in any way (it's not sorted)
10-
// BST O(log n) O(log n) (assuming it's balanced)
10+
// BST O(log n) (if balanced tree) O(log n) (if balanced tree)
1111
//
1212
// Note: Insert for array and linked list are O(n) since we insert into the position necessary to keep the data structure sorted
1313

1414
public class RankFromStream {
1515

1616
private static RankNode root = null;
1717

18-
/* Called each time a number is generated */
18+
// Called each time a number is generated
1919
public static void track(int x) {
2020
if (root == null) {
2121
root = new RankNode(x);
@@ -24,40 +24,45 @@ public static void track(int x) {
2424
}
2525
}
2626

27-
private static void insert(int x, RankNode node) {
28-
if (x <= node.data) {
29-
node.leftSize++;
30-
if (node.left == null) {
31-
node.left = new RankNode(x);
27+
private static void insert(int x, RankNode root) {
28+
RankNode curr = root;
29+
while (true) {
30+
if (x <= curr.data) {
31+
curr.leftSize++;
32+
if (curr.left == null) {
33+
curr.left = new RankNode(x);
34+
return;
35+
} else {
36+
curr = curr.left;
37+
}
3238
} else {
33-
insert(x, node.left);
34-
}
35-
} else {
36-
if (node.right == null) {
37-
node.right = new RankNode(x);
38-
} else {
39-
insert(x, node.right);
39+
if (curr.right == null) {
40+
curr.right = new RankNode(x);
41+
return;
42+
} else {
43+
curr = curr.right;
44+
}
4045
}
4146
}
4247
}
4348

44-
/* Returns number of values less than or equal to x (not including x itself) */
49+
// Returns number of values less than or equal to x (not including x itself)
4550
public static int getRankOfNumber(int x) {
4651
if (root == null) {
4752
return 0;
4853
}
49-
return getRankOfNumber(x, root);
50-
}
51-
52-
private static int getRankOfNumber(int x, RankNode node) {
53-
if (node == null) {
54-
return 0;
55-
} else if (x == node.data) {
56-
return node.leftSize;
57-
} else if (x > node.data) {
58-
return 1 + node.leftSize + getRankOfNumber(x, node.right);
59-
} else {
60-
return getRankOfNumber(x, node.left);
54+
RankNode curr = root;
55+
int rank = 0;
56+
while (curr != null) {
57+
if (x == curr.data) {
58+
return rank + curr.leftSize;
59+
} else if (x > curr.data) {
60+
rank += 1 + curr.leftSize;
61+
curr = curr.right;
62+
} else {
63+
curr = curr.left;
64+
}
6165
}
66+
return 0;
6267
}
6368
}

Chp. 10 - Sorting and Searching/_10_11_Peaks_and_Valleys/PeaksAndValleys.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,6 @@ private static void swap(int[] array, int left, int right) {
2121
array[right] = temp;
2222
}
2323
}
24+
25+
// Time Complexity: O(n)
26+
// Space Complexity: O(1)

Chp. 16 - More Problems (Moderate)/_16_04_Tic_Tac_Win/TicTacWin.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
// 2) Use an array of booleans to indicate which boards are winning boards.
66

77
public class TicTacWin {
8-
boolean[] winnerMap;
8+
private boolean[] winnerMap;
99

1010
public static int convertBoardToInt(char[][] board) {
1111
int sum = 0;

Chp. 16 - More Problems (Moderate)/_16_15_Master_Mind/MasterMind.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public static Result estimate(String guess, String solution) {
1717
Result result = new Result();
1818
Map<Character, Integer> colorMap = new HashMap<>();
1919

20-
// Count direct hits, while saving non-directHit colors in a HashMap, which will later help us count pseudohits
20+
// Count direct hits. Save other colors in HashMap for later.
2121
for (int i = 0; i < solution.length(); i++) {
2222
char solChar = solution.charAt(i);
2323
char guessChar = guess.charAt(i);

Chp. 16 - More Problems (Moderate)/_16_20_T9__HashMap_Solution/T9.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
// value = List of Valid Words
88

99
public class T9 {
10-
private static Map<Character, Character> letterToDigit = new HashMap<>();
10+
private Map<Character, Character> letterToDigit;
1111

12-
static { // static initializer block
12+
public T9() {
13+
letterToDigit = new HashMap<>();
1314
for (char ch = 'a'; ch <= 'c'; ch++) letterToDigit.put(ch, '2');
1415
for (char ch = 'd'; ch <= 'f'; ch++) letterToDigit.put(ch, '3');
1516
for (char ch = 'g'; ch <= 'i'; ch++) letterToDigit.put(ch, '4');
@@ -20,7 +21,7 @@ public class T9 {
2021
for (char ch = 'w'; ch <= 'z'; ch++) letterToDigit.put(ch, '9');
2122
}
2223

23-
public static Map<String, List<String>> buildMap(String[] words) {
24+
public Map<String, List<String>> buildMap(String[] words) {
2425
Map<String, List<String>> map = new HashMap<>();
2526
for (String word : words) {
2627
String number = getNumber(word);
@@ -31,7 +32,7 @@ public static Map<String, List<String>> buildMap(String[] words) {
3132
return map;
3233
}
3334

34-
private static String getNumber(String str) {
35+
private String getNumber(String str) {
3536
StringBuffer sb = new StringBuffer();
3637
for (int i = 0; i < str.length(); i++) {
3738
char ch = letterToDigit.get(str.charAt(i));

Chp. 16 - More Problems (Moderate)/_16_20_T9__HashMap_Solution/Tester.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ public class Tester {
88

99
public static void main(String[] args) {
1010
System.out.println("*** Test 16.20: T9 - HashMap Solution\n");
11-
Map<String, List<String>> map = T9.buildMap(words);
11+
T9 t9 = new T9();
12+
Map<String, List<String>> map = t9.buildMap(words);
1213
System.out.println("Matching words: ");
1314
for (String word : map.get("8733")) {
1415
System.out.println(word);

Chp. 17 - More Problems (Hard)/_17_03_Random_Set/RandomSet.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ to decide if array[n] should be inserted into our subset (which would require pu
1616
*/
1717
public class RandomSet {
1818
public int[] generate(int[] array, int m) {
19+
if (array == null || m > array.length) {
20+
return null;
21+
}
1922
/* Copy first "m" elements into new array */
2023
int[] solution = new int[m];
2124
for (int i = 0; i < m; i++) {

Chp. 17 - More Problems (Hard)/_17_11_Word_Distance/WordDistance.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,7 @@ public static Integer shortest(String[] words, String word1, String word2) {
4545
public static void preProcess(String[] words) {
4646
for (int i = 0; i < words.length; i++) {
4747
String currWord = words[i];
48-
if (!map.containsKey(currWord)) {
49-
map.put(currWord, new ArrayList<Integer>());
50-
}
48+
map.putIfAbsent(currWord, new ArrayList<Integer>());
5149
List<Integer> positions = map.get(currWord);
5250
positions.add(i);
5351
}
@@ -87,7 +85,7 @@ private static Integer findDistance(List<Integer> listA, List<Integer> listB) {
8785

8886
private static List<Pair> merge(List<Integer> listA, List<Integer> listB) {
8987
if (listA == null || listB == null || listA.size() == 0 || listB.size() == 0) {
90-
return null; // function assumes both lists are non-empty (to make error-checking easier to write)
88+
return new ArrayList<>();
9189
}
9290

9391
List<Pair> merged = new ArrayList<>();

Chp. 17 - More Problems (Hard)/_17_14_Smallest_K/SmallestK.java

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,17 @@ public static void findNthSmallestNums(int[] array, int n) {
3434
// - O(n) average run-time is since we recurse only on 1 side (n + n/2 + n/4 + ...) = n (1 + 1/2 + 1/4 + ...) = O(n).
3535
// Our formula above is a geometric series with "r = 1/2", which would converge to 1/(1-r) for infinite geometric series.
3636
// - O(n^2) worst-case run-time is if "partition()" consistently picks a bad pivot.
37-
private static Integer quickselect(int[] array, int n) {
38-
int start = 0;
39-
int end = array.length - 1;
40-
while (start <= end) {
41-
int pivotIndex = partition(array, start, end);
37+
private static Integer quickselect(int[] A, int n) {
38+
int lo = 0;
39+
int hi = A.length - 1;
40+
while (lo <= hi) {
41+
int pivotIndex = partition(A, lo, hi);
4242
if (pivotIndex == n) {
43-
return array[n];
43+
return A[n];
4444
} else if (pivotIndex < n) {
45-
start = pivotIndex + 1;
45+
lo = pivotIndex + 1;
4646
} else {
47-
end = pivotIndex - 1;
47+
hi = pivotIndex - 1;
4848
}
4949
}
5050
return null;
@@ -54,31 +54,31 @@ private static Integer quickselect(int[] array, int n) {
5454
// 1) Left side has values smaller than pivotValue
5555
// 2) Right side has values larger than pivotValue
5656
// Returns pivotIndex
57-
private static Integer partition(int[] array, int start, int end) {
58-
if (start > end) {
57+
private static Integer partition(int[] A, int lo, int hi) {
58+
if (lo > hi) {
5959
return null;
6060
}
61-
int pivotIndex = (start + end) / 2; // there are many ways to choose a pivot
62-
int pivotValue = array[pivotIndex];
61+
int pivotIndex = (lo + hi) / 2; // there are many ways to choose a pivot
62+
int pivotValue = A[pivotIndex];
6363

64-
swap(array, pivotIndex, end); // puts pivot at end for now.
64+
swap(A, pivotIndex, hi); // puts pivot at end for now.
6565

66-
/* Linear search, comparing all elements to pivotValue and swapping as necessary */
67-
int indexToReturn = start; // Notice we set it to "start", not to "0".
68-
for (int i = start; i < end; i++) {
69-
if (array[i] < pivotValue) {
70-
swap(array, i, indexToReturn);
66+
// Linear search, comparing all elements to pivotValue and swapping as necessary
67+
int indexToReturn = lo; // Notice we set it to "lo", not to "0".
68+
for (int i = lo; i < hi; i++) {
69+
if (A[i] < pivotValue) {
70+
swap(A, i, indexToReturn);
7171
indexToReturn++;
7272
}
7373
}
7474

75-
swap(array, indexToReturn, end); // puts pivot where it belongs
75+
swap(A, indexToReturn, hi); // puts pivot where it belongs
7676
return indexToReturn;
7777
}
7878

79-
private static void swap(int[] array, int i, int j) {
80-
int temp = array[i];
81-
array[i] = array[j];
82-
array[j] = temp;
79+
private static void swap(int[] A, int i, int j) {
80+
int temp = A[i];
81+
A[i] = A[j];
82+
A[j] = temp;
8383
}
8484
}

Chp. 17 - More Problems (Hard)/_17_14_Smallest_K/Tester.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public static void main(String[] args) {
1313
}
1414

1515
private static void test(int[] array, int k) {
16-
System.out.format("\n%2 d Smallest: ", k);
16+
System.out.format("\n%2d Smallest: ", k);
1717
SmallestK.findNthSmallestNums(array, k);
1818
}
1919
}

Chp. 17 - More Problems (Hard)/_17_18_Shortest_Supersequence/HeapNode.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public class HeapNode {
44
int value; // same as the value that's the key in our HashMap
5-
int index;
5+
int index; // index in array it came from
66

77
HeapNode(int listID, int pos) {
88
this.value = listID;

Chp. 17 - More Problems (Hard)/_17_18_Shortest_Supersequence/NodeComparator.java

Lines changed: 0 additions & 10 deletions
This file was deleted.

Chp. 17 - More Problems (Hard)/_17_18_Shortest_Supersequence/ShortestSupersequence.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,15 @@
1515
// Time Complexity: O(S + B log S)
1616

1717
public class ShortestSupersequence {
18-
public static void shortest(int[] arrayA, int[] arrayB) {
18+
public static Range shortest(int[] arrayA, int[] arrayB) {
1919
Map<Integer, Deque<HeapNode>> map = makeLists(arrayA, arrayB);
20-
Range range = getSmallestRange(map);
21-
System.out.println("Range: " + range);
20+
return getSmallestRange(map);
2221
}
2322

2423
private static Map<Integer, Deque<HeapNode>> makeLists(int[] arrayA, int[] arrayB) {
2524
Map<Integer, Deque<HeapNode>> map = new HashMap<>();
2625
for (int num : arrayA) {
27-
map.put(num, new ArrayDeque<>());
26+
map.putIfAbsent(num, new ArrayDeque<>());
2827
}
2928
for (int i = 0; i < arrayB.length; i++) {
3029
if (map.containsKey(arrayB[i])) {
@@ -37,7 +36,7 @@ private static Map<Integer, Deque<HeapNode>> makeLists(int[] arrayA, int[] array
3736
}
3837

3938
private static Range getSmallestRange(Map<Integer, Deque<HeapNode>> map) {
40-
Queue<HeapNode> minHeap = new PriorityQueue<>(new NodeComparator());
39+
Queue<HeapNode> minHeap = new PriorityQueue<>((hn1, hn2) -> hn1.index - hn2.index);
4140

4241
Range currRange = new Range(Integer.MAX_VALUE, Integer.MIN_VALUE);
4342

Chp. 17 - More Problems (Hard)/_17_18_Shortest_Supersequence/Tester.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public static void main(String[] args) {
1313
private static void test(int[] arrayA, int[] arrayB) {
1414
System.out.println(Arrays.toString(arrayA));
1515
System.out.println(Arrays.toString(arrayB));
16-
ShortestSupersequence.shortest(arrayA, arrayB);
16+
Range range = ShortestSupersequence.shortest(arrayA, arrayB);
17+
System.out.println("Range: " + range);
1718
}
1819
}

0 commit comments

Comments
 (0)