├── .classpath
├── .gitignore
├── .project
├── .settings
└── org.eclipse.jdt.core.prefs
└── src
├── .DS_Store
├── Util
└── Utility.java
├── chapter05
├── question0501.java
├── question0502.java
├── question0503.java
├── question0504.java
├── question0505.java
├── question0506.java
├── question0507.java
├── question0508.java
├── question0509.java
├── question0510.java
├── question0511.java
├── question0512.java
└── question0513.java
├── chapter06
├── question0601.java
├── question0603.java
├── question0605.java
├── question0606.java
├── question0607.java
├── question0609.java
├── question0610.java
├── question0612.java
├── question0613.java
├── question0614.java
├── question0615.java
├── question0616.java
├── question0617.java
├── question0618.java
├── question0619.java
├── question0620.java
├── question0621.java
└── question0622.java
├── chapter07
├── LinkedListNode.java
├── question0701.java
├── question0702.java
├── question0703.java
├── question0704.java
├── question0705.java
├── question0706.java
├── question0707.java
├── question0708.java
├── question0709.java
├── question0710.java
└── question0711.java
├── chapter08
├── PostingListNode.java
├── Queue.java
├── Stack.java
├── question0801.java
├── question0802.java
├── question0804.java
├── question0805.java
├── question0806.java
├── question0807.java
├── question0808.java
├── question0809.java
├── question0810.java
├── question0811.java
├── question0812.java
├── question0813.java
└── question0814.java
├── chapter09
├── TreeNode.java
├── Trie.java
├── question0901.java
├── question0902.java
├── question0903.java
├── question0904.java
├── question0905.java
├── question0906.java
├── question0907.java
├── question0908.java
├── question0909.java
├── question0910.java
├── question0911.java
├── question0912.java
├── question0913.java
└── question0914.java
├── chapter11
├── question1101.java
├── question1102.java
├── question1103.java
├── question1104.java
├── question1105.java
├── question1107.java
├── question1109.java
├── question1110.java
├── question1111.java
├── question1112.java
├── question1113.java
├── question1115.java
├── question1116.java
└── question1118.java
├── chapter12
├── question1203.java
├── question1207.java
├── question1208.java
├── question1209.java
├── question1214.java
├── question1215.java
└── question1216.java
├── chapter13
├── question1305.java
├── question1306.java
├── question1307.java
├── question1308.java
├── question1309.java
├── question1310.java
├── question1311.java
├── question1312.java
├── question1314.java
└── question1315.java
├── chapter14
├── question1401.java
├── question1402.java
├── question1403.java
├── question1404.java
├── question1405.java
├── question1406.java
├── question1407.java
├── question1408.java
├── question1409.java
├── question1411.java
├── question1412.java
├── question1413.java
├── question1414.java
├── question1417.java
├── question1418.java
└── question1420.java
├── chapter15
├── question1502.java
├── question1505.java
├── question1506.java
├── question1508.java
├── question1509.java
├── question1511.java
├── question1512.java
├── question1513.java
├── question1514.java
├── question1515.java
├── question1516.java
├── question1517.java
├── question1518.java
├── question1521.java
├── question1522.java
├── question1523.java
├── question1524.java
├── question1525.java
├── question1526.java
├── question1527.java
└── question1528.java
├── chapter16
├── GraphNode.java
├── question1601.java
├── question1602.java
├── question1603.java
├── question1604.java
├── question1605.java
├── question1606.java
├── question1607.java
├── question1608.java
├── question1609.java
└── question1610.java
├── chapter17
├── question1701.java
├── question1702.java
├── question1703.java
├── question1704.java
├── question1708.java
└── question1712.java
└── common
├── Combination.java
├── DoublyLinkedList.java
├── KMP.java
├── LRU.java
├── MinPriorityQueue.java
├── PartialOrdering.java
├── Permutation.java
├── PivotInRotatedArray.java
├── QuickSort.java
├── ReverseLinkedList.java
├── SelectIndexEqualValue.java
├── Selection.java
└── ShortestPath.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /bin
2 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Elements of Programming Interviews
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.7
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.7
12 |
--------------------------------------------------------------------------------
/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tao-qian/Elements-of-Programming-Interviews-Java-Solution/444a37f064e62efebe75ca65fec1fde013e657e2/src/.DS_Store
--------------------------------------------------------------------------------
/src/Util/Utility.java:
--------------------------------------------------------------------------------
1 | package Util;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | @SuppressWarnings({ "rawtypes" })
7 | public class Utility {
8 |
9 | public static void print(Object[] array) {
10 | for (int i = 0; i < array.length; i++) {
11 | System.out.print(array[i] + " ");
12 | }
13 | System.out.println();
14 | }
15 |
16 | public static void print(Object[][] array) {
17 | for (int i = 0; i < array.length; i++) {
18 | print(array[i]);
19 | }
20 | }
21 |
22 | public static void print(int[] array) {
23 | for (int i = 0; i < array.length; i++) {
24 | System.out.print(array[i] + " ");
25 | }
26 | System.out.println();
27 | }
28 |
29 | public static void print(int[][] array) {
30 | for (int i = 0; i < array.length; i++) {
31 | print(array[i]);
32 | }
33 | }
34 |
35 | public static String toString(List l) {
36 | StringBuilder sb = new StringBuilder();
37 | sb.append("{ ");
38 | for (Object item : l) {
39 | if (item == null) {
40 | sb.append("null");
41 | } else {
42 | sb.append(item.toString() + " ");
43 | }
44 | }
45 | sb.append("}");
46 | return sb.toString();
47 | }
48 |
49 | public static void print(Set s) {
50 | System.out.print("{ ");
51 | for (Object i : s)
52 | System.out.print(i + " ");
53 | System.out.print("}");
54 | }
55 |
56 | public static void print(List a) {
57 | System.out.println(toString(a));
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/chapter05/question0501.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0501 {
4 | public static void main(String[] args) {
5 | System.out.println(getParity(3));
6 | }
7 |
8 | public static int getParity(int n) {
9 | int count = 0;
10 | while (n > 0) {
11 | n = n & (n - 1);
12 | count++;
13 | }
14 | return count;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/chapter05/question0502.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0502 {
4 | public static void main(String[] args) {
5 | System.out.println(swapBit(2, 0, 1));
6 | }
7 |
8 | public static int swapBit(int n, int i, int j) {
9 | int b1 = (n >> i) & 1;
10 | int b2 = (n >> j) & 1;
11 | System.out.println("b1 " + b1);
12 | System.out.println("b2 " + b2);
13 | if (b1 == b2)
14 | return n;
15 | return n ^ ((1 << j) | (1 << i));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/chapter05/question0503.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0503 {
4 |
5 | public static void main(String[] args) {
6 | }
7 |
8 | public static int reverse(int n) {
9 | for (int i = 0; i < 32; i++) {
10 | n = question0502.swapBit(n, i, 31 - i);
11 | }
12 | return n;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/chapter05/question0504.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0504 {
4 |
5 | public static void main(String[] args) {
6 | // TODO Auto-generated method stub
7 |
8 | }
9 |
10 | public static int getSmallest(int n) {
11 | for (int i = 0; i < 31; i++)
12 | if (((n >> i) & 1) != ((n >> (i + 1)) & 1))
13 | return n ^ (1 << n | 1 << (n + 1));
14 | return 0;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/chapter05/question0505.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | import java.util.*;
4 |
5 | public class question0505 {
6 |
7 | /**
8 | * @param args
9 | */
10 | public static void main(String[] args) {
11 | HashSet original = new HashSet();
12 | original.add(0);
13 | original.add(1);
14 | original.add(2);
15 | original.add(3);
16 | original.add(4);
17 |
18 | HashSet> starter = new HashSet>();
19 | starter.add(new HashSet());
20 |
21 | HashSet> result = powerSetK(starter, original, 3);
22 | for (HashSet r : result) {
23 |
24 | Util.Utility.print(r);
25 | System.out.println();
26 | }
27 | }
28 |
29 | public static HashSet> powerSet(HashSet set) {
30 | HashSet> powerSet = new HashSet>();
31 | powerSet.add(new HashSet());
32 | for (Integer i : set) {
33 | HashSet> newPowerSet = cloneNested(powerSet);
34 | for (HashSet old : newPowerSet) {
35 | old.add(i);
36 | }
37 | powerSet.addAll(newPowerSet);
38 | }
39 | return powerSet;
40 | }
41 |
42 | public static HashSet> powerSetK(
43 | HashSet> result, HashSet set, int k) {
44 | if (k == 0)
45 | return result;
46 | HashSet> finalResult = new HashSet>();
47 | for (Integer i : set) {
48 | HashSet> newResult = cloneNested(result);
49 | for (HashSet lastResult : newResult) {
50 | lastResult.add(i);
51 | }
52 | HashSet cloned = clone(set);
53 | cloned.remove(i);
54 | finalResult.addAll(powerSetK(newResult, cloned, k - 1));
55 | }
56 | return finalResult;
57 | }
58 |
59 | public static HashSet> cloneNested(
60 | HashSet> s) {
61 | HashSet> newS = new HashSet>();
62 | for (HashSet ss : s) {
63 | newS.add(clone(ss));
64 | }
65 | return newS;
66 | }
67 |
68 | public static HashSet clone(HashSet s) {
69 | HashSet newS = new HashSet();
70 | for (Integer i : s)
71 | newS.add(i);
72 | return newS;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/chapter05/question0506.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0506 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(stringToInt("0"));
7 | }
8 |
9 | public static int stringToInt(String s) {
10 | boolean isNeg = false;
11 | int i = 0;
12 | if (s.charAt(0) == '-') {
13 | isNeg = true;
14 | i = 1;
15 | }
16 | int sum = 0;
17 | for (; i < s.length(); i++) {
18 | sum = sum * 10 + (s.charAt(i) - '0');
19 | }
20 | if (isNeg)
21 | sum *= -1;
22 | return sum;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/chapter05/question0507.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0507 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(baseConversion(10, 16, "31"));
7 | }
8 |
9 | public static String baseConversion(int b1, int b2, String s) {
10 | int sum = 0;
11 | boolean isNeg = false;
12 | int i = 0;
13 | if (s.charAt(0) == '-') {
14 | i = 1;
15 | isNeg = true;
16 | }
17 | for (; i < s.length(); i++) {
18 | sum = b1 * sum + toNum(s.charAt(i));
19 | }
20 |
21 | StringBuilder sb = new StringBuilder();
22 | while (sum != 0) {
23 | char c = toChar(sum % b2);
24 | sum /= b2;
25 | sb.append(c);
26 | }
27 | if (isNeg)
28 | sb.append('-');
29 | return sb.reverse().toString();
30 | }
31 |
32 | public static char toChar(int n) {
33 | if (n <= 9 && n >= 0)
34 | return (char) (n + '0');
35 | if (n >= 10 && n <= 15)
36 | return (char) (n - 10 + 'A');
37 | return 'G';
38 | }
39 |
40 | public static int toNum(char c) {
41 | if (c <= '9' && c >= '0')
42 | return c - '0';
43 | if (c <= 'F' && c >= 'A')
44 | return c - 'A' + 10;
45 | return -1;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/chapter05/question0508.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0508 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(toNumber("AA"));
7 | }
8 |
9 | public static int toNumber(String s) {
10 | int sum = 0;
11 | for (int i = 0; i < s.length(); i++) {
12 | sum *= 26;
13 | sum += (s.charAt(i) - 'A' + 1);
14 | }
15 | return sum;
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/chapter05/question0509.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | import java.util.*;
4 |
5 | public class question0509 {
6 |
7 | public static void main(String[] args)
8 | {
9 | ArrayList ints = new ArrayList();
10 | ints.add(5);
11 | ints.add(17);
12 | ints.add(32);
13 | String code = EliasGammaEncode(ints);
14 | Util.Utility.print(EliasGammaDecode(code));
15 | }
16 |
17 | public static String EliasGammaEncode(List l)
18 | {
19 | StringBuilder sb = new StringBuilder();
20 | for(Integer i : l)
21 | {
22 | String s = toBinary(i);
23 | for(int j = 0;j EliasGammaDecode(String s)
33 | {
34 | ArrayList result = new ArrayList();
35 | char[] a = s.toCharArray();
36 | int p = 0;
37 | int len = 0;
38 | while(p < a.length)
39 | {
40 | if(a[p] == '0')
41 | {
42 | len ++;
43 | p++;
44 | }
45 | else
46 | {
47 | int i = Integer.parseInt(new String(a,p,len + 1),2);
48 | //System.out.println(i);
49 | result.add(i);
50 | p += len + 1;
51 | len = 0;
52 | }
53 | }
54 | return result;
55 | }
56 |
57 | public static String toBinary(Integer i)
58 | {
59 | return Integer.toBinaryString(i);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/chapter05/question0510.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0510 {
4 |
5 | /**
6 | * @param args
7 | */
8 | public static void main(String[] args) {
9 | System.out.println(getGCD(42, 42));
10 | }
11 |
12 | public static int getGCD(int x, int y) {
13 | if (x == 0)
14 | return y;
15 | if (y == 0)
16 | return x;
17 | boolean xEven = isEven(x);
18 | boolean yEven = isEven(y);
19 | if (xEven && yEven)
20 | return 2 * getGCD(x >> 1, y >> 1);
21 | if (xEven)
22 | return getGCD(x >> 1, y);
23 | if (yEven)
24 | return getGCD(x, y >> 1);
25 | if (x >= y)
26 | return getGCD(y, x - y);
27 | return getGCD(x, y - x);
28 | }
29 |
30 | public static boolean isEven(int x) {
31 | return (x & 1) == 0;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/chapter05/question0511.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | import java.util.ArrayList;
4 |
5 | import Util.Utility;
6 |
7 | public class question0511 {
8 |
9 | /**
10 | * @param args
11 | */
12 | public static void main(String[] args) {
13 | Utility.print(sieve(43));
14 | }
15 |
16 | public static ArrayList sieve(int n) {
17 | boolean[] a = new boolean[n + 1];
18 | for (int i = 0; i < a.length; i++)
19 | a[i] = true;
20 | for (int i = 2; i <= n / 2; i++) {
21 | int crossout = i * i;
22 | while (crossout <= n) {
23 | a[crossout] = false;
24 | crossout += i;
25 | }
26 | }
27 | ArrayList list = new ArrayList();
28 | for (int i = 2; i < a.length; i++)
29 | if (a[i])
30 | list.add(i);
31 | return list;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/chapter05/question0512.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0512 {
4 |
5 | public static void main(String[] args) {
6 |
7 | }
8 |
9 | public static class Rectangle {
10 | public Rectangle(int x, int y, int w, int h) {
11 | this.x = x;
12 | this.y = y;
13 | this.w = w;
14 | this.h = h;
15 | }
16 |
17 | int x;
18 | int y;
19 | int w;
20 | int h;
21 | }
22 |
23 | public static Rectangle getIntersection(Rectangle r1, Rectangle r2) {
24 | if (r1.x < r2.x + r2.w && r2.x < r1.x + r1.w && r1.y < r2.y + r2.h
25 | && r2.y < r1.y + r1.h) {
26 | return new Rectangle(Math.max(r1.x, r2.x), Math.max(r1.y, r2.y),
27 | Math.min(r1.x + r1.w, r2.x + r2.w) - Math.max(r1.x, r2.x),
28 | Math.min(r1.y + r1.h, r2.y + r2.h) - Math.max(r1.y, r2.y));
29 | }
30 | return null;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/chapter05/question0513.java:
--------------------------------------------------------------------------------
1 | package chapter05;
2 |
3 | public class question0513 {
4 |
5 | /**
6 | * @param args
7 | */
8 | public static void main(String[] args) {
9 | System.out.println(multiplyNoOperator(11, 22));
10 | }
11 |
12 | public static int addNoOperator(int x, int y) {
13 | int sum = 0;
14 | int k = 1;
15 | int c = 0;
16 | while (k != 0) {
17 | int a = k & x;
18 | int b = k & y;
19 | // Think about full adder
20 | sum |= a ^ b ^ c;
21 | c = (a & c) | (b & c) | (a & b);
22 | c <<= 1;
23 | k <<= 1;
24 | }
25 | return sum;
26 | }
27 |
28 | public static int multiplyNoOperator(int x, int y) {
29 | int result = 0;
30 | int k = 1;
31 | int scaledY = y;
32 | while (k != 0) {
33 | if ((k & x) != 0)
34 | result = addNoOperator(result, scaledY);
35 | scaledY <<= 1;
36 | k <<= 1;
37 | }
38 | return result;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/chapter06/question0601.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import Util.*;
4 |
5 | public class question0601 {
6 |
7 | public static void main(String[] args) {
8 | int[] a = new int[] { 2, 4, 1, 5, 2, 3, 6, 2 };
9 | partition(a, 0);
10 | Utility.print(a);
11 | }
12 |
13 | public static void partition(int[] a, int i) {
14 | int pivot = a[i];
15 | int smaller = 0;
16 | int equal = 0;
17 | int larger = a.length - 1;
18 | while (equal <= larger) {
19 | if (a[equal] < pivot) {
20 | swap(a, smaller, equal);
21 | smaller++;
22 | equal++;
23 | } else if (a[equal] == pivot) {
24 | equal++;
25 | } else {
26 | swap(a, equal, larger);
27 | larger--;
28 | }
29 | }
30 | }
31 |
32 | public static void swap(int[] a, int p, int q) {
33 | int temp = a[q];
34 | a[q] = a[p];
35 | a[p] = temp;
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/chapter06/question0603.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0603 {
4 |
5 | /**
6 | * @param args
7 | */
8 | public static void main(String[] args) {
9 | // TODO Auto-generated method stub
10 |
11 | }
12 |
13 | public int getCapacity(int[] heights) {
14 | int capacity = 0;
15 | int minHeight = Integer.MAX_VALUE;
16 | for (int i = 0; i < heights.length; i++) {
17 | capacity = Math.max(capacity, heights[i] - minHeight);
18 | minHeight = Math.min(minHeight, heights[i]);
19 | }
20 | return minHeight;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/chapter06/question0605.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import java.util.*;
4 |
5 | public class question0605 {
6 |
7 | public static List findModnSubset(Integer[] n)
8 | {
9 | int[] modList = new int[n.length];
10 | int sumSoFar = 0;
11 | for(int i = 0;i ArrayList toArrayList(T[] a, int start, int end)
29 | {
30 | ArrayList result = new ArrayList();
31 | for(int i = start;i last)
24 | {
25 | end++;
26 | }else
27 | {
28 | int newLongest = end - start + 1;
29 | if(newLongest > longest)
30 | {
31 | longest = newLongest;
32 | longestStart = start;
33 | longestEnd = end;
34 | }
35 | start = i;
36 | end = i;
37 | }
38 | last = a[i];
39 | }
40 | return new int[]{longestStart,longestEnd};
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/chapter06/question0607.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0607 {
4 |
5 |
6 | public static void main(String[] args)
7 | {
8 | int[] A= new int []{1,5,3,6};
9 | int[] B = new int[]{2,1,0,5};
10 | Util.Utility.print(equivalentClass(A, B, 7));
11 | }
12 |
13 | public static int[] equivalentClass(int[] A, int[] B, int n)
14 | {
15 | int[] classes = new int[n];
16 | //Each element is initialized to be in its own class
17 | for(int i = 0;i bClass)
31 | {
32 | classes[A[i]] = bClass;
33 | }
34 | }
35 |
36 | for(int i = 0;i< classes.length;i++)
37 | {
38 | if(classes[i] != i)
39 | {
40 | int value = classes[i];
41 | while(classes[value] != value)
42 | {
43 | value = classes[value];
44 | }
45 | classes[i] = value;
46 | }
47 | }
48 | return classes;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/chapter06/question0609.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import java.util.Random;
4 |
5 | public class question0609 {
6 |
7 | public static void main(String[] args) {
8 | Random r = new Random();
9 | for (int i = 0; i < 1000; i++) {
10 | int a = r.nextInt(1000);
11 | int b = r.nextInt(1000);
12 | int m = a * b;
13 | int mm = Integer.parseInt(multiply(String.valueOf(a),
14 | String.valueOf(b)));
15 | int mmm = multiply2(String.valueOf(a), String.valueOf(b));
16 | if (m != mm)
17 | System.out.println("mm: " + a + " * " + b + " = " + m + " not "
18 | + mm);
19 | if (m != mmm)
20 | System.out.println("mmm: " + a + " * " + b + " = " + m
21 | + " not " + mmm);
22 | }
23 | }
24 |
25 | public static String multiply(String m, String n) {
26 | int carry = 0;
27 | StringBuilder sb = new StringBuilder();
28 | m = new StringBuilder(m).reverse().toString();
29 | n = new StringBuilder(n).reverse().toString();
30 | for (int i = 0; i < m.length() + n.length(); i++) {
31 | int sum = 0;
32 | int max = Math.min(m.length() - 1, i);
33 | for (int j = 0; j <= max; j++) {
34 | int k = i - j;
35 | if (k >= n.length())
36 | continue;
37 | sum += getNum(m.charAt(j)) * getNum(n.charAt(k));
38 | }
39 | sum += carry;
40 | sb.append(sum % 10);
41 | carry = sum / 10;
42 | }
43 | if (carry != 0)
44 | sb.append(carry);
45 | String result = sb.reverse().toString();
46 | if (result.charAt(0) == '0')
47 | result = result.substring(1, result.length());
48 | return result;
49 | }
50 |
51 | public static int multiply2(String m, String n) {
52 | int sum = 0;
53 | for (int i = 0; i < m.length(); i++) {
54 | int md = getNum(m.charAt(i));
55 | int subSum = 0;
56 | for (int j = 0; j < n.length(); j++) {
57 | int nd = getNum(n.charAt(j));
58 | subSum *= 10;
59 | subSum += md * nd;
60 | }
61 | sum *= 10;
62 | sum += subSum;
63 | }
64 | return sum;
65 | }
66 |
67 | public static String reverse(String s) {
68 | return new StringBuilder(s).reverse().toString();
69 | }
70 |
71 | public static int getNum(char c) {
72 | if (c >= '0' && c <= '9')
73 | return c - '0';
74 | return -1;
75 | }
76 |
77 | public static String getZeros(int n) {
78 | StringBuilder sb = new StringBuilder();
79 | for (int i = 0; i < n; i++)
80 | sb.append('0');
81 | return sb.toString();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/chapter06/question0610.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0610 {
4 |
5 | public static void main(String [] args)
6 | {
7 | char[] a = "abc".toCharArray();
8 | int[] permutation = new int[]{2,0,1};
9 | applyPermutation(a, permutation);
10 | System.out.println(new String(a));
11 | }
12 |
13 | public static void applyPermutation(char[] a, int[] permutation)
14 | {
15 | boolean[] checked = new boolean[a.length];
16 | for(int i = 0;i= factorials[factorials.length - 1]) {
34 | return null;
35 | }
36 | for (int i = factNum.length - 1; i > 0; i--) {
37 | factNum[i] = n / factorials[i - 1];
38 | n = n % factorials[i - 1];
39 | }
40 | reverse(factNum, 0, factNum.length - 1);
41 | return lehmerDecoding(factNum);
42 | }
43 |
44 | public static int[] lehmerEncoding(int[] a) {
45 | a = a.clone();
46 | for (int i = 0; i < a.length; i++) {
47 | for (int j = i + 1; j < a.length; j++) {
48 | if (a[j] > a[i]) {
49 | a[j]--;
50 | }
51 | }
52 | }
53 | return a;
54 | }
55 |
56 | public static int[] lehmerDecoding(int[] a) {
57 | a = a.clone();
58 | for (int i = a.length - 1; i >= 0; i--) {
59 | for (int j = i + 1; j < a.length; j++) {
60 | if (a[j] >= a[i]) {
61 | a[j]++;
62 | }
63 | }
64 | }
65 | return a;
66 | }
67 |
68 | public static int permutationIndex(int[] a) {
69 | a = a.clone();
70 | int mul = 1;
71 | int sum = 0;
72 | a = lehmerEncoding(a);
73 | for (int i = a.length - 2; i >= 0; i--) {
74 | sum += a[i] * mul;
75 | mul *= (i + 1);
76 | }
77 | return sum;
78 | }
79 |
80 | public static int permutationIndexOld(int[] a) {
81 | a = a.clone();
82 | reverse(a, 0, a.length - 1);
83 | int mul = 1;
84 | int sum = 0;
85 | LinkedList list = new LinkedList();
86 | for (int i = 0; i < a.length; i++) {
87 | // Add the element to the sorted list
88 | int index = insertToSortedList(list, a[i]);
89 | sum += (i - index) * mul;
90 | mul *= (i + 1);
91 | }
92 | return sum;
93 | }
94 |
95 | public static int insertToSortedList(LinkedList list, int n) {
96 | for (int i = 0; i < list.size(); i++) {
97 | if (list.get(i) < n) {
98 | list.add(i, n);
99 | return i;
100 | }
101 | }
102 | list.add(n);
103 | return list.size() - 1;
104 | }
105 |
106 | public static int[] nextPermutation(int[] a) {
107 | int k = a.length - 2;
108 | while (k >= 0 && a[k] >= a[k + 1]) {
109 | k--;
110 | }
111 | if (k < 0) {
112 | return null;
113 | }
114 | // Everything after k is a descending array with a[k] < a[k+1]
115 | // so we find l with a[l] > a[k] and a[l+1] < a[k]
116 | int l = k + 1;
117 | for (int i = l; i < a.length; i++) {
118 | if (a[i] > a[k]) {
119 | l = i;
120 | } else {
121 | break;
122 | }
123 | }
124 | // Swap
125 | int temp = a[l];
126 | a[l] = a[k];
127 | a[k] = temp;
128 |
129 | // Reverse everything after k, which is still a descending array after
130 | // the swap
131 | reverse(a, k + 1, a.length - 1);
132 | return a;
133 | }
134 |
135 | public static void reverse(int[] a, int start, int end) {
136 | while (start < end) {
137 | int tmp = a[start];
138 | a[start] = a[end];
139 | a[end] = tmp;
140 | start++;
141 | end--;
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/src/chapter06/question0613.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0613 {
4 |
5 | public static void main(String []args)
6 | {
7 | int[] a = {1,2,3,4,5};
8 | rotate(a,3);
9 | Util.Utility.print(a);
10 | }
11 |
12 | //012345
13 | //450123
14 | public static void rotate(int[] a, int offset)
15 | {
16 | //First reverse the entire array
17 | reverse(a, 0, a.length-1);
18 | //Then reverse the sub arrays
19 | offset = offset%a.length;
20 | reverse(a, 0, 0+offset-1);
21 | reverse(a, 0+offset,a.length-1);
22 | }
23 |
24 | public static void reverse(int[] a, int p, int q)
25 | {
26 | while(p < q)
27 | {
28 | int temp = a[p];
29 | a[p] = a[q];
30 | a[q] = temp;
31 | p++;
32 | q--;
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/chapter06/question0614.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0614 {
4 | //Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter06/question0615.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import java.util.ArrayList;
4 |
5 | import Util.Utility;
6 |
7 | public class question0615 {
8 |
9 | public static void main(String args[]) {
10 | int[][] rect = new int[][] { new int[] { 1, 2, 3 },
11 | new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
12 | Utility.print(spiralOrder(rect));
13 | }
14 |
15 | public static ArrayList spiralOrder(int[][] rect) {
16 | int totalSize = rect.length * rect[0].length;
17 | ArrayList result = new ArrayList();
18 |
19 | int xStart = 0;
20 | int yStart = 0;
21 | int xEnd = rect.length - 1;
22 | int yEnd = rect[0].length - 1;
23 |
24 | while (result.size() != totalSize) {
25 | // Special case when the rect is a single row
26 | if (xStart == xEnd) {
27 | for (int i = yStart; i <= yEnd; i++)
28 | result.add(rect[xStart][i]);
29 | continue;
30 | }
31 | // Special case when the rect is a single col
32 | if (yStart == yEnd) {
33 | for (int i = xStart; i <= xEnd; i++)
34 | result.add(rect[i][yStart]);
35 | continue;
36 | }
37 | for (int i = yStart; i <= yEnd - 1; i++)
38 | result.add(rect[xStart][i]);
39 | for (int i = xStart; i <= xEnd - 1; i++)
40 | result.add(rect[i][yEnd]);
41 | for (int i = yEnd; i >= yStart + 1; i--)
42 | result.add(rect[xEnd][i]);
43 | for (int i = xEnd; i >= xStart + 1; i--)
44 | result.add(rect[i][yStart]);
45 | xStart++;
46 | yStart++;
47 | xEnd--;
48 | yEnd--;
49 | }
50 | return result;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/chapter06/question0616.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import java.util.LinkedList;
4 |
5 | public class question0616 {
6 |
7 | public static void painting(boolean[][] map, int startX, int startY) {
8 | boolean color = !map[startX][startY];
9 | LinkedList queue = new LinkedList();
10 | queue.add(new Pair(startX, startY));
11 | int height = map.length;
12 | int width = map[0].length;
13 | while (queue.size() > 0) {
14 | Pair current = queue.pollFirst();
15 | if (current.x + 1 < width && map[current.x + 1][current.y] != color) {
16 | queue.add(new Pair(current.x + 1, current.y));
17 | }
18 | if (current.x - 1 > 0 && map[current.x - 1][current.y] != color) {
19 | queue.add(new Pair(current.x - 1, current.y));
20 | }
21 | if (current.y + 1 < height
22 | && map[current.x][current.y + 1] != color) {
23 | queue.add(new Pair(current.x, current.y + 1));
24 | }
25 | if (current.y - 1 > 0 && map[current.x][current.y - 1] != color) {
26 | queue.add(new Pair(current.x, current.y - 1));
27 | }
28 | map[current.x][current.y] = color;
29 | }
30 | }
31 |
32 | public static class Pair {
33 | int x;
34 | int y;
35 |
36 | Pair(int x, int y) {
37 | this.x = x;
38 | this.y = y;
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/chapter06/question0617.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import Util.Utility;
4 |
5 | public class question0617 {
6 |
7 | public static void main(String[] args) {
8 | // int[][] rect = new int[][]{new int[]{1,2,3},new int[]{8,9,4},new
9 | // int[]{7,6,5}};
10 | int[][] rect = new int[][] { new int[] { 1, 2 }, new int[] { 4, 3 } };
11 | Utility.print(rotate(rect));
12 | }
13 |
14 | public static int[][] rotate(int[][] m) {
15 | int startX = 0;
16 | int endX = m.length - 1;
17 | int startY = 0;
18 | int endY = m.length - 1;
19 | while (startY < endY) {
20 | for (int i = 0; i < endY - startY; i++) {
21 | int temp = m[startX][startY + i];
22 | m[startX][startY + i] = m[endX - i][startY];
23 | m[endX - i][startY] = m[endX][endY - i];
24 | m[endX][endY - i] = m[startX + i][endY];
25 | m[startX + i][endY] = temp;
26 | }
27 | startX++;
28 | endX--;
29 | startY++;
30 | endY--;
31 | }
32 | return m;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/chapter06/question0618.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0618 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(decoding(encoding("aaabbbccd")));
7 | }
8 |
9 | public static String encoding(String s) {
10 | StringBuilder sb = new StringBuilder();
11 | char lastChar = s.charAt(0);
12 | int count = 1;
13 | for (int i = 1; i < s.length(); i++) {
14 | if (s.charAt(i) == lastChar) {
15 | count++;
16 | continue;
17 | }
18 | sb.append(lastChar);
19 | sb.append(count);
20 | count = 1;
21 | lastChar = s.charAt(i);
22 | }
23 | sb.append(lastChar);
24 | sb.append(count);
25 | return sb.toString();
26 | }
27 |
28 | public static String decoding(String s) {
29 | int pointer = 0;
30 | StringBuilder sb = new StringBuilder();
31 | while (pointer < s.length()) {
32 | char c = s.charAt(pointer);
33 | pointer++;
34 | int count = s.charAt(pointer) - '0';
35 | pointer++;
36 | for (int i = 0; i < count; i++)
37 | sb.append(c);
38 | }
39 | return sb.toString();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/chapter06/question0619.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0619 {
4 |
5 | /**
6 | * @param args
7 | */
8 | public static void main(String[] args) {
9 | System.out.println(switchWords(" tao loves zx"));
10 | }
11 |
12 | public static String switchWords(String s) {
13 | s = reverse(s, 0, s.length() - 1);
14 | int start = 0;
15 | int end = 0;
16 | while (start < s.length()) {
17 | while (end < s.length() && s.charAt(end) != ' ') {
18 | end++;
19 | }
20 | s = reverse(s, start, end - 1);
21 | end++;
22 | start = end;
23 | }
24 | return s;
25 | }
26 |
27 | public static String reverse(String s, int start, int end) {
28 | char[] as = s.toCharArray();// No better way to do in place string
29 | // manipulation in Java
30 | while (start < end) {
31 | char temp = as[start];
32 | as[start] = as[end];
33 | as[end] = temp;
34 | start++;
35 | end--;
36 | }
37 | return new String(as);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/chapter06/question0620.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | public class question0620 {
4 |
5 | public static void main(String []args)
6 | {
7 | Util.Utility.print(buildTable("ababaababa"));
8 | }
9 |
10 | //Here we use KMP
11 | public static int KMP(String s, String w)
12 | {
13 | int[] table = buildTable(w);
14 | int sp = 0;
15 | int wp = 0;
16 | while (sp < s.length()) {
17 | if (s.charAt(sp + wp) == w.charAt(wp)) {
18 | wp++;
19 | if (wp == w.length()) {
20 | return sp;
21 | }
22 | continue;
23 | }
24 | // It works because table[0] = -1
25 | sp = sp + wp - table[wp];
26 | if (wp > 0) {
27 | wp = table[wp];
28 | }
29 | }
30 | return -1;
31 | }
32 |
33 | //a b a b a
34 | //-1 0 0 1 2
35 | public static int[] buildTable(String w)
36 | {
37 | char[] a = w.toCharArray();
38 | int[] table = new int[a.length];
39 | table[0] = -1;
40 | int p = 0;
41 | for(int i = 1;i= 0; readPointer--) {
35 | if (newC[readPointer] == 'a') {
36 | endWritePointer--;
37 | newC[endWritePointer] = 'd';
38 | endWritePointer--;
39 | newC[endWritePointer] = 'd';
40 | continue;
41 | }
42 | endWritePointer--;
43 | newC[endWritePointer] = newC[readPointer];
44 | }
45 | return new String(newC);
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/chapter06/question0622.java:
--------------------------------------------------------------------------------
1 | package chapter06;
2 |
3 | import java.util.ArrayList;
4 |
5 | import Util.Utility;
6 |
7 | public class question0622 {
8 |
9 | public static String[] mapping = new String[] { "", "", "ABC", "DEF",
10 | "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" };
11 |
12 | /**
13 | * @param args
14 | */
15 | public static void main(String[] args) {
16 | Utility.print(getAllCombination("1234"));
17 | }
18 |
19 | public static ArrayList getAllCombination(String numbers) {
20 | ArrayList result = new ArrayList();
21 | result.add(new StringBuilder());
22 | for (int i = 0; i < numbers.length(); i++) {
23 | char num = numbers.charAt(i);
24 | char[] choices = mapping[num - '0'].toCharArray();
25 | if (choices.length == 0) {
26 | append(result, num);
27 | continue;
28 | }
29 | ArrayList clone = result;
30 | result = new ArrayList();
31 | for (int j = 0; j < choices.length; j++) {
32 | ArrayList newClone = clone(clone);
33 | append(newClone, choices[j]);
34 | result.addAll(newClone);
35 | }
36 | }
37 | ArrayList stringResult = new ArrayList();
38 | for (int i = 0; i < result.size(); i++)
39 | stringResult.add(result.get(i).toString());
40 | return stringResult;
41 | }
42 |
43 | public static ArrayList clone(ArrayList a) {
44 | ArrayList n = new ArrayList();
45 | for (int i = 0; i < a.size(); i++)
46 | n.add(new StringBuilder(a.get(i)));
47 | return n;
48 | }
49 |
50 | public static void append(ArrayList a, char c) {
51 | for (int i = 0; i < a.size(); i++)
52 | a.get(i).append(c);
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/chapter07/LinkedListNode.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | import java.util.Arrays;
4 | import java.util.Random;
5 |
6 | public class LinkedListNode {
7 | public T data;
8 | public LinkedListNode next;
9 |
10 | public LinkedListNode(T n) {
11 | this.data = n;
12 | }
13 |
14 | public void printNode() {
15 | LinkedListNode runner = this;
16 | while (runner != null) {
17 | System.out.print(runner.data + "->");
18 | runner = runner.next;
19 | }
20 | System.out.println("NULL");
21 | }
22 |
23 | public String toString() {
24 | return data.toString();
25 | }
26 |
27 | public static LinkedListNode randomList(int length, int max) {
28 | Random r = new Random();
29 | LinkedListNode n = new LinkedListNode(r.nextInt(max));
30 | n.next = null;
31 | for (int i = 1; i < length; i++) {
32 | LinkedListNode nn = new LinkedListNode(r.nextInt(max));
33 | nn.next = n;
34 | n = nn;
35 | }
36 | return n;
37 | }
38 |
39 | public static LinkedListNode randomSortedList(int length, int max) {
40 | Random r = new Random();
41 | int[] list = new int[length];
42 | for (int i = 0; i < length; i++)
43 | list[i] = r.nextInt(max);
44 | Arrays.sort(list);
45 | return arrayToList(list);
46 | }
47 |
48 | @SuppressWarnings("rawtypes")
49 | public static void printList(LinkedListNode n) {
50 | while (n != null) {
51 | System.out.print(n.data + "->");
52 | n = n.next;
53 | }
54 | System.out.println("null");
55 | }
56 |
57 | public static LinkedListNode arrayToList(int[] array) {
58 | LinkedListNode n = new LinkedListNode(array[0]);
59 | LinkedListNode runner = n;
60 | for (int i = 1; i < array.length; i++) {
61 | LinkedListNode nextNode = new LinkedListNode(array[i]);
62 | runner.next = nextNode;
63 | runner = nextNode;
64 | }
65 | runner.next = null;
66 | return n;
67 | }
68 | }
--------------------------------------------------------------------------------
/src/chapter07/question0701.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0701 {
4 |
5 | public static void main(String[] args) {
6 | LinkedListNode n1 = LinkedListNode.randomSortedList(4, 100);
7 | LinkedListNode n2 = LinkedListNode.randomSortedList(1, 100);
8 | n1.printNode();
9 | n2.printNode();
10 | LinkedListNode n3 = merge(n1, n2);
11 | n3.printNode();
12 | }
13 |
14 | public static LinkedListNode merge(LinkedListNode l, LinkedListNode r) {
15 | LinkedListNode pl = l;
16 | LinkedListNode pr = r;
17 | LinkedListNode top = l;
18 | LinkedListNode last = l;
19 | if (l.data > r.data) {
20 | top = r;
21 | last = r;
22 | pr = pr.next;
23 | } else {
24 | pl = pl.next;
25 | }
26 | while (pl != null && pr != null) {
27 | if (pl.data > pr.data) {
28 | last.next = pr;
29 | last = pr;
30 | pr = pr.next;
31 | } else {
32 | last.next = pl;
33 | last = pl;
34 | pl = pl.next;
35 | }
36 | }
37 | if (pl != null)
38 | last.next = pl;
39 | else
40 | last.next = pr;
41 |
42 | return top;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/chapter07/question0702.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0702 {
4 |
5 | @SuppressWarnings("rawtypes")
6 | public static LinkedListNode checkCycle(LinkedListNode start) {
7 | LinkedListNode p1 = start;
8 | LinkedListNode p2 = start;
9 | if (p2 == null) {
10 | return null;
11 | }
12 | while (p2.next != null && p2.next.next != null) {
13 | p2 = p2.next.next;
14 | p1 = p1.next;
15 | if (p1 == p2) {
16 | // Count the length of the cycle
17 | // and advance a counter from the start
18 | // by the same amount
19 | LinkedListNode p3 = start;
20 | while (p1 != p2) {
21 | p1 = p1.next;
22 | p3 = p3.next;
23 | }
24 | p1 = start;
25 | while (p1 != p3) {
26 | p1 = p1.next;
27 | p3 = p3.next;
28 | }
29 | return p1;
30 | }
31 | }
32 | return null;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/chapter07/question0703.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0703 {
4 |
5 | @SuppressWarnings({ "rawtypes", "unchecked" })
6 | public static void main(String[] args) {
7 | int[] a = new int[] { 2, 2, 2, 3, 3, 4, 4 };
8 | LinkedListNode s = LinkedListNode.arrayToList(a);
9 | LinkedListNode p1 = s;
10 | for (int i = 0; i < a.length - 1; i++) {
11 | p1 = p1.next;
12 | }
13 | p1.next = s;
14 | System.out.println(getMedian(s));
15 | }
16 |
17 | public static double getMedian(LinkedListNode s) {
18 | LinkedListNode p1 = s;
19 | int count = 1;
20 | LinkedListNode smallest = s;
21 | boolean different = false;
22 |
23 | while (p1.next != s) {
24 | if (p1.next.data < p1.data) {
25 | smallest = p1.next;
26 | }
27 | if (!different && p1.next.data != p1.data) {
28 | different = true;
29 | }
30 | p1 = p1.next;
31 | count++;
32 | }
33 | if (!different) {
34 | return s.data;
35 | }
36 | if (count % 2 == 1) {
37 | for (int i = 0; i < count / 2; i++) {
38 | smallest = smallest.next;
39 | }
40 | return smallest.data;
41 | }
42 | for (int i = 0; i < count / 2 - 1; i++) {
43 | smallest = smallest.next;
44 | }
45 | return ((double) smallest.data + smallest.next.data) / 2;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/chapter07/question0704.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0704 {
4 | // Not tested
5 | @SuppressWarnings("rawtypes")
6 | public static LinkedListNode findStart(LinkedListNode n1, LinkedListNode n2) {
7 | int l1 = getLength(n1);
8 | int l2 = getLength(n2);
9 | LinkedListNode r1 = n1;
10 | LinkedListNode r2 = n2;
11 | if (l1 > l2) {
12 | advance(r1, l1 - l2);
13 | } else if (l2 > l1) {
14 | advance(r2, l2 - l1);
15 | }
16 | while (r1 != null && r2 != null) {
17 | if (r1 == r2)
18 | return r1;
19 | r1 = r1.next;
20 | r2 = r2.next;
21 | }
22 | return null;
23 | }
24 |
25 | @SuppressWarnings("rawtypes")
26 | public static LinkedListNode advance(LinkedListNode n, int steps) {
27 | for (int i = 0; i < steps; i++) {
28 | n = n.next;
29 | }
30 | return n;
31 | }
32 |
33 | @SuppressWarnings("rawtypes")
34 | public static int getLength(LinkedListNode n) {
35 | int length = 0;
36 | while (n != null) {
37 | n = n.next;
38 | length++;
39 | }
40 | return length;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/chapter07/question0705.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0705 {
4 | // Not implemented because using previous written functions
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter07/question0706.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0706 {
4 |
5 | public static void main(String[] args) {
6 | LinkedListNode list = LinkedListNode.arrayToList(new int[] { 0, 1, 2, 3, 4, 5 });
7 | list.printNode();
8 | evenOdd(list).printNode();
9 | }
10 |
11 | @SuppressWarnings({ "rawtypes", "unchecked" })
12 | public static LinkedListNode evenOdd(LinkedListNode n) {
13 | LinkedListNode even = n;
14 | if (even == null)
15 | return null;
16 | LinkedListNode odd = n.next;
17 | LinkedListNode oddTop = odd;
18 | while (odd != null && odd.next != null) {
19 | even.next = odd.next;
20 | even = even.next;
21 | odd.next = even.next;
22 | odd = odd.next;
23 | }
24 | even.next = oddTop;
25 | return n;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/chapter07/question0707.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0707 {
4 |
5 | @SuppressWarnings({ "rawtypes", "unchecked" })
6 | public static void deleteNode(LinkedListNode s) {
7 | s.data = s.next.data;
8 | s.next = s.next.next;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/chapter07/question0708.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0708 {
4 | public static void main(String[] args) {
5 | LinkedListNode n = LinkedListNode.arrayToList(new int[] { 1, 2, 3, 4, 5, 6 });
6 | LinkedListNode.printList(n);
7 | System.out.println(deleteLastK(n, 6));
8 | LinkedListNode.printList(n);
9 |
10 | }
11 |
12 | @SuppressWarnings({ "rawtypes", "unchecked" })
13 | public static boolean deleteLastK(LinkedListNode s, int k) {
14 | LinkedListNode p1 = s;
15 | LinkedListNode p2 = s;
16 | for (int i = 0; i < k; i++) {
17 | if (p1 == null) {
18 | return false;
19 | }
20 | p1 = p1.next;
21 | }
22 | if (p1 == null) {
23 | return false;
24 | }
25 | while (p1.next != null) {
26 | p1 = p1.next;
27 | p2 = p2.next;
28 | }
29 | p2.next = p2.next.next;
30 | return true;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/chapter07/question0709.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0709 {
4 |
5 | public static void main(String[] args) {
6 | LinkedListNode list = LinkedListNode.arrayToList(new int[] { 0, 1, 2, 3, 4 });
7 | reverse(list).printNode();
8 | }
9 |
10 | @SuppressWarnings({ "rawtypes", "unchecked" })
11 | public static LinkedListNode reverse(LinkedListNode n) {
12 | if (n == null)
13 | return null;
14 | LinkedListNode front = n;
15 | LinkedListNode end = n;
16 | while (end.next != null) {
17 | LinkedListNode temp = front;
18 | front = end.next;
19 | end.next = front.next;
20 | front.next = temp;
21 | }
22 | end.next = null;
23 | return front;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/chapter07/question0710.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0710 {
4 | // Trivial with the solution from question0709
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter07/question0711.java:
--------------------------------------------------------------------------------
1 | package chapter07;
2 |
3 | public class question0711 {
4 | // Not implemented because solution is trivial
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter08/PostingListNode.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | // Used by question0804
4 | public class PostingListNode {
5 | public PostingListNode next;
6 | public PostingListNode jump;
7 | public int order = -1;
8 | }
9 |
--------------------------------------------------------------------------------
/src/chapter08/Queue.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.LinkedList;
4 |
5 | import chapter07.LinkedListNode;
6 |
7 | public class Queue {
8 |
9 | protected LinkedListNode head;
10 | protected LinkedListNode tail;
11 | protected int size;
12 |
13 | public Queue() {
14 | head = null;
15 | tail = null;
16 | size = 0;
17 | }
18 |
19 | public LinkedList> toLinkedList() {
20 | LinkedList> list = new LinkedList>();
21 | LinkedListNode p = head;
22 | while (p != null) {
23 | list.addLast(p);
24 | p = p.next;
25 | }
26 | return list;
27 | }
28 |
29 | public void enqueue(T n) {
30 | LinkedListNode newNode = new LinkedListNode(n);
31 | if (tail == null) {
32 | head = newNode;
33 | } else {
34 | tail.next = newNode;
35 | }
36 | tail = newNode;
37 | size++;
38 | }
39 |
40 | public T dequeue() throws Exception {
41 | if (head == null) {
42 | throw new Exception("queue is empty!");
43 | }
44 | T result = head.data;
45 | head = head.next;
46 | if (head == null) {
47 | tail = null;
48 | }
49 | size--;
50 | return result;
51 | }
52 |
53 | public T peek() throws Exception {
54 | if (head == null) {
55 | throw new Exception("Queue is empty!");
56 | }
57 | return head.data;
58 | }
59 |
60 | public T peekTail() throws Exception {
61 | if (tail == null) {
62 | throw new Exception("Queue is empty");
63 | }
64 | return tail.data;
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/chapter08/Stack.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.LinkedList;
4 |
5 | import chapter07.LinkedListNode;
6 |
7 | public class Stack {
8 | protected LinkedListNode head;
9 | protected int size;
10 |
11 | public Stack() {
12 | head = null;
13 | size = 0;
14 | }
15 |
16 | public LinkedList> toLinkedList() {
17 | LinkedList> list = new LinkedList>();
18 | LinkedListNode p = head;
19 | while (p != null) {
20 | list.addFirst(p);
21 | p = p.next;
22 | }
23 | return list;
24 | }
25 |
26 | public void push(T n) {
27 | LinkedListNode newNode = new LinkedListNode(n);
28 | newNode.next = head;
29 | head = newNode;
30 | size++;
31 | }
32 |
33 | public T pop() throws Exception {
34 | if (head == null) {
35 | throw new Exception("Stack is empty!");
36 | }
37 | T result = head.data;
38 | head = head.next;
39 | size--;
40 | return result;
41 | }
42 |
43 | public T peek() throws Exception {
44 | if (head == null) {
45 | throw new Exception("Stack is empty!");
46 | }
47 | return head.data;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/chapter08/question0801.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0801 {
4 |
5 | public class MaxStack extends Stack {
6 | public Stack max;
7 |
8 | public MaxStack() {
9 | super();
10 | max = new Stack();
11 | }
12 |
13 | public void push(int n) {
14 | if (max.head == null || max.head.data <= n) {
15 | max.push(n);
16 | }
17 | super.push(n);
18 | }
19 |
20 | public Integer pop() throws Exception {
21 | int n = super.pop();
22 | if (n == max.head.data) {
23 | max.pop();
24 | }
25 | return n;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/chapter08/question0802.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.*;
4 |
5 | public class question0802 {
6 |
7 | static HashSet operators;
8 | static {
9 | operators = new HashSet();
10 | operators.add('+');
11 | operators.add('-');
12 | operators.add('*');
13 | operators.add('/');
14 | }
15 |
16 | public static void main(String[] args) throws Exception {
17 | System.out.println(evaluateRPN(new char[] { '1', '2', '+', '-', '-',
18 | '-', '3', '*' })
19 | + " ");
20 | }
21 |
22 | public static int evaluateRPN(char[] rpns) throws Exception {
23 | Stack numbers = new Stack();
24 | boolean isNegative = false;
25 | char op = '.';
26 | for (int i = 0; i < rpns.length; i++) {
27 | char c = rpns[i];
28 | // If it is an operator
29 | if (operators.contains(c)) {
30 | // Every operator other than - requires two operands
31 | // And here we assume the negating - has lower precedence than
32 | // the minus -
33 | if (numbers.size < 2) {
34 | if (c != '-') {
35 | throw new Exception("Invalid RPN");
36 | } else {
37 | isNegative = !isNegative;
38 | }
39 | continue;
40 | }
41 | op = c;
42 | int b = numbers.pop();
43 | int a = numbers.pop();
44 | switch (op) {
45 | case '+':
46 | numbers.push(a + b);
47 | break;
48 | case '-':
49 | numbers.push(a - b);
50 | break;
51 | case '*':
52 | numbers.push(a * b);
53 | break;
54 | case '/':
55 | numbers.push(a / b);
56 | break;
57 | default:
58 | throw new Exception("Invalid operator");
59 | }
60 | continue;
61 | }
62 | // Check if is a number
63 | if (c > '9' || c < '0') {
64 | throw new Exception("Invalid char");
65 | }
66 | int num = c - '0';
67 | if (isNegative) {
68 | num *= -1;
69 | }
70 | numbers.push(num);
71 | }
72 | return numbers.pop();
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/chapter08/question0804.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0804 {
4 | public void traversePostingList(PostingListNode s) throws Exception {
5 | Stack stack = new Stack();
6 | int order = 0;
7 | stack.push(s);
8 | while (stack.size != 0) {
9 | PostingListNode n = stack.pop();
10 | if (n.order == -1) {
11 | continue;
12 | }
13 | n.order = order;
14 | order++;
15 | stack.push(n.next);
16 | stack.push(n.jump);
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/chapter08/question0805.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0805 {
4 |
5 | public static void towerOfHanoi(int from, int to, int temp, int n) {
6 | if (n == 1) {
7 | System.out.println(from + " -> " + to);
8 | return;
9 | }
10 | towerOfHanoi(from, temp, to, n - 1);
11 | towerOfHanoi(from, to, temp, 1);
12 | towerOfHanoi(temp, to, from, n - 1);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/chapter08/question0806.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0806 {
4 | public static Stack getSunsetWindows(int[] heights)
5 | throws Exception {
6 | Stack good = new Stack();
7 | for (int i = 0; i < heights.length; i++) {
8 | while (good.size > 0 && good.peek() <= heights[i]) {
9 | good.pop();
10 | }
11 | // Here we only record the heights of the good windows,
12 | // it is better to record the index of those windows, as required by
13 | // the question
14 | // to achieve that, create a new class which contains both index and
15 | // height
16 | good.push(heights[i]);
17 | }
18 | return good;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/chapter08/question0807.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0807 {
4 | // Not implemented because question is unclear
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter08/question0808.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.LinkedList;
4 | import java.util.StringTokenizer;
5 |
6 | import chapter07.LinkedListNode;
7 |
8 | public class question0808 {
9 |
10 | public static void main(String[] args) throws Exception {
11 | System.out.println(getShortestPath("/./../tao/../tt/../..//ss"));
12 | }
13 |
14 | public static String getShortestPath(String original) throws Exception {
15 | Stack pathStack = new Stack();
16 | StringTokenizer st = new StringTokenizer(original);
17 | while (st.hasMoreTokens()) {
18 | String token = st.nextToken("/");
19 | if (token.equals("..")) {
20 | if (pathStack.size == 0 || pathStack.peek() == "..") {
21 | pathStack.push("..");
22 | } else {
23 | pathStack.pop();
24 | }
25 | } else if (token.equals(".")) {
26 | continue;
27 | } else if (token.equals("")) {
28 | continue;
29 | } else {
30 | pathStack.push(token);
31 | }
32 | }
33 | StringBuilder sb = new StringBuilder();
34 | if (original.startsWith("/")) {
35 | sb.append("/");
36 | }
37 | LinkedList> list = pathStack.toLinkedList();
38 | for (LinkedListNode s : list) {
39 | sb.append("/" + s.data);
40 | }
41 | return sb.toString();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/chapter08/question0809.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import chapter09.TreeNode;
4 |
5 | public class question0809 {
6 |
7 | public static void traverseByLevel(TreeNode root) throws Exception {
8 | Queue> q = new Queue>();
9 | int levelCount = 1;
10 | int nextLevelCount = 0;
11 | q.enqueue(root);
12 | while (q.size != 0) {
13 | while (levelCount != 0) {
14 | TreeNode n = q.dequeue();
15 | System.out.print(n + " ");
16 | if (n.left != null) {
17 | q.enqueue(n.left);
18 | nextLevelCount++;
19 | }
20 | if (n.right != null) {
21 | q.enqueue(n.right);
22 | nextLevelCount++;
23 | }
24 | }
25 | System.out.println();
26 | levelCount = nextLevelCount;
27 | nextLevelCount = 0;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/chapter08/question0810.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.Arrays;
4 | import java.util.NoSuchElementException;
5 |
6 | public class question0810 {
7 |
8 | /**
9 | * This is an implementation of a bounded queue in Java. This implementation
10 | * supports common queue operations like enqueue and dequeue. Internally, an
11 | * array of integers is used to store the elements in the queue. The size of
12 | * the array expands as more elements are added to the queue. The enqueue()
13 | * operation runs in amortized constant time and the dequeue operation runs
14 | * in constant time.
15 | *
16 | * @author Tao Qian (taoqian_2015@depauw.edu)
17 | *
18 | */
19 | public class Queue {
20 |
21 | private int[] block;
22 | private int head;
23 | private int tail;
24 | private int size;
25 | private int bound;
26 | private final static int INITIAL_CAPACITY = 10;
27 |
28 | /**
29 | * Constructs an empty queue with the specified initial capacity and
30 | * bound.
31 | *
32 | * @param initialCapacity
33 | * the initial capacity of the queue
34 | * @param bound
35 | * the bound of the queue
36 | * @exception IllegalArgumentException
37 | * if the specified initial capacity is negative
38 | */
39 | public Queue(int initialCapacity, int bound) {
40 | if (initialCapacity < 0)
41 | throw new IllegalArgumentException("Illegal Capacity: "
42 | + initialCapacity);
43 | if (bound < initialCapacity)
44 | throw new IllegalArgumentException(
45 | "Bound cannot be smaller than the capacity");
46 | this.block = new int[initialCapacity];
47 | this.bound = bound;
48 | head = 0;
49 | tail = 0;
50 | size = 0;
51 | }
52 |
53 | /**
54 | * Constructs an empty queue with an initial capacity of 0, and the
55 | * specified bound.
56 | *
57 | * @param bound
58 | * the bound of the queue
59 | */
60 | public Queue(int bound) {
61 | this(0, bound);
62 | }
63 |
64 | /**
65 | * Constructs an empty list with an initial capacity of 10, and bound of
66 | * Integer.MAX_VALUE, though the actually bound is a smaller value
67 | * determined by the VM and the memory available.
68 | *
69 | */
70 | public Queue() {
71 | this(INITIAL_CAPACITY, Integer.MAX_VALUE);
72 | }
73 |
74 | /**
75 | * Increases the capacity of this Queue instance, if necessary,
76 | * to ensure that it can hold at least the number of elements specified
77 | * by the minimum capacity argument.
78 | *
79 | * @param minCapacity
80 | * the desired minimum capacity, assumed to be no greater
81 | * than the bound
82 | */
83 | private void ensureCapacity(int minCapacity) {
84 | int oldCapacity = block.length;
85 | if (minCapacity <= oldCapacity)// No need to expand the block
86 | return;
87 |
88 | int newCapacity = (oldCapacity * 3) / 2 + 1;// Increase the size by
89 | // at
90 | // least 50%.
91 | if (newCapacity < minCapacity)
92 | newCapacity = minCapacity;
93 | if (newCapacity > bound)
94 | newCapacity = bound;
95 |
96 | // Copy data in the original array to a new one
97 | int[] newBlock;
98 | if (head != tail)// If tail did not wrap around
99 | {
100 | newBlock = Arrays.copyOf(block, newCapacity);
101 | } else// if tail wrapped around(head == tail)
102 | {
103 | newBlock = new int[newCapacity];
104 | int newPointer = 0;
105 | for (int i = head; i < oldCapacity; i++) {
106 | newBlock[newPointer] = block[i];
107 | newPointer++;
108 | }
109 | for (int i = 0; i < head; i++) {
110 | newBlock[newPointer] = block[i];
111 | newPointer++;
112 | }
113 | // Reset head and tail
114 | head = 0;
115 | tail = oldCapacity;
116 | }
117 | block = newBlock;
118 | }
119 |
120 | /**
121 | * Add an item to the end of the queue.
122 | *
123 | * @param item
124 | * the item to be added.
125 | * @exception IllegalArgumentException
126 | * If the size of the queue reaches its bound
127 | */
128 | public void enqueue(int item) {
129 | size++;
130 | if (size > bound) {
131 | throw new IllegalArgumentException(
132 | "Size of queue exceeded bound");
133 | }
134 | ensureCapacity(size);
135 | if (tail == block.length)
136 | tail = 0;
137 | block[tail] = item;
138 | tail++;
139 | }
140 |
141 | /**
142 | * Remove an item from the front of the queue.
143 | *
144 | * @return the item at the front of the queue
145 | * @exception NoSuchElementException
146 | * If the queue is empty
147 | */
148 | public int dequeue() {
149 | if (size == 0)// If array is empty
150 | throw new NoSuchElementException();
151 | size--;
152 | int item = block[head];
153 | head++;
154 | if (head == block.length)
155 | head = 0;
156 | return item;
157 | }
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/src/chapter08/question0811.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0811 {
4 |
5 | public static void main(String[] args) throws Exception {
6 | TwoIntQueue q = new TwoIntQueue();
7 | q.enqueue(0);
8 | q.enqueue(0);
9 | q.enqueue(1);
10 | q.enqueue(2);
11 | q.enqueue(0);
12 | q.enqueue(0);
13 | q.enqueue(3);
14 | q.enqueue(4);
15 | q.enqueue(0);
16 | q.enqueue(0);
17 | while (q.size != 0) {
18 | System.out.println(q.dequeue());
19 | }
20 | }
21 |
22 | public static class TwoIntQueue {
23 | private int n;
24 | private int size;
25 |
26 | public TwoIntQueue() {
27 | n = 0;
28 | size = 0;
29 | }
30 |
31 | public void enqueue(int k) {
32 | n = n * 10 + k;
33 | size++;
34 | }
35 |
36 | public int dequeue() throws Exception {
37 | if (size == 0) {
38 | throw new Exception("Queue is empty");
39 | }
40 | int d = (int) Math.pow(10, size - 1);
41 | int r = n / d;
42 | n = n - r * d;
43 | size--;
44 | return r;
45 | }
46 |
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/chapter08/question0812.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0812 {
4 | public static void main(String[] args) throws Exception {
5 |
6 | TwoStackQueue q = new TwoStackQueue();
7 | q.enqueue(0);
8 | q.enqueue(0);
9 | q.enqueue(1);
10 | q.enqueue(2);
11 | q.enqueue(0);
12 | q.enqueue(0);
13 | q.enqueue(3);
14 | q.enqueue(4);
15 | q.enqueue(0);
16 | q.enqueue(0);
17 | while (q.size() != 0) {
18 | System.out.println(q.dequeue());
19 | }
20 | }
21 |
22 | public static class TwoStackQueue {
23 | private Stack input;
24 | private Stack output;
25 |
26 | public int size() {
27 | return input.size + output.size;
28 | }
29 |
30 | public TwoStackQueue() {
31 | input = new Stack();
32 | output = new Stack();
33 | }
34 |
35 | public void enqueue(T data) {
36 | input.push(data);
37 | }
38 |
39 | public T dequeue() throws Exception {
40 | if (output.size == 0) {
41 | while (input.size != 0) {
42 | output.push(input.pop());
43 | }
44 | }
45 | if (output.size == 0) {
46 | throw new Exception("Queue is empty");
47 | }
48 | return output.pop();
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/chapter08/question0813.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Random;
5 |
6 | import Util.Utility;
7 | import chapter07.LinkedListNode;
8 |
9 | public class question0813 {
10 |
11 | public static void main(String[] args) throws Exception {
12 | System.out.println("Test started");
13 | MaxQueue q = new MaxQueue();
14 | Random r = new Random();
15 | for (int i = 0; i < 1000; i++) {
16 | int randomAction = r.nextInt(3);
17 | if (randomAction >= 1 && q.size() > 0) {
18 | q.dequeue();
19 | } else {
20 | q.enqueue(r.nextInt(1000));
21 | }
22 | if (q.size() > 0) {
23 | int nMax = q.naiveMax();
24 | int max = q.max();
25 | if (nMax != max) {
26 | System.out.println(q.toString());
27 | System.out.print(max);
28 | System.out.println(" " + nMax);
29 | }
30 | }
31 | }
32 | System.out.println("Test ended");
33 | }
34 |
35 | public static class MaxQueue {
36 | private Queue q;
37 | private LinkedList max;
38 |
39 | public String toString() {
40 | LinkedList> l = q.toLinkedList();
41 | String result = "q " + Utility.toString(l) + "\n";
42 | result += "max " + Utility.toString(max);
43 | return result;
44 | }
45 |
46 | public int size() {
47 | return q.size;
48 | }
49 |
50 | public int naiveMax() {
51 | LinkedList> l = q.toLinkedList();
52 | int max = Integer.MIN_VALUE;
53 | for (LinkedListNode n : l) {
54 | if (n.data > max) {
55 | max = n.data;
56 | }
57 | }
58 | return max;
59 | }
60 |
61 | public MaxQueue() {
62 | q = new Queue();
63 | max = new LinkedList();
64 | }
65 |
66 | public void enqueue(int n) throws Exception {
67 | q.enqueue(n);
68 | while (max.size() != 0 && max.getLast() < n) {
69 | max.removeLast();
70 | }
71 | max.addLast(n);
72 | }
73 |
74 | public int dequeue() throws Exception {
75 | if (q.size == 0) {
76 | throw new Exception("Queue is empty");
77 | }
78 | int result = q.dequeue();
79 | if (result == max.peek()) {
80 | max.removeFirst();
81 | }
82 | return result;
83 | }
84 |
85 | public int max() throws Exception {
86 | if (q.size == 0) {
87 | throw new Exception("Queue is empty");
88 | }
89 | return max.getFirst();
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/chapter08/question0814.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | public class question0814 {
4 |
5 | // Not implemented
6 | }
7 |
--------------------------------------------------------------------------------
/src/chapter09/TreeNode.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import java.util.*;
4 |
5 | public class TreeNode {
6 |
7 | public static void main(String[] args) {
8 | TreeNode tree = new TreeNode(2);
9 | tree.left = new TreeNode(1);
10 | beautifulPrint(tree);
11 | }
12 |
13 | public TreeNode left;
14 | public TreeNode right;
15 | public TreeNode parent;
16 | public T data;
17 |
18 | public TreeNode(T n) {
19 | this.data = n;
20 | left = null;
21 | right = null;
22 | parent = null;
23 | }
24 |
25 | public String toString() {
26 | return data.toString();
27 | }
28 |
29 | public ArrayList inOrder() {
30 | ArrayList result = new ArrayList();
31 | inOrderRecur(this, result);
32 | return result;
33 | }
34 |
35 | private void inOrderRecur(TreeNode root, ArrayList result) {
36 | if (root == null) {
37 | return;
38 | }
39 | inOrderRecur(root.left, result);
40 | result.add(root.data);
41 | inOrderRecur(root.right, result);
42 | }
43 |
44 | public ArrayList preOrder() {
45 | ArrayList result = new ArrayList();
46 | preOrderRecur(this, result);
47 | return result;
48 | }
49 |
50 | private void preOrderRecur(TreeNode root, ArrayList result) {
51 | if (root == null) {
52 | return;
53 | }
54 | result.add(root.data);
55 | preOrderRecur(root.left, result);
56 | preOrderRecur(root.right, result);
57 | }
58 |
59 | public ArrayList postOrder() {
60 | ArrayList result = new ArrayList();
61 | postOrderRecur(this, result);
62 | return result;
63 | }
64 |
65 | private void postOrderRecur(TreeNode root, ArrayList result) {
66 | if (root == null) {
67 | return;
68 | }
69 | postOrderRecur(root.left, result);
70 | postOrderRecur(root.right, result);
71 | result.add(root.data);
72 | }
73 |
74 | @SuppressWarnings("rawtypes")
75 | public static LinkedList> getNodesByLevel(TreeNode root) {
76 | // Do a BFS and print by level
77 | LinkedList> nodesByLevel = new LinkedList>();
78 |
79 | nodesByLevel.add(new LinkedList());
80 | nodesByLevel.peekLast().add(root);
81 | boolean allNull = true;
82 | while (true) {
83 | LinkedList currentLevel = nodesByLevel.peekLast();
84 | LinkedList nextLevel = new LinkedList();
85 | allNull = true;
86 | for (TreeNode node : currentLevel) {
87 | if (node == null) {
88 | nextLevel.add(null);
89 | nextLevel.add(null);
90 | continue;
91 | }
92 | nextLevel.add(node.left);
93 | nextLevel.add(node.right);
94 | if (node.left != null || node.right != null) {
95 | allNull = false;
96 | }
97 | }
98 | if (allNull) {
99 | break;
100 | }
101 | nodesByLevel.add(nextLevel);
102 | }
103 | return nodesByLevel;
104 | }
105 |
106 | @SuppressWarnings("rawtypes")
107 | public static void beautifulPrint(TreeNode root) {
108 | String intervalString = " ";
109 | String nullString = ".";
110 | LinkedList> nodesByLevel = getNodesByLevel(root);
111 | StringBuilder sb = new StringBuilder();
112 | int padding = 0;
113 | int interval = 1;
114 | while (nodesByLevel.size() != 0) {
115 | LinkedList currentLevel = nodesByLevel.pollLast();
116 | StringBuilder levelsb = new StringBuilder();
117 | for (int i = 0; i < padding; i++) {
118 | levelsb.append(intervalString);
119 | }
120 | for (TreeNode node : currentLevel) {
121 | if (node == null) {
122 | levelsb.append(nullString);
123 | } else {
124 | levelsb.append(node.data);
125 | }
126 | for (int i = 0; i < interval; i++) {
127 | levelsb.append(intervalString);
128 | }
129 | }
130 | levelsb.append("\n");
131 | sb.insert(0, levelsb);
132 | padding = padding * 2 + 1;
133 | interval = interval * 2 + 1;
134 | }
135 | System.out.println(sb.toString());
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/chapter09/Trie.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import java.util.*;
4 |
5 | public class Trie {
6 |
7 | public static void main(String[] args)
8 | {
9 | Trie t1 = new Trie(1);
10 | Trie t2 = new Trie(2);
11 | HashSet> set = new HashSet>();
12 | set.add(t1);
13 | set.add(t2);
14 | Util.Utility.print(set);
15 | }
16 |
17 | T key;
18 | HashMap> children;
19 |
20 | public Trie(T key) {
21 | this.key = key;
22 | children = new HashMap>();
23 | }
24 |
25 | public int hashCode() {
26 | return key.hashCode();
27 | }
28 |
29 | public boolean equals(Object obj) {
30 | if (this == obj)
31 | return true;
32 | if (obj == null || this.getClass() != obj.getClass()) {
33 | return false;
34 | }
35 | return this.hashCode() == obj.hashCode();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/chapter09/question0901.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0901 {
4 |
5 | public static void main(String[] args) {
6 |
7 | }
8 |
9 | public static int isBalanced(TreeNode root) {
10 | if (root == null) {
11 | return 0;
12 | }
13 | int leftResult = isBalanced(root.left);
14 | int rightResult = isBalanced(root.right);
15 |
16 | if (leftResult == -1 || rightResult == -1) {
17 | return -1;
18 | }
19 | if (leftResult != rightResult) {
20 | return -1;
21 | }
22 | return leftResult + 1;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/chapter09/question0902.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0902 {
4 |
5 | public static Result getKBalanced(TreeNode root, int k) {
6 | if (root == null) {
7 | return new Result(0, null);
8 | }
9 | Result leftResult = getKBalanced(root.left, k);
10 | if (leftResult.n != null) {
11 | return leftResult;
12 | }
13 | Result rightResult = getKBalanced(root.right, k);
14 | if (rightResult.n != null) {
15 | return rightResult;
16 | }
17 | if (Math.abs(rightResult.size - leftResult.size) > k) {
18 | return new Result(0, root);
19 | }
20 | return null;
21 | }
22 |
23 | public static class Result {
24 | int size;
25 | TreeNode n;
26 |
27 | Result(int size, TreeNode n) {
28 | this.size = size;
29 | this.n = n;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/chapter09/question0903.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0903 {
4 |
5 | public static boolean isSymmetric(TreeNode root) {
6 | if (root == null)
7 | return true;
8 | return isSymmetric(root.left, root.right);
9 | }
10 |
11 | public static boolean isSymmetric(TreeNode left,
12 | TreeNode right) {
13 | if (left == null && right == null) {
14 | return true;
15 | }
16 | if (left.data != right.data) {
17 | return false;
18 | }
19 | return isSymmetric(left.left, right.right)
20 | && isSymmetric(left.right, right.left);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/chapter09/question0904.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0904 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter09/question0905.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0905 {
4 |
5 | public static void main(String[] args) {
6 | TreeNode node = new TreeNode(2);
7 | node.left = new TreeNode(1);
8 | node.right = new TreeNode(3);
9 | node.left.parent = node;
10 | node.right.parent = node;
11 | postorder(node);
12 | }
13 |
14 | @SuppressWarnings({ "rawtypes", "unchecked" })
15 | public static void inorder(TreeNode n) {
16 | n.parent = null;
17 | TreeNode current = n;
18 | TreeNode prev = null;
19 | while (current != null) {
20 | TreeNode next = null;
21 | if (prev == null || prev == current.parent) {
22 | if (current.left == null) {
23 | System.out.println(current.data);
24 | if (current.right == null)
25 | next = current.parent;
26 | else
27 | next = current.right;
28 | } else {
29 | next = current.left;
30 | }
31 | } else if (prev == current.left) {
32 | System.out.println(current.data);
33 | if (current.right == null)
34 | next = current.parent;
35 | else
36 | next = current.right;
37 | } else {
38 | next = current.parent;
39 | }
40 | prev = current;
41 | current = next;
42 | }
43 | }
44 |
45 | // Not tested
46 | @SuppressWarnings({ "rawtypes", "unchecked" })
47 | public static void preorder(TreeNode n) {
48 | n.parent = null;
49 | TreeNode current = n;
50 | TreeNode prev = null;
51 | while (current != null) {
52 | TreeNode next = null;
53 | if (prev == null || prev == current.parent) {
54 | System.out.println(current.data);
55 | if (current.left != null) {
56 | next = current.left;
57 | } else if (current.right != null) {
58 | next = current.right;
59 | } else
60 | next = current.parent;
61 | } else if (prev == current.left) {
62 | if (current.right != null)
63 | next = current.right;
64 | else {
65 | next = current.parent;
66 | }
67 | } else if (prev == current.right) {
68 | next = current.parent;
69 | }
70 | prev = current;
71 | current = next;
72 | }
73 | }
74 |
75 | // Not tested
76 | @SuppressWarnings({ "rawtypes", "unchecked" })
77 | public static void postorder(TreeNode root) {
78 | root.parent = null;
79 | TreeNode prev = null;
80 | TreeNode current = root;
81 | while (current != null) {
82 | TreeNode next = null;
83 | if (prev == null || prev == current.parent) {
84 | if (current.left == null) {
85 | if (current.right == null) {
86 | System.out.println(current.data);
87 | next = current.parent;
88 | } else {
89 | next = current.right;
90 | }
91 | } else {
92 | next = current.left;
93 | }
94 | } else if (prev == current.left) {
95 | if (current.right == null) {
96 | System.out.println(current.data);
97 | next = current.parent;
98 | } else {
99 | next = current.right;
100 | }
101 | } else if (prev == current.right) {
102 | System.out.println(current.data);
103 | next = current.parent;
104 | }
105 | prev = current;
106 | current = next;
107 | }
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/src/chapter09/question0906.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0906 {
4 |
5 | // Off-by-one is not properly handled
6 | public static SizedTreeNode getNth(SizedTreeNode root,
7 | int n) {
8 | // Not possible
9 | if (root.size < n) {
10 | return null;
11 | }
12 | int leftSize = 0;
13 | if (root.left != null) {
14 | leftSize = root.left.size;
15 | }
16 | if (leftSize > n) {
17 | return getNth(root.left, n);
18 | }
19 | if (leftSize < n) {
20 | return getNth(root.right, n - leftSize);
21 | }
22 | return root;
23 |
24 | }
25 |
26 | public class SizedTreeNode {
27 | public SizedTreeNode left;
28 | public SizedTreeNode right;
29 | public SizedTreeNode parent;
30 | public T data;
31 | public int size;
32 |
33 | public SizedTreeNode(T n) {
34 | this.data = n;
35 | left = null;
36 | right = null;
37 | parent = null;
38 | size = 0;
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/chapter09/question0907.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0907 {
4 |
5 | public static void main(String[] args) {
6 | // String[] inorder = new String[]{"B","A","D","C","E"};
7 | // String[] preorder = new String[]{"A","B","C","D","E"};
8 | String[] inorder = new String[] { "F", "B", "A", "E", "H", "C", "D",
9 | "I", "G" };
10 | String[] preorder = new String[] { "H", "B", "F", "E", "A", "C", "D",
11 | "G", "I" };
12 | TreeNode root = reconstructTree(inorder, preorder, 0,
13 | inorder.length, 0, preorder.length);
14 | Util.Utility.print(root.inOrder());
15 |
16 | }
17 |
18 | public static TreeNode reconstructTree(String[] inorder,
19 | String[] preorder, int inStart, int inEnd, int preStart, int preEnd) {
20 | if (inStart - inEnd != preStart - preEnd) {
21 | System.out.println("Wrong answer!");
22 | }
23 | if (inEnd - inStart <= 0) {
24 | return null;
25 | }
26 | String rootKey = preorder[preStart];
27 | TreeNode root = new TreeNode(rootKey);
28 | int rootInorderIndex = search(inorder, rootKey, inStart, inEnd);
29 | int leftSize = rootInorderIndex - inStart;// start is inclusive
30 | int rightSize = inEnd - rootInorderIndex - 1; // end is exclusive
31 | root.left = reconstructTree(inorder, preorder, inStart,
32 | rootInorderIndex, preStart + 1, preStart + 1 + leftSize);
33 | root.right = reconstructTree(inorder, preorder, rootInorderIndex + 1,
34 | inEnd, preStart + 1 + leftSize, preStart + 1 + leftSize
35 | + rightSize);
36 | return root;
37 | }
38 |
39 | public static int search(String[] a, String s, int start, int end) {
40 | for (int i = start; i < end; i++) {
41 | if (a[i].equals(s)) {
42 | return i;
43 | }
44 | }
45 | return -1;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/chapter09/question0908.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import java.util.Stack;
4 |
5 | public class question0908 {
6 | public static void main(String[] args) {
7 | String[] preorder = new String[] { "H", "B", "F", "null", "null", "E",
8 | "A", "null", "null", "null", "C", "null", "D", "null", "G",
9 | "I", "null", "null", "null" };
10 | Util.Utility.print(reconstructTree(preorder).inOrder());
11 | }
12 |
13 | public static TreeNode reconstructTree(String[] preorder) {
14 | Stack> stack = new Stack>();
15 | TreeNode root = null;
16 | for (int i = preorder.length - 1; i >= 0; i--) {
17 | if (preorder[i].equals("null")) {
18 | stack.push(null);
19 | } else {
20 | root = new TreeNode(preorder[i]);
21 | root.left = stack.pop();
22 | root.right = stack.pop();
23 | stack.push(root);
24 | }
25 | }
26 | return root;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/chapter09/question0909.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import java.util.*;
4 |
5 | public class question0909 {
6 |
7 | public static void main(String[] args) {
8 | String[] preorder = new String[] { "H", "B", "F", "null", "null", "E",
9 | "A", "null", "null", "null", "C", "null", "D", "null", "G",
10 | "I", "null", "null", "null" };
11 | @SuppressWarnings("rawtypes")
12 | TreeNode root = question0908.reconstructTree(preorder);
13 | TreeNode.beautifulPrint(root);
14 | Util.Utility.print(getLeaves(root));
15 | }
16 |
17 | @SuppressWarnings("rawtypes")
18 | public static ArrayList getLeaves(TreeNode root) {
19 | LinkedList queue = new LinkedList();
20 | queue.add(root);
21 | ArrayList result = new ArrayList();
22 | while (queue.size() != 0) {
23 | TreeNode current = queue.pollFirst();
24 | if (current.left == null && current.right == null) {
25 | result.add(current);
26 | continue;
27 | }
28 | if (current.left != null) {
29 | queue.add(current.left);
30 | }
31 | if (current.right != null) {
32 | queue.add(current.right);
33 | }
34 | }
35 | return result;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/chapter09/question0910.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import java.util.*;
4 |
5 | @SuppressWarnings("rawtypes")
6 | public class question0910 {
7 |
8 | // Combine the getLeaves function in question0909 with the two functions in
9 | // this class.
10 |
11 | public static ArrayList getLeftExterior(TreeNode root) {
12 | ArrayList result = new ArrayList();
13 | while (root.left != null || root.right != null) {
14 | result.add(root);
15 | if (root.left != null) {
16 | root = root.left;
17 | } else {
18 | root = root.right;
19 | }
20 | }
21 | return result;
22 | }
23 |
24 | public static ArrayList getRightExterior(TreeNode root) {
25 | ArrayList result = new ArrayList();
26 | while (root.right != null || root.left != null) {
27 | result.add(root);
28 | if (root.right != null) {
29 | root = root.right;
30 | } else {
31 | root = root.left;
32 | }
33 | }
34 | return result;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/chapter09/question0911.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | @SuppressWarnings("rawtypes")
4 | public class question0911 {
5 |
6 | public static class MetaNode {
7 | public TreeNode treeNode;
8 | public boolean isLCA;
9 |
10 | public MetaNode(T n) {
11 | if (n == null) {
12 | this.treeNode = null;
13 | } else {
14 | this.treeNode = new TreeNode(n);
15 | }
16 | isLCA = false;
17 | }
18 |
19 | public MetaNode(T n, boolean isLCA) {
20 | this(n);
21 | this.isLCA = isLCA;
22 | }
23 | }
24 |
25 | @SuppressWarnings("unchecked")
26 | public static MetaNode getLCA(TreeNode a, TreeNode b, TreeNode root) {
27 | if (root == null) {
28 | return new MetaNode(null);
29 | }
30 |
31 | boolean foundA = false;
32 | boolean foundB = false;
33 |
34 | if (root.left != null) {
35 | MetaNode leftResult = getLCA(a, b, root.left);
36 | if (leftResult.isLCA) {
37 | return leftResult;
38 | }
39 | if (leftResult.treeNode == a) {
40 | foundA = true;
41 | } else if (leftResult.treeNode == b) {
42 | foundB = true;
43 | }
44 | }
45 |
46 | if (root.right != null) {
47 | MetaNode rightResult = getLCA(a, b, root.right);
48 | if (rightResult.isLCA) {
49 | return rightResult;
50 | }
51 | if (rightResult.treeNode == a) {
52 | foundA = true;
53 | } else if (rightResult.treeNode == b) {
54 | foundB = true;
55 | }
56 | }
57 |
58 | if (root == a) {
59 | foundA = true;
60 | } else if (root == b) {
61 | foundB = true;
62 | }
63 |
64 | if (foundA & foundB) {
65 | return new MetaNode(root, true);
66 | }
67 |
68 | if (foundA) {
69 | return new MetaNode(a);
70 | } else if (foundB) {
71 | return new MetaNode(b);
72 | }
73 |
74 | return new MetaNode(null);
75 |
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/chapter09/question0912.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0912 {
4 |
5 | @SuppressWarnings("rawtypes")
6 | public static TreeNode getCommonAncestor(TreeNode n1, TreeNode n2,
7 | TreeNode root) {
8 | int d1 = getDepth(n1);
9 | int d2 = getDepth(n2);
10 | if (d1 > d2) {
11 | n1 = moveUp(n1, d1 - d2);
12 | } else if (d2 > d1) {
13 | n2 = moveUp(n2, d2 - d1);
14 | }
15 | while (n1 != null && n2 != null) {
16 | if (n1 == n2)
17 | return n1;
18 | n1 = n1.parent;
19 | n2 = n2.parent;
20 | }
21 | return null;
22 | }
23 |
24 | @SuppressWarnings("rawtypes")
25 | public static TreeNode moveUp(TreeNode n, int levels) {
26 | for (int i = 0; i < levels; i++)
27 | n = n.parent;
28 | return n;
29 | }
30 |
31 | @SuppressWarnings("rawtypes")
32 | public static int getDepth(TreeNode n) {
33 | int count = 0;
34 | while (n.parent != null) {
35 | n = n.parent;
36 | count++;
37 | }
38 | return count;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/chapter09/question0913.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | public class question0913 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter09/question0914.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import chapter09.Trie;
4 |
5 | public class question0914 {
6 |
7 | public static void main(String[] args) {
8 | String[] words = new String[] { "dog", "be", "cat" };
9 | System.out.println(getShortestPrefix(buildTrie(words), "cat"));
10 | }
11 |
12 | public static Trie buildTrie(String[] words) {
13 | Trie root = new Trie(' ');
14 | for (int i = 0; i < words.length; i++) {
15 | Trie temp = root;
16 | String word = words[i];
17 | for (int j = 0; j < words[i].length(); j++) {
18 | Trie existing = temp.children.get(word.charAt(j));
19 | if (existing == null) {
20 | existing = new Trie(word.charAt(j));
21 | temp.children.put(word.charAt(j), existing);
22 | }
23 | temp = existing;
24 | }
25 | }
26 | return root;
27 | }
28 |
29 | public static String getShortestPrefix(Trie trie, String word) {
30 | for (int i = 0; i < word.length(); i++) {
31 | if (!trie.children.containsKey(word.charAt(i))) {
32 | return word.substring(0, i);
33 | }
34 | trie = trie.children.get(word.charAt(i));
35 | }
36 | return word;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/chapter11/question1101.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1101 {
4 |
5 | public static void main(String[] args) {
6 | int[] a = new int[] { 2 };
7 | System.out.println(binarySearchFirstOccur(a, 2));
8 | }
9 |
10 | public static int binarySearchFirstOccur(int[] a, int n) {
11 | int p = 0;
12 | int q = a.length - 1;
13 | while (p <= q) {
14 | int m = (p + q) / 2;
15 | if (a[m] == n) {
16 | // Find the first occurance
17 | while (m > 1 && a[m - 1] == n) {
18 | m -= 1;
19 | }
20 | return m;
21 | } else if (a[m] > n) {
22 | q = m - 1;
23 | } else {
24 | p = m + 1;
25 | }
26 | }
27 | return -1;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/chapter11/question1102.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1102 {
4 |
5 | public static void main(String[] args) {
6 | int[] a = new int[] { 1, 2, 3, 4, 5 };
7 | System.out.println(findFirstLarger(a, 5));
8 | }
9 |
10 | public static int findFirstLarger(int[] a, int n) {
11 | int p = 0;
12 | int q = a.length - 1;
13 | int larger = -1;
14 | while (p <= q) {
15 | int m = (p + q) / 2;
16 | if (a[m] > n) {
17 | larger = m;
18 | q = m - 1;
19 | } else {
20 | p = m + 1;
21 | }
22 | }
23 | return larger;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/chapter11/question1103.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1103 {
4 |
5 | public static int searchIndexEqualValue(int[] a) {
6 | int p = 0;
7 | int q = a.length - 1;
8 | while (p <= q) {
9 | int m = (p + q) / 2;
10 | if (a[m] == m) {
11 | return m;
12 | } else if (a[m] > m) {
13 | q = m - 1;
14 | } else {
15 | p = m + 1;
16 | }
17 | }
18 | return -1;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/chapter11/question1104.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1104 {
4 | // Here we did not implement the first solution mentioned in the book,
5 | // because it is too complicated :(.
6 | // One way to solve this problem is to sort the array first and then use
7 | // the two pointers approach. It has space O(n) and time O(n), but is
8 | // significantly
9 | // easier to implement.
10 | }
11 |
--------------------------------------------------------------------------------
/src/chapter11/question1105.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1105 {
4 |
5 | public static void main(String[] args) {
6 | int[] a = new int[] { 3, 1, 2 };
7 | System.out.println(searchCyclicSorted(a));
8 | }
9 |
10 | public static int searchCyclicSorted(int[] a) {
11 | int p = 0;
12 | int q = a.length - 1;
13 | while (p < q) {
14 | int m = (p + q) / 2;
15 | if (a[m] > a[q]) {
16 | p = m + 1;
17 | } else {
18 | q = m;
19 | }
20 | }
21 | return p;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/chapter11/question1107.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | import java.util.Arrays;
4 |
5 | public class question1107 {
6 |
7 | public float completionSearch(float[] a, float S) {
8 | Arrays.sort(a);
9 |
10 | float totalSum = 0;
11 | for (int i = 0; i < a.length; i++) {
12 | totalSum += a[i];
13 | }
14 |
15 | // Or we can use a binary search, but time complexity is still O(nlogn)
16 | // because of sorting
17 | float partialSum = a[0];
18 | for (int i = 1; i < a.length; i++) {
19 | float mean = (totalSum - partialSum) / (a.length - i - 1);
20 | if (mean >= a[i] && mean <= a[i - 1]) {
21 | return mean;
22 | }
23 | partialSum += a[i];
24 | }
25 | return 0;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/chapter11/question1109.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1109 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(squareRoot((float) 0.8, (float) 0.0001));
7 |
8 | }
9 |
10 | public static float squareRoot(float n, float precision) {
11 | float p = -1;
12 | float q = -1;
13 | if (n > 1) {
14 | p = 1;
15 | q = n;
16 | } else if (n >= 0 && n <= 1) {
17 | p = 0;
18 | q = 1;
19 | } else {
20 | return -1;
21 | }
22 | while (q - p >= precision) {
23 | float m = (p + q) / 2;
24 | float square = m * m;
25 | if (Math.abs(square - n) < precision) {
26 | return m;
27 | }
28 | if (square > n) {
29 | q = m;
30 | } else {
31 | p = m;
32 | }
33 | }
34 | return p;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/chapter11/question1110.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1110 {
4 | public static void main(String[] args) {
5 | int[][] a = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
6 | Util.Utility.print(searchIn2D(a, 1));
7 | }
8 |
9 | public static int[] searchIn2D(int[][] a, int n) {
10 | int numRow = a.length;
11 | int numCol = a[0].length;
12 | int rowIndex = 0;
13 | int colIndex = numCol - 1;
14 | while (rowIndex < numRow && colIndex >= 0) {
15 | if (a[rowIndex][colIndex] == n) {
16 | return new int[] { rowIndex, colIndex };
17 | } else if (a[rowIndex][colIndex] < n) {
18 | rowIndex++;
19 | } else {
20 | colIndex--;
21 | }
22 | }
23 | return new int[] { -1, -1 };
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/chapter11/question1111.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1111 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter11/question1112.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1112 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter11/question1113.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1113 {
4 | // Refer to Selection in common
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter11/question1115.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1115 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter11/question1116.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | import java.util.Random;
4 |
5 | public class question1116 {
6 |
7 | public static void main(String[] args) {
8 | int[] a = new int[10];
9 | for (int i = 0; i < a.length; i++) {
10 | a[i] = i;
11 | }
12 | Random r = new Random();
13 | int missing = r.nextInt(a.length);
14 | int extra = r.nextInt(a.length);
15 | if (missing == extra) {
16 | System.out.println("Bad luck, try again");
17 | return;
18 | }
19 | a[missing] = extra;
20 | System.out.println(missing + " , " + extra);
21 | Util.Utility.print(findDuplicateAndMissing(a, a.length));
22 | }
23 |
24 | // 7 1
25 |
26 | public static int[] findDuplicateAndMissing(int[] a, int range) {
27 | if (a.length != range) {
28 | // throw new Exception ("Illegal parameters");
29 | return new int[] { -1, -1 };
30 | }
31 | int xor = 0;
32 | for (int i = 0; i < a.length; i++) {
33 | xor ^= a[i];
34 | xor ^= i;
35 | }
36 | // xor is the xor of the missing element m and extra element l.
37 | // find the first bit where m differs from l
38 | int diffBit = 0;
39 | while (((xor >> diffBit) & 1) == 0) {
40 | diffBit++;
41 | }
42 | // mOrL is m or l
43 | int mOrL = 0;
44 | for (int i = 0; i < a.length; i++) {
45 | if (((a[i] >> diffBit) & 1) == 1) {
46 | mOrL ^= a[i];
47 | }
48 | if (((i >> diffBit) & 1) == 1) {
49 | mOrL ^= i;
50 | }
51 | }
52 | // Then we find if mOrL is m or l
53 | for (int i = 0; i < a.length; i++) {
54 | // mOrL is l
55 | if (a[i] == mOrL) {
56 | return new int[] { mOrL ^ xor, mOrL };
57 | }
58 | }
59 | return new int[] { mOrL, mOrL ^ xor };
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/chapter11/question1118.java:
--------------------------------------------------------------------------------
1 | package chapter11;
2 |
3 | public class question1118 {
4 |
5 | public static int searchCloseArray(int[] a, int n) {
6 | int start = 0;
7 | while (start < a.length) {
8 | if (a[start] == n) {
9 | return start;
10 | }
11 | start += Math.abs(n - a[start]);
12 | }
13 | if (start >= a.length) {
14 | return -1;
15 | }
16 | return start;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/chapter12/question1203.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | import java.util.*;
4 |
5 | public class question1203 {
6 |
7 | public int findClosetDistance(int[] a) {
8 | HashMap lastSeen = new HashMap();
9 | int minDist = Integer.MAX_VALUE;
10 | for (int i = 0; i < a.length; i++) {
11 | Integer last = lastSeen.get(a[i]);
12 | if (last != null) {
13 | minDist = Math.min(minDist, i - last);
14 | }
15 | lastSeen.put(i, a[i]);
16 | }
17 | return minDist;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/chapter12/question1207.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | import java.util.Arrays;
4 |
5 | public class question1207 {
6 |
7 | public static void main(String[] args) {
8 | System.out.println(hashString("haha"));
9 | }
10 |
11 | public static String hashString(String s) {
12 | char[] c = s.toCharArray();
13 | Arrays.sort(c);
14 | return new String(c);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/chapter12/question1208.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | public class question1208 {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(canBePalindrome("asba"));
7 | }
8 |
9 | public static boolean canBePalindrome(String s) {
10 | int[] counts = new int[256];
11 | for (int i = 0; i < s.length(); i++) {
12 | counts[(int) s.charAt(i)] += 1;
13 | }
14 | int oddCount = 0;
15 | for (int i = 0; i < counts.length; i++) {
16 | if (counts[i] % 2 == 1) {
17 | oddCount++;
18 | }
19 | }
20 | if (oddCount > 1) {
21 | return false;
22 | }
23 | return true;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/chapter12/question1209.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | public class question1209 {
4 | // Not implemented
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter12/question1214.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | import java.util.*;
4 |
5 | import common.DoublyLinkedList;
6 | import common.DoublyLinkedList.DoublyLinkedListNode;
7 |
8 | public class question1214 {
9 |
10 | public static void main(String[] args) {
11 | String[] a = { "a", "b", "c", "d", "a", "c", "d" };
12 | String[] q = { "a", "d" };
13 | Util.Utility.print(subarrayCoveringSet(a, q));
14 | }
15 |
16 | public static int[] subarrayCoveringSet(String[] a, String[] q) {
17 | // Store q in a HashSet for faster access.
18 | HashSet qMatches = new HashSet();
19 | for (int i = 0; i < q.length; i++) {
20 | qMatches.add(q[i]);
21 | }
22 |
23 | DoublyLinkedList matchIndices = new DoublyLinkedList();
24 |
25 | int minStart = -1;
26 | int minEnd = -1;
27 | int minInterval = Integer.MAX_VALUE;
28 | HashMap> matchMap = new HashMap>();
29 | for (int i = 0; i < a.length; i++) {
30 | // Do nothing if the next word in a does not match anything in q
31 | if (!qMatches.contains(a[i])) {
32 | continue;
33 | }
34 |
35 | // Find the last match we had and delete it
36 | DoublyLinkedListNode lastMatch = matchMap.get(a[i]);
37 | if (lastMatch != null) {
38 | matchIndices.remove(lastMatch);
39 | }
40 |
41 | // Add the new match to the doubly linked list and HashMap
42 | DoublyLinkedListNode newMatch = new DoublyLinkedListNode(
43 | i);
44 | matchMap.put(a[i], newMatch);
45 | matchIndices.append(newMatch);
46 |
47 | // Then we update the min length if a better result is found
48 | if (matchIndices.size == q.length) {
49 | int newInterval = matchIndices.tail.data
50 | - matchIndices.head.data;
51 | if (newInterval < minInterval) {
52 | minStart = matchIndices.head.data;
53 | minEnd = matchIndices.tail.data;
54 | minInterval = newInterval;
55 | }
56 | }
57 | }
58 | return new int[] { minStart, minEnd };
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/chapter12/question1215.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | import java.util.*;
4 |
5 | public class question1215 {
6 |
7 | public static void main(String[] args) {
8 | String[] a = { "d","a", "b", "c", "d", "a", "c", "d" };
9 | String[] q = { "a", "d" };
10 | Util.Utility.print(subarraySequentialCoveringSet(a, q));
11 | }
12 |
13 | // The implementation here is different from that in the book.
14 | // we use more space O(a.length) instead of O(q.length)
15 | public static int[] subarraySequentialCoveringSet(String[] a, String[] q) {
16 | HashMap indexMap = new HashMap();
17 | for (int i = 0; i < q.length; i++) {
18 | indexMap.put(q[i], i);
19 | }
20 |
21 | int[] lastSeen = new int[q.length];
22 | int[] startingIndexForShortest = new int[a.length];
23 | for(int i = 0;i newShortestLength) {
52 | shortestLength = newShortestLength;
53 | shortestStart = startingIndexForShortest[i];
54 | shortestEnd = i;
55 | }
56 | }
57 | }
58 |
59 | // update lastSeen
60 | lastSeen[wordIndex] = i;
61 | }
62 |
63 | return new int[] { shortestStart, shortestEnd };
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/chapter12/question1216.java:
--------------------------------------------------------------------------------
1 | package chapter12;
2 |
3 | public class question1216 {
4 | // See LRU in common
5 | }
6 |
--------------------------------------------------------------------------------
/src/chapter13/question1305.java:
--------------------------------------------------------------------------------
1 | package chapter13;
2 |
3 | import java.util.ArrayList;
4 |
5 | import Util.Utility;
6 |
7 | public class question1305 {
8 |
9 | public static void main(String[] args) {
10 | int[] a = new int[] { 1, 2, 2, 3, 4, 5, 6, 8 };
11 | int[] b = new int[] { 1, 3, 4, 5 };
12 | Utility.print(findDuplicates(a, b));
13 | }
14 |
15 | public static ArrayList findDuplicates(int[] a, int[] b) {
16 | int p1 = 0;
17 | int p2 = 0;
18 | ArrayList