Skip to content

Commit 4100751

Browse files
committed
Updated 14 solutions
1 parent 722e19c commit 4100751

File tree

20 files changed

+426
-326
lines changed

20 files changed

+426
-326
lines changed

Chp. 01 - Arrays and Strings/_1_6_String_Compression/StringCompression.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static String basicCompression(String str) {
1919
}
2020
}
2121

22-
/* Accounts for last character */
22+
// Accounts for last character
2323
sb.append(str.charAt(str.length() - 1));
2424
sb.append(String.valueOf(numSame));
2525

Chp. 01 - Arrays and Strings/_1_8_Zero_Matrix/Tester.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,23 @@
55
public class Tester {
66
public static void main(String[] args) {
77
System.out.println("*** Test 1.8: Zero Matrix\n");
8-
int[][] matrix = {{ 1, 2, 3 },
9-
{ 0, 5, 6 }};
8+
int[][] matrix1 = {{ 1, 2, 3, 1 },
9+
{ 4, 5, 6, 0 },
10+
{ 0, 5, 3, 0 }};
1011

1112
int[][] matrix2 = {{ 1, 2, 3, 1 },
1213
{ 4, 5, 6, 0 },
1314
{ 0, 5, 3, 0 }};
1415

15-
testMatrix(matrix);
16+
testMatrix(matrix1);
1617
testMatrix(matrix2);
1718
}
1819

1920
private static void testMatrix(int[][] matrix) {
2021
System.out.println("Original matrix");
2122
Functions.printImage(matrix); // uses print function above in 1.6
2223
System.out.println("Zero out necessary rows/columns");
23-
ZeroMatrix.zero(matrix);
24+
ZeroMatrix.solution1(matrix);
2425
Functions.printImage(matrix);
2526
System.out.println();
2627
}
Lines changed: 88 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,110 @@
11
package _1_8_Zero_Matrix;
22

3+
// Solutions Runtime Space
4+
// -----------------------------------------------
5+
// 1. Using 2 arrays O(m * n) O(m + n)
6+
// 2. Using input as storage O(m * n) O(1)
7+
38
public class ZeroMatrix {
4-
public static void zero(int[][] array) {
5-
int M = array.length;
6-
int N = array[0].length;
9+
10+
// Algorithm
11+
//
12+
// 1. Create a boolean array to save which rows have 0s.
13+
// 2. Repeat above step for columns.
14+
// 3. Loop through 2-d grid to figure out which rows & columns have a 0.
15+
// 4. Re-loop through 2-d grid and set whichever entries are necessary to 0.
16+
17+
public static void solution1(int[][] grid) {
18+
int M = grid.length;
19+
int N = grid[0].length;
720

8-
/* Figure out which rows & columns should become 0 */
21+
// Loop through 2-d grid to figure out which rows & columns have a 0
922
boolean[] rows = new boolean[M];
1023
boolean[] cols = new boolean[N];
1124
for (int row = 0; row < M; row++) {
1225
for (int col = 0; col < N; col++) {
13-
if (array[row][col] == 0) {
26+
if (grid[row][col] == 0) {
1427
rows[row] = true;
1528
cols[col] = true;
1629
}
1730
}
1831
}
1932

20-
/* Re-loop through 2-d matrix and set whichever entries are necessary to 0 */
33+
// Re-loop through 2-d matrix and set whichever entries are necessary to 0
2134
for (int row = 0; row < M; row++) {
2235
for (int col = 0; col < N; col++) {
2336
if (rows[row] == true || cols[col] == true) {
24-
array[row][col] = 0;
37+
grid[row][col] = 0;
38+
}
39+
}
40+
}
41+
}
42+
43+
// Algorithm
44+
//
45+
// - To achieve an O(1) space solution, instead of using 2 new boolean arrays as in above solution, we will
46+
// use the array itself as storage. Specifically, we will use the 0th row and 0th column as our 2 arrays.
47+
// - To be able to overwrite the values in the 0th row and 0th col, we will process them first.
48+
//
49+
// 1. Check if row 0 has a 0. Save this info for later.
50+
// 2. Check if col 0 has a 0. Save this info for later.
51+
// 3. Use row 0 and col 0 as storage. Loop through grid and save which rows and columns have 0s.
52+
// 4. Zero out the necessary cells in grid (except for 0th row and 0th col).
53+
// 5. Zero out the necessary cells in row 0.
54+
// 6. Zero out the necessary cells in col 0.
55+
56+
public static void solution2(int[][] grid) {
57+
int rows = grid.length;
58+
int cols = grid[0].length;
59+
60+
// Check if row 0 has a 0. Save this info for later.
61+
boolean row0Has0 = false;
62+
for (int col = 0; col < cols; col++) {
63+
if (grid[0][col] == 0) {
64+
row0Has0 = true;
65+
}
66+
}
67+
68+
// Check if col 0 has a 0. Save this info for later.
69+
boolean col0Has0 = false;
70+
for (int row = 0; row < rows; row++) {
71+
if (grid[row][0] == 0) {
72+
col0Has0 = true;
73+
}
74+
}
75+
76+
// Use row 0 and col 0 as storage.
77+
// Loop through grid and save which rows and columns have 0s.
78+
for (int row = 0; row < rows; row++) {
79+
for (int col = 0; col < cols; col++) {
80+
if (grid[row][col] == 0) {
81+
grid[row][0] = 0;
82+
grid[0][col] = 0;
83+
}
84+
}
85+
}
86+
87+
// Zero out the necessary cells in grid (except for 0th row and 0th col).
88+
for (int row = 1; row < rows; row++) {
89+
for (int col = 1; col < cols; col++) {
90+
if (grid[row][0] == 0 || grid[0][col] == 0) {
91+
grid[row][col] = 0;
2592
}
2693
}
2794
}
95+
96+
// Zero out the necessary cells in row 0.
97+
if (row0Has0) {
98+
for (int col = 0; col < cols; col++) {
99+
grid[0][col] = 0;
100+
}
101+
}
102+
103+
// Zero out the necessary cells in col 0.
104+
if (col0Has0) {
105+
for (int row = 0; row < rows; row++) {
106+
grid[row][0] = 0;
107+
}
108+
}
28109
}
29110
}

Chp. 02 - Linked Lists/_2_5_Sum_Lists/Pair.java

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 46 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,92 +1,76 @@
11
package _2_5_Sum_Lists;
22

33
import common.Node;
4-
import common.ListFunctions;
4+
import java.util.Stack;
55

66
public class SumLists {
7-
/* Reverse Order: Iterative solution */
8-
public static Node addReverseOrder(Node n, Node m) {
9-
if (n == null) {
7+
public static Node addReverseOrder(Node m, Node n) {
8+
if (m == null) {
109
return m;
11-
} else if (m == null) {
10+
} else if (n == null) {
1211
return n;
1312
}
1413
int carry = 0;
15-
Node head = null;
16-
Node tail = null;
17-
while (n != null || m != null || carry != 0) {
14+
Node dummy = new Node(0); // 1 Node before the actual head of list
15+
Node tail = dummy;
16+
while (m != null || n != null || carry != 0) {
1817
int value = carry;
19-
if (n != null) {
20-
value += n.data;
21-
n = n.next;
22-
}
2318
if (m != null) {
2419
value += m.data;
2520
m = m.next;
2621
}
22+
if (n != null) {
23+
value += n.data;
24+
n = n.next;
25+
}
2726
int digit = value % 10;
2827
carry = value / 10;
29-
Node toAdd = new Node(digit);
30-
if (head == null) {
31-
head = toAdd;
32-
tail = toAdd;
33-
} else {
34-
tail.next = toAdd;
35-
tail = toAdd;
36-
}
28+
tail.next = new Node(digit);
29+
tail = tail.next;
3730
}
38-
return head;
31+
return dummy.next;
3932
}
4033

41-
/* Forward Order: Recursive solution */
42-
public static Node addForwardOrder(Node n, Node m) {
43-
/* Pad the shorter list with 0's */
44-
int sizeN = ListFunctions.calculateSize(n);
45-
int sizeM = ListFunctions.calculateSize(m);
46-
if (sizeN > sizeM) {
47-
int numberOfZerosToInsert = sizeN - sizeM;
48-
for (int i = 0; i < numberOfZerosToInsert; i++) {
49-
m = ListFunctions.insertInFront(m, 0);
50-
}
51-
} else if (sizeM > sizeN) {
52-
int numberOfZerosToInsert = sizeM - sizeN;
53-
for (int i = 0; i < numberOfZerosToInsert; i++) {
54-
n = ListFunctions.insertInFront(n, 0);
55-
}
34+
public static Node addForwardOrder(Node m, Node n) {
35+
if (m == null) {
36+
return m;
37+
} else if (n == null) {
38+
return n;
5639
}
5740

58-
/* Do the addition */
59-
Pair result = addForwardOrderHelper(n, m);
41+
Stack<Integer> stack1 = new Stack<>();
42+
Stack<Integer> stack2 = new Stack<>();
6043

61-
/* Account for the carry if necessary */
62-
if (result.carry == 0) {
63-
return result.node;
64-
} else {
65-
Node head = new Node(result.carry);
66-
head.next = result.node;
67-
return head;
44+
while (m != null) {
45+
stack1.push(m.data);
46+
m = m.next;
6847
}
69-
}
70-
71-
private static Pair addForwardOrderHelper(Node n, Node m) {
72-
// Either both "n" and "m" are null, or neither are null
73-
if (n == null) {
74-
return new Pair(null, 0);
48+
while (n != null) {
49+
stack2.push(n.data);
50+
n = n.next;
7551
}
7652

77-
Pair rest = addForwardOrderHelper(n.next, m.next);
78-
int value = n.data + m.data + rest.carry;
79-
80-
int digit = value % 10;
81-
int carry = value / 10;
82-
83-
Node head = new Node(digit);
84-
head.next = rest.node;
85-
return new Pair(head, carry);
53+
int carry = 0;
54+
Node dummy = new Node(0); // 1 Node before the actual head of list
55+
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
56+
int value = carry;
57+
if (!stack1.isEmpty()) {
58+
value += stack1.pop();
59+
}
60+
if (!stack2.isEmpty()) {
61+
value += stack2.pop();
62+
}
63+
int digit = value % 10;
64+
carry = value / 10;
65+
Node head = new Node(digit);
66+
head.next = dummy.next;
67+
dummy.next = head;
68+
}
69+
return dummy.next;
8670
}
8771
}
8872

8973
// Time/Space Complexity for both solutions
9074
//
91-
// Time Complexity: O(n + m)
92-
// Space Complexity: O(n + m)
75+
// Time Complexity: O(m + n)
76+
// Space Complexity: O(m + n)

Chp. 02 - Linked Lists/_2_6_Palindrome/Palindrome.java

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,42 +3,52 @@
33
import common.Node;
44
import common.ListFunctions;
55

6-
import java.util.ArrayDeque;
7-
86
public class Palindrome {
97
public static boolean palindrome(Node head) {
10-
int size = ListFunctions.calculateSize(head);
11-
ArrayDeque<Integer> deque = new ArrayDeque<>();
12-
Node curr = head;
13-
/* Save 1st half of list */
14-
for (int i = 0; i < size / 2; i++) {
15-
deque.push(curr.data);
16-
curr = curr.next;
8+
if (head == null) {
9+
return false; // depends on our definition of a palindrome.
10+
}
11+
12+
// Reverse 2nd half of list
13+
Node slow = head;
14+
Node fast = head;
15+
while (fast != null && fast.next != null) {
16+
slow = slow.next;
17+
fast = fast.next.next;
1718
}
18-
/* If list had odd number of elements -> skip middle element */
19-
if (size % 2 == 1) {
20-
curr = curr.next;
19+
if (fast != null) { // for lists with odd # of Nodes
20+
slow = slow.next;
2121
}
22-
/* Compare 2nd half of list to 1st half of list */
23-
while (curr != null) {
24-
if (deque.pop() != curr.data) {
22+
Node slowCenter = ListFunctions.reverseListIterative(slow);
23+
24+
// compare 1st half of list to 2nd half
25+
Node slowFront = head;
26+
ListFunctions.printList(slowFront);
27+
ListFunctions.printList(slowCenter);
28+
29+
while (slowCenter != null) {
30+
if (slowCenter.data != slowFront.data) {
2531
return false;
2632
}
27-
curr = curr.next;
33+
slowFront = slowFront.next;
34+
slowCenter = slowCenter.next;
2835
}
2936
return true;
3037
}
3138
}
3239

3340
// Time Complexity: O(n)
34-
// Space Complexity: O(n)
41+
// Space Complexity: O(1)
3542

3643

37-
// Alternate solution
44+
// Alternate solution - O(n) time, O(n) space
45+
//
46+
// 1. Save 1st half of list in stack
47+
// 2. Compare 2nd half of list to 1st half of list
48+
49+
50+
// Alternate solution - O(n) time, O(n) space
3851
//
3952
// 1. Deep copy list.
4053
// 2. Reverse it.
4154
// 3. Compare it to original.
42-
//
43-
// Time Complexity: O(n)
44-
// Space Complexity: O(n)

0 commit comments

Comments
 (0)