├── .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 result = new ArrayList(); 19 | while (p1 < a.length && p2 < b.length) { 20 | if (a[p1] == b[p2]) { 21 | result.add(a[p1]); 22 | p1++; 23 | p2++; 24 | } else if (a[p1] > b[p2]) { 25 | p2++; 26 | } else { 27 | p1++; 28 | } 29 | } 30 | return result; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/chapter13/question1306.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.Arrays; 4 | 5 | public class question1306 { 6 | 7 | public boolean teamPic(int[] front, int[] back) { 8 | Arrays.sort(front); 9 | Arrays.sort(back); 10 | for (int i = 0; i < front.length; i++) { 11 | if (front[i] > back[i]) { 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/chapter13/question1307.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.*; 4 | 5 | public class question1307 { 6 | 7 | public static void main(String[] args) { 8 | Util.Utility.print(countOccurence("asfaxxasss")); 9 | } 10 | 11 | public static class Result { 12 | public char c; 13 | public int count; 14 | 15 | public Result(char c, int count) { 16 | this.c = c; 17 | this.count = count; 18 | } 19 | 20 | public String toString() { 21 | return c + "," + count; 22 | } 23 | } 24 | 25 | public static ArrayList countOccurence(String s) { 26 | char[] c = s.toCharArray(); 27 | Arrays.sort(c); 28 | Result lastResult = new Result(c[0], 1); 29 | ArrayList r = new ArrayList(); 30 | 31 | for (int i = 1; i < c.length; i++) { 32 | if (c[i] == lastResult.c) { 33 | lastResult.count += 1; 34 | } else { 35 | r.add(lastResult); 36 | lastResult = new Result(c[i], 1); 37 | } 38 | } 39 | r.add(lastResult); 40 | return r; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/chapter13/question1308.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | 6 | public class question1308 { 7 | 8 | public static void main(String[] args) { 9 | ArrayList a = new ArrayList(); 10 | a.add("a"); 11 | a.add("b"); 12 | a.add("c"); 13 | a.add("a"); 14 | Util.Utility.print(removeDuplicate(a)); 15 | } 16 | 17 | public static ArrayList removeDuplicate(ArrayList a) { 18 | HashSet result = new HashSet(); 19 | result.addAll(a); 20 | return new ArrayList(result); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/chapter13/question1309.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.*; 4 | 5 | public class question1309 { 6 | 7 | public static class Tasks { 8 | int task1; 9 | int task2; 10 | 11 | public Tasks(int task1, int task2) { 12 | this.task1 = task1; 13 | this.task2 = task2; 14 | } 15 | } 16 | 17 | public static ArrayList assignTasks(int[] a) { 18 | Arrays.sort(a); 19 | ArrayList result = new ArrayList(); 20 | for (int i = 0; i < a.length; i++) { 21 | result.add(new Tasks(a[i], a[a.length - 1 - i])); 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter13/question1310.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.Arrays; 4 | 5 | public class question1310 { 6 | 7 | public static class EndPoint implements Comparable { 8 | public int time; 9 | public boolean isStarting; 10 | 11 | public EndPoint(int time, boolean isStarting) { 12 | this.time = time; 13 | this.isStarting = isStarting; 14 | } 15 | 16 | @Override 17 | public int compareTo(EndPoint o) { 18 | int diff = this.time - o.time; 19 | if (diff != 0) { 20 | return diff; 21 | } 22 | 23 | if (isStarting ^ o.isStarting) { 24 | return isStarting == true ? 1 : -1; 25 | } 26 | return 0; 27 | } 28 | } 29 | 30 | public int getMaxOverLap(int[] startingEndPoint, int[] endingEndPoint) { 31 | if (startingEndPoint.length != endingEndPoint.length) { 32 | return -1; 33 | } 34 | EndPoint[] endPoints = new EndPoint[startingEndPoint.length 35 | + endingEndPoint.length]; 36 | int pointer = 0; 37 | int i = 0; 38 | while (pointer < endPoints.length) { 39 | endPoints[pointer] = new EndPoint(startingEndPoint[i], true); 40 | pointer++; 41 | endPoints[pointer] = new EndPoint(endingEndPoint[i], false); 42 | pointer++; 43 | i++; 44 | } 45 | Arrays.sort(endPoints); 46 | 47 | int maxCount = Integer.MIN_VALUE; 48 | int currentCount = 0; 49 | for (int j = 0; j < endPoints.length; j++) { 50 | if (endPoints[j].isStarting) { 51 | currentCount++; 52 | } else { 53 | currentCount--; 54 | } 55 | maxCount = Math.max(currentCount, maxCount); 56 | } 57 | return maxCount; 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/chapter13/question1311.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.*; 4 | 5 | // Not tested :( 6 | public class question1311 { 7 | 8 | public static class Interval { 9 | int start; 10 | int end; 11 | boolean startInclusive; 12 | boolean endInclusive; 13 | 14 | public Interval(int start, int end, boolean startInclusive, 15 | boolean endInclusive) { 16 | this.start = start; 17 | this.end = end; 18 | this.startInclusive = startInclusive; 19 | this.endInclusive = endInclusive; 20 | } 21 | } 22 | 23 | public static ArrayList unionOfIntervals( 24 | ArrayList intervals) { 25 | ArrayList union = new ArrayList(); 26 | Collections.sort(intervals, new Comparator() { 27 | 28 | @Override 29 | public int compare(Interval o1, Interval o2) { 30 | int diff = o1.start - o2.start; 31 | if (diff != 0) { 32 | return diff; 33 | } 34 | if (o1.startInclusive) { 35 | return 1; 36 | } else { 37 | return -1; 38 | } 39 | } 40 | }); 41 | Interval current = null; 42 | for (int i = 0; i < intervals.size(); i++) { 43 | if (current == null) { 44 | current = intervals.get(i); 45 | continue; 46 | } 47 | // The next interval and the current one are not connected 48 | if (intervals.get(i).start > current.end 49 | || (intervals.get(i).start == current.end 50 | && !intervals.get(i).startInclusive && !current.endInclusive)) { 51 | union.add(current); 52 | current = intervals.get(i); 53 | continue; 54 | } 55 | // Otherwise we update current to be an union of the old one and the 56 | // new interval 57 | current.end = intervals.get(i).end; 58 | current.endInclusive = intervals.get(i).endInclusive; 59 | } 60 | union.add(current); 61 | return union; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/chapter13/question1312.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.*; 4 | 5 | public class question1312 { 6 | 7 | public static void main(String[] args) { 8 | TreeSet m = new TreeSet(); 9 | HashSet toBeRemoved = new HashSet(); 10 | m.add(1); 11 | m.add(2); 12 | m.add(3); 13 | for (Integer i : m) { 14 | toBeRemoved.remove(i); 15 | } 16 | for (Integer i : toBeRemoved) { 17 | m.remove(i); 18 | } 19 | } 20 | 21 | public static class Interval implements Comparable { 22 | int start; 23 | int end; 24 | 25 | public Interval(int start, int end) { 26 | this.start = start; 27 | this.end = end; 28 | } 29 | 30 | @Override 31 | public int compareTo(Interval o) { 32 | return this.end - o.end; 33 | } 34 | } 35 | 36 | public static ArrayList coveringIntervals( 37 | ArrayList intervals) { 38 | TreeSet map = new TreeSet(intervals); 39 | ArrayList result = new ArrayList(); 40 | while (map.size() != 0) { 41 | Interval current = map.pollFirst(); 42 | HashSet toBeRemoved = new HashSet(); 43 | for (Interval i : map) { 44 | if (i.end <= current.end && i.start >= current.end) { 45 | toBeRemoved.add(i); 46 | } 47 | } 48 | for (Interval i : toBeRemoved) { 49 | map.remove(i); 50 | } 51 | result.add(current.end); 52 | } 53 | return result; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/chapter13/question1314.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import java.util.Arrays; 4 | 5 | public class question1314 { 6 | public static void main(String[] args) { 7 | int[] a = new int[] { 2, 3, 4, 3, 5, 6, 7, 3, 2, 3, 4 }; 8 | int sum = 18; 9 | System.out.println(threeSum(a, sum)); 10 | } 11 | 12 | public static boolean threeSum(int[] a, int sum) { 13 | Arrays.sort(a); 14 | for (int i = 0; i < a.length; i++) { 15 | int twoSum = sum - a[i]; 16 | int p1 = i + 1; 17 | int p2 = a.length - 1; 18 | while (p1 < p2) { 19 | int currentTwoSum = a[p1] + a[p2]; 20 | if (currentTwoSum == twoSum) { 21 | return true; 22 | } 23 | if (currentTwoSum > twoSum) { 24 | p2--; 25 | } else { 26 | p1++; 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/chapter13/question1315.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | public class question1315 { 4 | 5 | public static void main(String[] args) { 6 | int[] a = new int[] { 3, 2, 4, 5, 2, 1, 3 }; 7 | pancakeSort(a); 8 | Util.Utility.print(a); 9 | } 10 | 11 | public static void pancakeSort(int[] a) { 12 | for (int i = 0; i < a.length - 1; i++) { 13 | int maxIndex = findMax(a, a.length - i); 14 | if (maxIndex != a.length - i - 1) { 15 | flip(a, maxIndex + 1); 16 | flip(a, a.length - i); 17 | } 18 | } 19 | } 20 | 21 | public static int findMax(int[] a, int n) { 22 | if (n > a.length) { 23 | return -1; 24 | } 25 | int max = Integer.MIN_VALUE; 26 | int maxIndex = -1; 27 | for (int i = 0; i < n; i++) { 28 | if (a[i] > max) { 29 | max = a[i]; 30 | maxIndex = i; 31 | } 32 | } 33 | return maxIndex; 34 | } 35 | 36 | public static void flip(int[] a, int n) { 37 | if (n > a.length) { 38 | return; 39 | } 40 | for (int i = 0; i < n / 2; i++) { 41 | int temp = a[i]; 42 | a[i] = a[n - 1 - i]; 43 | a[n - 1 - i] = temp; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/chapter14/question1401.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1401 { 6 | public static boolean isBST(TreeNode n, int upper, int lower) { 7 | boolean leftBST = true; 8 | boolean rightBST = true; 9 | if (n.left != null) 10 | leftBST = isBST(n.left, lower, n.data); 11 | if (n.right != null) 12 | rightBST = isBST(n.right, n.data, upper); 13 | return leftBST && rightBST && n.data < upper && n.data > lower; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/chapter14/question1402.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | import chapter09.question0908; 5 | 6 | public class question1402 { 7 | 8 | @SuppressWarnings("unchecked") 9 | public static void main(String[] args) { 10 | String[] preorder = new String[] { "H", "B", "F", "null", "null", "E", 11 | "A", "null", "null", "null", "C", "null", "D", "null", "G", 12 | "I", "null", "null", "null" }; 13 | @SuppressWarnings("rawtypes") 14 | TreeNode root = question0908.reconstructTree(preorder); 15 | TreeNode.beautifulPrint(root); 16 | // Cannot be tested because parent node is not set properly 17 | System.out.println(successor(root.left.left)); 18 | } 19 | 20 | public static TreeNode successor(TreeNode n) { 21 | // First check if the node has a right child. If it does, 22 | // the successor is the left most node in the right child 23 | if (n.right != null) { 24 | TreeNode successor = n.right; 25 | while (successor.left != null) { 26 | successor = successor.left; 27 | } 28 | return successor; 29 | } 30 | 31 | // Go up the tree until cannot go up anymore or the current node is the 32 | // left child of the parent 33 | while (n.parent != null) { 34 | if (n.parent.left == n) { 35 | return n.parent; 36 | } 37 | n = n.parent; 38 | } 39 | 40 | return null; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/chapter14/question1403.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1403 { 6 | 7 | public static void main(String[] args) { 8 | TreeNode root = null; 9 | root = insert(root, new TreeNode(10)); 10 | root = insert(root, new TreeNode(12)); 11 | root = insert(root, new TreeNode(20)); 12 | root = insert(root, new TreeNode(30)); 13 | root = insert(root, new TreeNode(24)); 14 | root = insert(root, new TreeNode(7)); 15 | root = insert(root, new TreeNode(4)); 16 | root = insert(root, new TreeNode(11)); 17 | root = insert(root, new TreeNode(16)); 18 | root = insert(root, new TreeNode(17)); 19 | TreeNode.beautifulPrint(root); 20 | root = delete(root, root.right.right); 21 | TreeNode.beautifulPrint(root); 22 | root = delete(root, root.right.right); 23 | TreeNode.beautifulPrint(root); 24 | } 25 | 26 | public static TreeNode delete(TreeNode root, 27 | TreeNode n) { 28 | // First case, if n has no left child 29 | if (n.left == null) { 30 | transplant(n, n.right); 31 | if (n == root) { 32 | root = n.right; 33 | } 34 | return root; 35 | } 36 | // If n only has its left child 37 | if (n.right == null) { 38 | transplant(n, n.left); 39 | if (n == root) { 40 | root = n.left; 41 | } 42 | return root; 43 | } 44 | // If n has both children, find its succesor, which is in the right 45 | // subtree 46 | TreeNode succesor = question1402.successor(n); 47 | // When succesor is the right child of n, the successor have no left 48 | // child. 49 | if (succesor == n.right) { 50 | transplant(n, n.right); 51 | n.right.left = n.left; 52 | n.left.parent = n.right; 53 | if (n == root) { 54 | root = n.right; 55 | } 56 | return root; 57 | } 58 | // When successor is the left most child of the right child of n 59 | transplant(succesor, succesor.right); 60 | succesor.right = n.right; 61 | n.right.parent = succesor; 62 | succesor.left = n.left; 63 | n.left.parent = succesor; 64 | transplant(n, succesor); 65 | if (n == root) { 66 | root = succesor; 67 | } 68 | return root; 69 | } 70 | 71 | public static void transplant(TreeNode oldNode, 72 | TreeNode newNode) { 73 | if (newNode != null) { 74 | newNode.parent = oldNode.parent; 75 | } 76 | if (oldNode.parent != null) { 77 | if (oldNode == oldNode.parent.left) { 78 | oldNode.parent.left = newNode; 79 | } else { 80 | oldNode.parent.right = newNode; 81 | } 82 | } 83 | } 84 | 85 | public static TreeNode insert(TreeNode root, 86 | TreeNode n) { 87 | if (root == null) { 88 | return n; 89 | } 90 | TreeNode current = root; 91 | while (true) { 92 | if (current.data == n.data) { 93 | // do nothing 94 | return root; 95 | } 96 | if (current.data > n.data) { 97 | if (current.left == null) { 98 | current.left = n; 99 | n.parent = current; 100 | return root; 101 | } 102 | current = current.left; 103 | } else if (current.data < n.data) { 104 | if (current.right == null) { 105 | current.right = n; 106 | n.parent = current; 107 | return root; 108 | } 109 | current = current.right; 110 | } 111 | } 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/chapter14/question1404.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1404 { 6 | public static TreeNode search(TreeNode n, int num) { 7 | TreeNode found = null; 8 | while (n != null) { 9 | if (n.data == num) { 10 | found = n; 11 | n = n.left; 12 | } else if (n.data > num) { 13 | n = n.left; 14 | } else if (n.data < num) { 15 | n = n.right; 16 | } 17 | } 18 | return found; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/chapter14/question1405.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1405 { 6 | public static TreeNode searchGreaterK(TreeNode root, int k) { 7 | if (root == null) 8 | return null; 9 | TreeNode greater = null; 10 | boolean foundK = false; 11 | while (root != null) { 12 | if (root.data > k) { 13 | greater = root; 14 | root = root.left; 15 | } 16 | if (root.data < k) { 17 | root = root.right; 18 | } 19 | if (root.data == k) { 20 | foundK = true; 21 | root = root.left; 22 | } 23 | } 24 | if (foundK) 25 | return greater; 26 | return null; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/chapter14/question1406.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1406 { 6 | 7 | // This solution is different from that one in the book. 8 | public static boolean searchInMinBST(TreeNode root, int k) { 9 | TreeNode current = root; 10 | while (current != null) { 11 | if (k < current.data) { 12 | return false; 13 | } 14 | if (k == current.data) { 15 | return true; 16 | } 17 | if (current.right != null && current.right.data <= k) { 18 | current = current.right; 19 | } else { 20 | current = current.left; 21 | } 22 | } 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/chapter14/question1407.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1407 { 6 | public static TreeNode buildBalancedBST(int[] a, int p, int q) { 7 | if (p > q) 8 | return null; 9 | int middle = q + (p - q) / 2; 10 | TreeNode n = new TreeNode(a[middle]); 11 | TreeNode left = buildBalancedBST(a, p, middle - 1); 12 | TreeNode right = buildBalancedBST(a, middle + 1, q); 13 | n.left = left; 14 | n.right = right; 15 | return n; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/chapter14/question1408.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | import common.DoublyLinkedList; 5 | import common.DoublyLinkedList.*; 6 | 7 | public class question1408 { 8 | 9 | public static void main(String[] args) { 10 | DoublyLinkedList list = new DoublyLinkedList(); 11 | list.append(1); 12 | list.append(2); 13 | list.append(3); 14 | list.append(4); 15 | list.append(5); 16 | TreeNode root = BSTfromLinkedList(new NodeReference( 17 | list.head), 0, list.size); 18 | TreeNode.beautifulPrint(root); 19 | } 20 | 21 | // Necessary because node = node.next is assignment, so without the ref 22 | // wrapper, the change will not be reflected on node. 23 | public static class NodeReference { 24 | public DoublyLinkedListNode node; 25 | 26 | public NodeReference(DoublyLinkedListNode node) { 27 | this.node = node; 28 | } 29 | } 30 | 31 | public static TreeNode BSTfromLinkedList( 32 | NodeReference nodeRef, int start, int end) { 33 | if (start >= end) { 34 | return null; 35 | } 36 | int m = start + ((end - start) >> 1); 37 | TreeNode left = BSTfromLinkedList(nodeRef, start, m); 38 | TreeNode current = new TreeNode(nodeRef.node.data); 39 | nodeRef.node = nodeRef.node.next; 40 | TreeNode right = BSTfromLinkedList(nodeRef, m + 1, end); 41 | current.left = left; 42 | current.right = right; 43 | if (left != null) { 44 | left.parent = current; 45 | } 46 | if (right != null) { 47 | right.parent = current; 48 | } 49 | return current; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/chapter14/question1409.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import java.util.LinkedList; 4 | 5 | import chapter09.TreeNode; 6 | import chapter14.question1403; 7 | 8 | public class question1409 { 9 | 10 | public static void main(String[] args) { 11 | TreeNode root = new TreeNode(10); 12 | root = question1403.insert(root, new TreeNode(9)); 13 | root = question1403.insert(root, new TreeNode(8)); 14 | root = question1403.insert(root, new TreeNode(7)); 15 | root = question1403.insert(root, new TreeNode(12)); 16 | root = question1403.insert(root, new TreeNode(11)); 17 | TreeNode.beautifulPrint(root); 18 | Util.Utility.print(BSTtoLinkedList(root)); 19 | } 20 | 21 | // Only wrote solution using util.LinkedList. Solution with doubly linked 22 | // list is not much different 23 | public static LinkedList BSTtoLinkedList(TreeNode root) { 24 | if (root == null) { 25 | return new LinkedList(); 26 | } 27 | 28 | LinkedList l = BSTtoLinkedList(root.left); 29 | l.add(root.data); 30 | l.addAll(BSTtoLinkedList(root.right)); 31 | return l; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/chapter14/question1411.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import java.util.*; 4 | 5 | import chapter09.TreeNode; 6 | import chapter14.question1403; 7 | 8 | public class question1411 { 9 | 10 | public static void main(String[] args) { 11 | TreeNode root = null; 12 | root = question1403.insert(root, new TreeNode(10)); 13 | root = question1403.insert(root, new TreeNode(12)); 14 | root = question1403.insert(root, new TreeNode(20)); 15 | root = question1403.insert(root, new TreeNode(30)); 16 | root = question1403.insert(root, new TreeNode(24)); 17 | root = question1403.insert(root, new TreeNode(7)); 18 | root = question1403.insert(root, new TreeNode(4)); 19 | root = question1403.insert(root, new TreeNode(11)); 20 | root = question1403.insert(root, new TreeNode(16)); 21 | root = question1403.insert(root, new TreeNode(17)); 22 | TreeNode.beautifulPrint(root); 23 | ArrayList largest = new ArrayList(); 24 | getKLargest(root, largest, 4); 25 | Util.Utility.print(largest); 26 | } 27 | 28 | public static void getKLargest(TreeNode root, 29 | ArrayList largest, int k) { 30 | if (root == null) { 31 | return; 32 | } 33 | if (largest.size() == k) { 34 | return; 35 | } 36 | getKLargest(root.right, largest, k); 37 | if (largest.size() == k) { 38 | return; 39 | } 40 | largest.add(root.data); 41 | if (largest.size() == k) { 42 | return; 43 | } 44 | getKLargest(root.left, largest, k); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/chapter14/question1412.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import java.util.ArrayList; 4 | 5 | import chapter09.TreeNode; 6 | 7 | public class question1412 { 8 | 9 | public static void main(String[] args) { 10 | TreeNode root = new TreeNode(10); 11 | root = question1403.insert(root, new TreeNode(9)); 12 | root = question1403.insert(root, new TreeNode(8)); 13 | root = question1403.insert(root, new TreeNode(7)); 14 | root = question1403.insert(root, new TreeNode(12)); 15 | root = question1403.insert(root, new TreeNode(11)); 16 | TreeNode.beautifulPrint(root); 17 | ArrayList preOrder = root.preOrder(); 18 | TreeNode reconstructed = BSTfromPreorder(preOrder, 19 | new IntReference(0), Integer.MIN_VALUE, Integer.MAX_VALUE); 20 | TreeNode.beautifulPrint(reconstructed); 21 | 22 | } 23 | 24 | public static class IntReference { 25 | Integer n; 26 | 27 | public IntReference(Integer n) { 28 | this.n = n; 29 | } 30 | } 31 | 32 | public static TreeNode BSTfromPreorder( 33 | ArrayList preorder, IntReference index, int min, int max) { 34 | if (index.n >= preorder.size()) { 35 | return null; 36 | } 37 | int value = preorder.get(index.n); 38 | // value cannot be equal to min or max because that indicates 39 | // duplication of keys in the tree 40 | // which is not allowed because otherwise the tree will not be unique 41 | if (value < min || value > max) { 42 | return null; 43 | } 44 | TreeNode root = new TreeNode(value); 45 | index.n += 1; 46 | root.left = BSTfromPreorder(preorder, index, min, value); 47 | root.right = BSTfromPreorder(preorder, index, value, max); 48 | return root; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/chapter14/question1413.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1413 { 6 | 7 | public TreeNode LCABST(TreeNode root, int s, int b) { 8 | TreeNode current = root; 9 | while (current.data < s || current.data > b) { 10 | if (current.data < s) { 11 | current = current.right; 12 | } 13 | if (current.data > b) { 14 | current = current.left; 15 | } 16 | } 17 | return current; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/chapter14/question1414.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import chapter09.TreeNode; 4 | 5 | public class question1414 { 6 | 7 | public static boolean descendantAndAncestor(TreeNode r, 8 | TreeNode s, TreeNode m) { 9 | return existenceSearch(r, m, s) || existenceSearch(s, m, r); 10 | } 11 | 12 | public static boolean existenceSearch(TreeNode top, 13 | TreeNode middle, TreeNode bottom) { 14 | boolean encountered = false; 15 | while (top != null) { 16 | if (top.data == middle.data) { 17 | encountered = true; 18 | } 19 | if (top.data == bottom.data) { 20 | break; 21 | } 22 | if (top.data > bottom.data) { 23 | top = top.left; 24 | } else { 25 | top = top.right; 26 | } 27 | } 28 | return encountered; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter14/question1417.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | import java.util.*; 4 | 5 | public class question1417 { 6 | 7 | public static void main(String[] args) throws Exception { 8 | Log l = new Log(); 9 | l.add("zz"); 10 | l.add("zz"); 11 | l.add("bb"); 12 | l.add("aa"); 13 | l.add("bb"); 14 | l.add("aa"); 15 | l.add("aa"); 16 | l.add("cc"); 17 | l.add("cc"); 18 | l.add("aa"); 19 | l.add("aa"); 20 | l.add("aa"); 21 | l.add("aa"); 22 | l.add("aa"); 23 | l.add("bb"); 24 | l.add("bb"); 25 | l.add("bb"); 26 | l.add("aa"); 27 | Util.Utility.print(l.common(3)); 28 | } 29 | 30 | public static class LogEntry implements Comparable { 31 | String timeStamp; 32 | String page; 33 | int count; 34 | 35 | public LogEntry(String page) { 36 | // Not used in code 37 | this.timeStamp = ""; 38 | this.page = page; 39 | this.count = 0; 40 | } 41 | 42 | public int compareTo(LogEntry e) { 43 | int diff = e.count - this.count; 44 | if (diff != 0) { 45 | return diff; 46 | } 47 | return page.compareTo(e.page); 48 | } 49 | 50 | public String toString() { 51 | return page; 52 | } 53 | 54 | } 55 | 56 | public static class Log { 57 | TreeSet entries; 58 | HashMap map; 59 | 60 | public Log() { 61 | entries = new TreeSet(); 62 | map = new HashMap(); 63 | } 64 | 65 | public void add(String page) { 66 | LogEntry existing = map.get(page); 67 | if (existing == null) { 68 | existing = new LogEntry(page); 69 | map.put(page, existing); 70 | } else { 71 | entries.remove(existing); 72 | } 73 | existing.count += 1; 74 | entries.add(existing); 75 | } 76 | 77 | public LogEntry[] common(int k) throws Exception { 78 | if (k > entries.size()) { 79 | throw new Exception("Cannot get that many!"); 80 | } 81 | LogEntry[] result = new LogEntry[k]; 82 | int i = 0; 83 | for (LogEntry entry : entries) { 84 | result[i] = entry; 85 | i++; 86 | if (i == k) { 87 | break; 88 | } 89 | } 90 | return result; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/chapter14/question1418.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | public class question1418 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter14/question1420.java: -------------------------------------------------------------------------------- 1 | package chapter14; 2 | 3 | public class question1420 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter15/question1502.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1502 { 4 | 5 | public static void main(String[] args) { 6 | int[] a = new int[] { 1, 3, 2, 5, 3, 4, 6, 7, 4, 2, 8 }; 7 | mergesort(a, 0, a.length - 1); 8 | Util.Utility.print(a); 9 | } 10 | 11 | public static int mergesort(int[] a, int p, int q) { 12 | if (q <= p) 13 | return 0; 14 | int m = (p + q) / 2; 15 | int inversion = 0; 16 | inversion += mergesort(a, p, m); 17 | inversion += mergesort(a, m + 1, q); 18 | inversion += merge(a, p, q, m); 19 | return inversion; 20 | } 21 | 22 | public static int merge(int[] a, int p, int q, int m) { 23 | int inversion = 0; 24 | int[] helper = new int[q - p + 1]; 25 | for (int i = p; i <= q; i++) 26 | helper[i - p] = a[i]; 27 | int r1 = p; 28 | int r2 = m + 1; 29 | int r3 = p; 30 | while (r1 <= m && r2 <= q) { 31 | if (a[r1] <= a[r2]) { 32 | a[r3] = helper[r1 - p]; 33 | r1++; 34 | } else { 35 | inversion += m - r1 + 1; 36 | a[r3] = helper[r2 - p]; 37 | r2++; 38 | } 39 | r3++; 40 | } 41 | while (r1 <= m) { 42 | a[r3] = helper[r1 - p]; 43 | r3++; 44 | r1++; 45 | } 46 | return inversion; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/chapter15/question1505.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1505 { 4 | 5 | public static int circularMaxSubarraySum(int[] a) { 6 | int lastMin = 0; 7 | int min = Integer.MAX_VALUE; 8 | int sum = 0; 9 | for (int i = 0; i < a.length; i++) { 10 | sum += a[i]; 11 | lastMin = Math.min(0, lastMin + a[i]); 12 | min = Math.min(lastMin, min); 13 | } 14 | return sum - min; 15 | } 16 | 17 | public static int maxSubarraySum(int[] a) { 18 | int max = Integer.MIN_VALUE; 19 | int lastMax = 0; 20 | for (int i = 0; i < a.length; i++) { 21 | lastMax = Math.max(0, lastMax + a[i]); 22 | max = Math.max(max, lastMax); 23 | } 24 | return max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/chapter15/question1506.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class question1506 { 7 | 8 | public static void main(String[] args) { 9 | int[] a = new int[] { 2, -1, 3, -3, 4, -4, 5, 6 }; 10 | ArrayList result = longestNondecreasingSubsequence(a); 11 | for (int i = 0; i < result.size(); i++) { 12 | System.out.println(a[result.get(i)]); 13 | } 14 | } 15 | 16 | public static ArrayList longestNondecreasingSubsequence(int[] a) { 17 | int[] last = new int[a.length]; 18 | int[] bestCount = new int[a.length]; 19 | int bestSoFar = Integer.MIN_VALUE; 20 | int bestIndex = -1; 21 | for (int i = 0; i < a.length; i++) { 22 | last[i] = -1; 23 | bestCount[i] = 0; 24 | for (int j = 0; j < i; j++) { 25 | if (a[j] <= a[i]) { 26 | if (bestCount[i] < bestCount[j]) { 27 | bestCount[i] = bestCount[j]; 28 | last[i] = j; 29 | } 30 | } 31 | } 32 | bestCount[i] = bestCount[i] + 1; 33 | if (bestCount[i] > bestSoFar) { 34 | bestSoFar = bestCount[i]; 35 | bestIndex = i; 36 | } 37 | } 38 | ArrayList result = new ArrayList(); 39 | result.add(bestIndex); 40 | int lastIndex = a[bestIndex]; 41 | while (lastIndex != -1) { 42 | result.add(lastIndex); 43 | lastIndex = last[lastIndex]; 44 | } 45 | Collections.reverse(result); 46 | return result; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/chapter15/question1508.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class question1508 { 6 | 7 | public static void main(String[] args) { 8 | int[] h = new int[] { 2, 3, 4, 5, 6, 3, 6, 73, 2, 1 }; 9 | System.out.println(largestRectangle(h)); 10 | } 11 | 12 | public static int largestRectangle(int[] h) { 13 | LinkedList forwardStack = new LinkedList(); 14 | LinkedList backwardStack = new LinkedList(); 15 | int[] leftRecWidth = new int[h.length]; 16 | int[] rightRecWidth = new int[h.length]; 17 | for (int i = 0; i < h.length; i++) { 18 | while (forwardStack.size() != 0 19 | && h[forwardStack.peekLast()] >= h[i]) { 20 | forwardStack.pollLast(); 21 | } 22 | if (forwardStack.size() == 0) { 23 | /* 24 | * When the stack is empty, there can be two cases. The first 25 | * one is that we are at the beginning of the loop, in this case 26 | * i = 0, and the width of i should also be 0. The second case 27 | * is that we are in the middle of the loop, but h[i] is smaller 28 | * than all the number in front of it, so the width should be i 29 | */ 30 | leftRecWidth[i] = i; 31 | } else { 32 | /* 33 | * Otherwise the width is the difference between the current 34 | * index and the last index whose height is smaller than the 35 | * current height 36 | */ 37 | leftRecWidth[i] = i - forwardStack.peekLast() - 1; 38 | } 39 | forwardStack.addLast(i); 40 | 41 | // Do the same thing with the backwardStack 42 | int j = h.length - i - 1; 43 | while (backwardStack.size() != 0 44 | && h[backwardStack.peekLast()] >= h[j]) { 45 | backwardStack.pollLast(); 46 | } 47 | if (backwardStack.size() == 0) { 48 | rightRecWidth[j] = i; 49 | } else { 50 | rightRecWidth[j] = backwardStack.peekLast() - j - 1; 51 | } 52 | backwardStack.addLast(j); 53 | } 54 | 55 | int max = Integer.MIN_VALUE; 56 | int maxIndex = -1; 57 | for (int i = 0; i < h.length; i++) { 58 | int newWidth = leftRecWidth[i] + rightRecWidth[i] + 1; 59 | int newArea = newWidth * h[i]; 60 | if (newArea > max) { 61 | max = newArea; 62 | maxIndex = i; 63 | } 64 | } 65 | Util.Utility.print(leftRecWidth); 66 | Util.Utility.print(rightRecWidth); 67 | System.out.println(maxIndex - leftRecWidth[maxIndex] + "," 68 | + (maxIndex + rightRecWidth[maxIndex])); 69 | return max; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/chapter15/question1509.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1509 { 4 | 5 | public static void main(String[] args) { 6 | Boolean[][] a = new Boolean[5][5]; 7 | for (int i = 0; i < a.length; i++) { 8 | for (int j = 0; j < a[0].length; j++) { 9 | if (i == 3 || j == 3) { 10 | a[i][j] = false; 11 | } else { 12 | a[i][j] = true; 13 | } 14 | } 15 | } 16 | 17 | Util.Utility.print(a); 18 | System.out.println(twoDimensionAllOne(a)); 19 | 20 | } 21 | 22 | public static int twoDimensionAllOne(Boolean[][] a) { 23 | 24 | int h = a.length; 25 | int w = a[0].length; 26 | int[][] horizontalMax = new int[h][w]; 27 | int[][] verticalMax = new int[h][w]; 28 | 29 | // Build the horizontal max. 30 | for (int i = 0; i < h; i++) { 31 | int start = 0; 32 | for (int j = 0; j < w; j++) { 33 | if (a[i][j] == false) { 34 | int max = 0; 35 | for (int k = j; k >= start; k--) { 36 | horizontalMax[i][k] = max; 37 | max++; 38 | } 39 | start = j + 1; 40 | } 41 | } 42 | if (start < w) { 43 | int max = 1; 44 | for (int k = w - 1; k >= start; k--) { 45 | horizontalMax[i][k] = max; 46 | max++; 47 | } 48 | } 49 | } 50 | 51 | // Build the vertical max 52 | for (int i = 0; i < w; i++) { 53 | int start = 0; 54 | for (int j = 0; j < h; j++) { 55 | if (a[j][i] == false) { 56 | int max = 0; 57 | for (int k = j; k >= start; k--) { 58 | verticalMax[k][i] = max; 59 | max++; 60 | } 61 | start = j + 1; 62 | } 63 | } 64 | if (start < h) { 65 | int max = 1; 66 | for (int k = h - 1; k >= start; k--) { 67 | verticalMax[k][i] = max; 68 | max++; 69 | } 70 | } 71 | } 72 | 73 | int maxArea = Integer.MIN_VALUE; 74 | 75 | // Here we calculate and record the max rectangle area 76 | for (int i = 0; i < h; i++) { 77 | for (int j = 0; j < w; j++) { 78 | if (!a[i][j]) { 79 | continue; 80 | } 81 | if (horizontalMax[i][j] * verticalMax[i][j] < maxArea) { 82 | continue; 83 | } 84 | int minWidth = Integer.MAX_VALUE; 85 | for (int k = 0; k < verticalMax[i][j]; k++) { 86 | minWidth = Math.min(minWidth, horizontalMax[i + k][j]); 87 | maxArea = Math.max(maxArea, minWidth * (k + 1)); 88 | } 89 | } 90 | } 91 | return maxArea; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/chapter15/question1511.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1511 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(levenshteinDistance("a", "b")); 7 | } 8 | 9 | public static int INSERT_COST = 1; 10 | public static int DELETE_COST = 1; 11 | public static int REPLACE_COST = 2; 12 | 13 | public static int levenshteinDistance(String a, String b) { 14 | int[][] costMap = new int[a.length() + 1][b.length() + 1]; 15 | 16 | for (int i = 0; i < costMap.length; i++) { 17 | costMap[i][0] = i * DELETE_COST; 18 | } 19 | 20 | for (int j = 0; j < costMap[0].length; j++) { 21 | costMap[0][j] = j * INSERT_COST; 22 | } 23 | 24 | for (int i = 1; i < costMap.length; i++) { 25 | for (int j = 1; j < costMap[i].length; j++) { 26 | if (a.charAt(i - 1) == b.charAt(j - 1)) { 27 | costMap[i][j] = costMap[i - 1][j - 1]; 28 | continue; 29 | } 30 | int replace = costMap[i - 1][j - 1] + REPLACE_COST; 31 | int insert = costMap[i][j - 1] + INSERT_COST; 32 | int delete = costMap[i - 1][j] + DELETE_COST; 33 | costMap[i][j] = Math.min(delete, Math.min(replace, insert)); 34 | } 35 | } 36 | return costMap[a.length()][b.length()]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/chapter15/question1512.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.*; 4 | 5 | public class question1512 { 6 | 7 | public static void main(String[] args) { 8 | HashSet hash = new HashSet(); 9 | hash.add("ha"); 10 | hash.add("tao"); 11 | System.out.println(wordBreaking("taotao", hash)); 12 | } 13 | 14 | public static boolean wordBreaking(String s, HashSet dictionary) { 15 | boolean[] possible = new boolean[s.length()]; 16 | for (int i = 0; i < possible.length; i++) { 17 | possible[i] = false; 18 | for (int j = 0; j < i; j++) { 19 | if (possible[j] 20 | && dictionary.contains(s.substring(j + 1, i + 1))) { 21 | possible[i] = true; 22 | break; 23 | } 24 | } 25 | 26 | if (!possible[i] && dictionary.contains(s.substring(0, i + 1))) { 27 | possible[i] = true; 28 | } 29 | } 30 | return possible[possible.length - 1]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/chapter15/question1513.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1513 { 4 | 5 | public static void main(String[] args) { 6 | String[] words = new String[] { "I", "have", "shit" }; 7 | System.out.println(prettyPrinting(words, 5)); 8 | } 9 | 10 | public static int prettyCost(int lineLength, int occupied) { 11 | return 1 << (lineLength - occupied); 12 | } 13 | 14 | public static int prettyPrinting(String[] words, int lineLength) { 15 | int[] costsByWords = new int[words.length]; 16 | 17 | for (int i = 0; i < costsByWords.length; i++) { 18 | if (i == 0) { 19 | costsByWords[i] = prettyCost(lineLength, words[i].length()); 20 | continue; 21 | } 22 | int min = Integer.MAX_VALUE; 23 | int index = i; 24 | int currentLength = words[index].length(); 25 | while (currentLength <= lineLength) { 26 | int previousCost = 0; 27 | if (index > 0) { 28 | previousCost = costsByWords[index - 1]; 29 | } 30 | int newCost = prettyCost(lineLength, currentLength) 31 | + previousCost; 32 | min = Math.min(min, newCost); 33 | 34 | index--; 35 | if (index < 0) { 36 | break; 37 | } 38 | currentLength += 1 + words[index].length(); 39 | } 40 | costsByWords[i] = min; 41 | } 42 | return costsByWords[words.length - 1]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/chapter15/question1514.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1514 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(combination(10, 5)); 7 | } 8 | 9 | public static int combination(int n, int k) { 10 | int[][] combination = new int[n + 1][n + 1]; 11 | for (int i = 0; i <= n; i++) { 12 | for (int j = 0; j <= i; j++) { 13 | if (j == 0 || i == j) { 14 | combination[i][j] = 1; 15 | } else { 16 | combination[i][j] = combination[i - 1][j] 17 | + combination[i - 1][j - 1]; 18 | } 19 | if (j == k && i == n) { 20 | return combination[i][j]; 21 | } 22 | } 23 | } 24 | return -1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/chapter15/question1515.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.*; 4 | 5 | public class question1515 { 6 | 7 | public static int countCombination(int k, HashSet ways) { 8 | int[] count = new int[k + 1]; 9 | count[0] = 1; 10 | for (Integer n : ways) { 11 | for (int i = n; i <= k; i++) { 12 | count[i] += count[i - n]; 13 | } 14 | } 15 | return count[k]; 16 | } 17 | 18 | public static int countPermutation(int k, HashSet ways) { 19 | int[] count = new int[k + 1]; 20 | count[0] = 1; 21 | for (int i = 0; i < k; i++) { 22 | for (Integer n : ways) { 23 | if (i >= n) { 24 | count[i] += count[i - n]; 25 | } 26 | } 27 | } 28 | return count[k]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter15/question1516.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1516 { 4 | 5 | public static void main(String[] args) { 6 | boolean[][] map = new boolean[6][6]; 7 | for (int i = 0; i < map.length; i++) { 8 | for (int j = 0; j < map[i].length; j++) { 9 | map[i][j] = true; 10 | } 11 | } 12 | System.out.println(countPath(map)); 13 | } 14 | 15 | public static int countPath(boolean[][] map) { 16 | int[] current = new int[map[0].length]; 17 | for (int i = 0; i < current.length; i++) { 18 | current[i] = 1; 19 | } 20 | // We can safely start from i=1 21 | // because current is initialized to be all 1. 22 | for (int i = 1; i < map.length; i++) { 23 | for (int j = map[i].length-1; j >= 0; j--) { 24 | // If obstacle 25 | if (!map[i][j]) { 26 | current[j] = 0; 27 | continue; 28 | } 29 | if (j == 0) { 30 | current[j] = 1; 31 | continue; 32 | } 33 | current[j] = current[j - 1] + current[j]; 34 | } 35 | } 36 | return current[current.length - 1]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/chapter15/question1517.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1517 { 4 | 5 | public static int catchFish(int[][] map) { 6 | for (int i = 0; i < map.length; i++) { 7 | for (int j = 0; j < map[i].length; j++) { 8 | int upper = i > 0 ? map[i - 1][j] : 0; 9 | int left = j > 0 ? map[i][j - 1] : 0; 10 | map[i][j] += Math.max(upper, left); 11 | } 12 | } 13 | return map[map.length][map[0].length]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/chapter15/question1518.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1518 { 4 | 5 | public static void main(String[] args) { 6 | int[] coins = new int[] { 1, 2, 1, 1 }; 7 | System.out.println(pickCoins(coins)); 8 | } 9 | 10 | public static int pickCoins(int[] coins) { 11 | int[][] best = new int[coins.length + 1][coins.length + 1]; 12 | for (int interval = 0; interval <= coins.length; interval += 2) { 13 | for (int i = 0; i < coins.length + 1 - interval; i++) { 14 | if (interval == 0) { 15 | best[i][i] = 0; 16 | continue; 17 | } 18 | best[i][i + interval] = Math.max( 19 | coins[i] 20 | + Math.min(best[i + 1][i + interval - 1], 21 | best[i + 2][i + interval]), 22 | coins[i + interval - 1] 23 | + Math.min(best[i + 1][i + interval - 1], 24 | best[i][i + interval - 2])); 25 | } 26 | } 27 | return best[0][coins.length]; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/chapter15/question1521.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.Arrays; 4 | 5 | public class question1521 { 6 | 7 | public static void main(String[] args) { 8 | int[] waitingTimes = new int[] { 3, 1, 2 }; 9 | Arrays.sort(waitingTimes); 10 | Util.Utility.print(waitingTimes); 11 | } 12 | 13 | public static int minimizeWaitingTime(int[] waitingTimes) { 14 | Arrays.sort(waitingTimes); 15 | int minWaitTime = 0; 16 | for (int i = 0; i < waitingTimes.length; i++) { 17 | minWaitTime += waitingTimes[i] * (waitingTimes.length - 1 - i); 18 | } 19 | return minWaitTime; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/chapter15/question1522.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1522 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter15/question1523.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1523 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter15/question1524.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | public class question1524 { 4 | 5 | public static void main(String[] args) { 6 | int[] a = new int[] { 1, 2, 3, 4, 5, 6 }; 7 | int serverNum = 201; 8 | System.out.println(loadBalancing(a, serverNum)); 9 | // System.out.println(willFit(1, 6, a)); 10 | } 11 | 12 | public static int loadBalancing(int[] a, int serverNum) { 13 | int totalSize = 0; 14 | for (int i = 0; i < a.length; i++) { 15 | totalSize += a[i]; 16 | } 17 | int p = 1; 18 | int q = totalSize; 19 | int bestSoFar = Integer.MAX_VALUE; 20 | while (p <= q) { 21 | int m = (p + q) / 2; 22 | boolean canFit = willFit(m, serverNum, a); 23 | if (canFit) { 24 | bestSoFar = m; 25 | q = m - 1; 26 | } else { 27 | p = m + 1; 28 | } 29 | } 30 | return bestSoFar; 31 | } 32 | 33 | public static boolean willFit(int bucketSize, int numBucket, int[] a) { 34 | int currentNumBucket = 0; 35 | int currentBucketSize = 0; 36 | for (int i = 0; i < a.length; i++) { 37 | int newBucketSize = currentBucketSize + a[i]; 38 | if (newBucketSize > bucketSize) { 39 | currentNumBucket++; 40 | if (currentNumBucket >= numBucket) { 41 | return false; 42 | } 43 | newBucketSize = a[i]; 44 | if (newBucketSize > bucketSize) { 45 | return false; 46 | } 47 | } 48 | currentBucketSize = newBucketSize; 49 | } 50 | return true; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/chapter15/question1525.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.TreeSet; 4 | 5 | public class question1525 { 6 | 7 | public static void main(String[] args) { 8 | int[] items = new int[] { 4, 3, 2, 1 }; 9 | int boxSize = 5; 10 | System.out.println(boxPacking(items, boxSize)); 11 | } 12 | 13 | public static class Box implements Comparable { 14 | int remainingSpace; 15 | int insertSequence; 16 | 17 | public Box(int remainingSpace, int insertSequence) { 18 | this.remainingSpace = remainingSpace; 19 | this.insertSequence = insertSequence; 20 | } 21 | 22 | public String toString() { 23 | return insertSequence + ":" + remainingSpace; 24 | } 25 | 26 | public int compareTo(Box b) { 27 | int diff = b.remainingSpace - remainingSpace; 28 | if (diff != 0) { 29 | return diff; 30 | } 31 | return insertSequence - b.insertSequence; 32 | } 33 | } 34 | 35 | public static int boxPacking(int[] items, int boxSize) { 36 | TreeSet boxes = new TreeSet(); 37 | int boxCount = 0; 38 | boxes.add(new Box(boxSize, boxCount)); 39 | boxCount++; 40 | for (int i = 0; i < items.length; i++) { 41 | int currentBestRemaining = boxes.first().remainingSpace; 42 | if (currentBestRemaining < items[i]) { 43 | boxes.add(new Box(boxSize - items[i], boxCount)); 44 | boxCount++; 45 | } else { 46 | Box current = boxes.pollFirst(); 47 | current.remainingSpace -= items[i]; 48 | boxes.add(current); 49 | } 50 | } 51 | return boxes.size(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/chapter15/question1526.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.*; 4 | 5 | public class question1526 { 6 | 7 | public static void main(String[] args) { 8 | final HashMap frequencies = new HashMap(); 9 | ArrayList chars = new ArrayList(); 10 | Random r = new Random(); 11 | for (int i = (int) 'A'; i <= (int) 'z'; i++) { 12 | frequencies.put((char) i, (double) r.nextInt(100) / 100); 13 | chars.add((char) i); 14 | } 15 | HashMap code = huffmanCode(frequencies); 16 | Collections.sort(chars, new Comparator() { 17 | 18 | @Override 19 | public int compare(Character o1, Character o2) { 20 | return (int) Math.signum(frequencies.get(o1) 21 | - frequencies.get(o2)); 22 | } 23 | }); 24 | for (Character c : chars) { 25 | System.out.println(c + " : " + frequencies.get(c) + " " 26 | + code.get(c)); 27 | } 28 | } 29 | 30 | public static class HuffmanNode implements Comparable { 31 | double frequency; 32 | char c; 33 | 34 | public HuffmanNode leftNode; 35 | public HuffmanNode rightNode; 36 | 37 | public HuffmanNode(double frequency, char c) { 38 | this.frequency = frequency; 39 | this.c = c; 40 | this.leftNode = null; 41 | this.rightNode = null; 42 | } 43 | 44 | public static HuffmanNode merge(HuffmanNode n1, HuffmanNode n2) { 45 | HuffmanNode newOne = new HuffmanNode(n1.frequency + n2.frequency, 46 | ' '); 47 | newOne.leftNode = n1; 48 | newOne.rightNode = n2; 49 | return newOne; 50 | } 51 | 52 | public int compareTo(HuffmanNode n) { 53 | double diff = frequency - n.frequency; 54 | if (diff != 0) { 55 | return (int) Math.signum(diff); 56 | } 57 | // Just so that nodes with the same frequencies will not be thought 58 | // to be the same 59 | return hashCode() - n.hashCode(); 60 | } 61 | } 62 | 63 | public static HashMap huffmanCode( 64 | HashMap frequencies) { 65 | TreeSet nodes = new TreeSet(); 66 | for (Map.Entry pair : frequencies.entrySet()) { 67 | nodes.add(new HuffmanNode(pair.getValue(), pair.getKey())); 68 | } 69 | 70 | while (nodes.size() != 1) { 71 | HuffmanNode n1 = nodes.pollFirst(); 72 | HuffmanNode n2 = nodes.pollFirst(); 73 | nodes.add(HuffmanNode.merge(n1, n2)); 74 | } 75 | 76 | HashMap code = new HashMap(); 77 | LinkedList sequence = new LinkedList(); 78 | GenerateHuffmanCode(nodes.first(), sequence, true, code); 79 | return code; 80 | } 81 | 82 | public static void GenerateHuffmanCode(HuffmanNode root, 83 | LinkedList sequence, boolean isLeft, 84 | HashMap result) { 85 | if (isLeft) { 86 | sequence.addLast("1"); 87 | } else { 88 | sequence.addLast("0"); 89 | } 90 | 91 | if (root.leftNode == null && root.rightNode == null) { 92 | result.put(root.c, linkedListToString(sequence)); 93 | } else { 94 | GenerateHuffmanCode(root.leftNode, sequence, true, result); 95 | GenerateHuffmanCode(root.rightNode, sequence, false, result); 96 | } 97 | sequence.removeLast(); 98 | return; 99 | } 100 | 101 | public static String linkedListToString(LinkedList l) { 102 | StringBuilder sb = new StringBuilder(); 103 | for (String s : l) { 104 | sb.append(s); 105 | } 106 | return sb.toString(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/chapter15/question1527.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.*; 4 | 5 | public class question1527 { 6 | 7 | public static void main(String[] args) { 8 | Node root = new Node(3); 9 | Node c1 = new Node(1); 10 | Node c2 = new Node(4); 11 | root.children.add(c1); 12 | root.children.add(c2); 13 | reweight(root); 14 | System.out.println(c1); 15 | } 16 | 17 | public static class Node { 18 | HashSet children; 19 | int weight; 20 | 21 | public Node(int weight) { 22 | this.weight = weight; 23 | children = new HashSet(); 24 | } 25 | 26 | public String toString() { 27 | return String.valueOf(weight); 28 | } 29 | } 30 | 31 | public static void reweight(Node root) { 32 | int goal = getHighestPath(root, 0); 33 | HashMap weightDiff = new HashMap(); 34 | calculateWeightDiff(root, 0, goal, weightDiff); 35 | } 36 | 37 | public static int calculateWeightDiff(Node root, int lastWeights, int goal, 38 | HashMap weightDiff) { 39 | int diff = Integer.MAX_VALUE; 40 | if (root.children.size() == 0) { 41 | diff = goal - lastWeights - root.weight; 42 | } else { 43 | for (Node child : root.children) { 44 | int childWeight = calculateWeightDiff(child, lastWeights 45 | + root.weight, goal, weightDiff); 46 | diff = Math.min(childWeight, diff); 47 | } 48 | // Then we update the weight in the child 49 | for (Node child : root.children) { 50 | child.weight += weightDiff.get(child) - diff; 51 | } 52 | } 53 | weightDiff.put(root, diff); 54 | return diff; 55 | } 56 | 57 | public static int getHighestPath(Node root, int lastWeights) { 58 | if (root.children.size() == 0) { 59 | return lastWeights + root.weight; 60 | } 61 | int currentHighest = Integer.MIN_VALUE; 62 | for (Node child : root.children) { 63 | int newHighest = getHighestPath(child, lastWeights + root.weight); 64 | currentHighest = Math.max(newHighest, currentHighest); 65 | } 66 | return currentHighest; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/chapter15/question1528.java: -------------------------------------------------------------------------------- 1 | package chapter15; 2 | 3 | import java.util.*; 4 | 5 | public class question1528 { 6 | 7 | public static void main(String[] args) { 8 | 9 | } 10 | 11 | public static class Person { 12 | HashSet connecting; 13 | HashSet connected; 14 | String name; 15 | 16 | public Person(String name) { 17 | this.name = name; 18 | connecting = new HashSet(); 19 | connected = new HashSet(); 20 | } 21 | 22 | public int hashCode() { 23 | return name.hashCode(); 24 | } 25 | 26 | public boolean equal(Object o) { 27 | if (o == null) { 28 | return false; 29 | } 30 | if (this == o) { 31 | return true; 32 | } 33 | if (!(o instanceof Person)) { 34 | return false; 35 | } 36 | return o.hashCode() == hashCode(); 37 | } 38 | } 39 | 40 | public HashMap planParty(HashMap connections) { 41 | HashMap people = new HashMap(); 42 | // Build the graph 43 | for (Map.Entry connection : connections.entrySet()) { 44 | Person connecting = people.get(connection.getKey()); 45 | if (connecting == null) { 46 | connecting = new Person(connection.getKey()); 47 | people.put(connection.getKey(), connecting); 48 | } 49 | Person connected = people.get(connection.getValue()); 50 | if (connected == null) { 51 | connected = new Person(connection.getValue()); 52 | people.put(connection.getValue(), connecting); 53 | } 54 | connecting.connecting.add(connected); 55 | connected.connected.add(connected); 56 | } 57 | 58 | while (true) { 59 | Person toBeRemoved = null; 60 | for (Map.Entry person : people.entrySet()) { 61 | if (person.getValue().connecting.size() < 3 62 | || people.size() - person.getValue().connecting.size() < 3) { 63 | toBeRemoved = person.getValue(); 64 | break; 65 | } 66 | } 67 | 68 | if (toBeRemoved == null) { 69 | return people; 70 | } 71 | for (Person p : toBeRemoved.connected) { 72 | p.connecting.remove(toBeRemoved); 73 | } 74 | people.remove(toBeRemoved.name); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/chapter16/GraphNode.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class GraphNode { 6 | T data; 7 | HashMap, Integer> edges; 8 | public GraphNode(T data) 9 | { 10 | this.data = data; 11 | edges = new HashMap, Integer>(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/chapter16/question1601.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | public class question1601 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter16/question1602.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class question1602 { 6 | 7 | 8 | public static void main(String[] args) 9 | { 10 | HashSet dict = new HashSet(); 11 | dict.add("aa"); 12 | dict.add("ab"); 13 | dict.add("bb"); 14 | System.out.println(stringTransformation("aa", "bb", dict)); 15 | } 16 | 17 | // Tracking the length of the sequence requires an extra parameter attached to each string in the queue. 18 | // And we are not doing that here. 19 | public static boolean stringTransformation(String s, String d, Set dictionary) 20 | { 21 | HashSet checked = new HashSet(); 22 | LinkedList queue = new LinkedList(); 23 | queue.add(s); 24 | checked.add(s); 25 | while(queue.size() != 0) 26 | { 27 | char[] current = queue.pollFirst().toCharArray(); 28 | for(int i = 0;i queue = new LinkedList(); 10 | while (queue.size() != 0) { 11 | Integer current = queue.pollFirst(); 12 | for (int i = 0; i < matrix[current].length; i++) { 13 | if (!matrix[current][i]) { 14 | continue; 15 | } 16 | if (distance[i] == 0) { 17 | queue.add(i); 18 | distance[i] = distance[current] + 1; 19 | } else if (distance[current] == distance[i]) { 20 | return false; 21 | } 22 | } 23 | } 24 | return true; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/chapter16/question1604.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class question1604 { 6 | 7 | public static void main(String[] args) 8 | { 9 | GraphNode node1 = new GraphNode(1); 10 | GraphNode node2 = new GraphNode(2); 11 | GraphNode node3 = new GraphNode(3); 12 | GraphNode node4 = new GraphNode(4); 13 | GraphNode node5 = new GraphNode(5); 14 | GraphNode node6 = new GraphNode(6); 15 | 16 | node1.edges.put(node2,0); 17 | node2.edges.put(node3,0); 18 | node3.edges.put(node1,0); 19 | node3.edges.put(node4,0); 20 | HashMap, Integer> discovery = new HashMap, Integer> (); 21 | HashMap, Integer> min = new HashMap, Integer> (); 22 | discovery.put(node1,0); 23 | min.put(node1,Integer.MAX_VALUE); 24 | 25 | System.out.println(isTwoAllConnected(node1,discovery, min)); 26 | 27 | } 28 | 29 | public static boolean isTwoAllConnected(GraphNode node, HashMap, Integer> discoveryTime, HashMap, Integer> minDescendantsDiscovery) 30 | { 31 | int discovery = discoveryTime.get(node); 32 | int min = minDescendantsDiscovery.get(node); 33 | for(GraphNode child: node.edges.keySet()) 34 | { 35 | if(discoveryTime.get(child) == null) 36 | { 37 | discoveryTime.put(child, discovery+1); 38 | minDescendantsDiscovery.put(child, Integer.MAX_VALUE); 39 | if(!isTwoAllConnected(child, discoveryTime,minDescendantsDiscovery)) 40 | { 41 | return false; 42 | } 43 | int childMin = Math.min(discovery+1, minDescendantsDiscovery.get(child)); 44 | if(min > childMin) 45 | { 46 | min = childMin; 47 | minDescendantsDiscovery.put(node, min); 48 | } 49 | } 50 | else 51 | { 52 | int newMin = Math.min(discoveryTime.get(child),min); 53 | newMin = Math.min(minDescendantsDiscovery.get(child),newMin); 54 | if(newMin != min) 55 | { 56 | min = newMin; 57 | minDescendantsDiscovery.put(node, min); 58 | } 59 | } 60 | } 61 | if(min > discovery) 62 | { 63 | return false; 64 | } 65 | return true; 66 | } 67 | 68 | public static boolean isTwoExistConnected(GraphNode node) 69 | { 70 | return hasCycle(node,new HashSet>(), new HashSet>()); 71 | } 72 | 73 | public static boolean hasCycle(GraphNode node, HashSet> checked, HashSet> checking) 74 | { 75 | // Existence of a loop 76 | if(checking.contains(node)) 77 | { 78 | return true; 79 | } 80 | // Existence of a cross edge 81 | if(checked.contains(node)) 82 | { 83 | return false; 84 | } 85 | 86 | checking.add(node); 87 | for(GraphNode connection : node.edges.keySet()) 88 | { 89 | if(hasCycle(connection, checked, checking)) 90 | { 91 | return true; 92 | } 93 | } 94 | checking.remove(node); 95 | checked.add(node); 96 | return false; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/chapter16/question1605.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | public class question1605 { 4 | //Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter16/question1606.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class question1606 { 6 | 7 | public static void main(String[] args) { 8 | ArrayList equal = new ArrayList(); 9 | ArrayList notEqual = new ArrayList(); 10 | equal.add(new Constraint(1, 2)); 11 | equal.add(new Constraint(2, 3)); 12 | equal.add(new Constraint(3, 4)); 13 | equal.add(new Constraint(1, 3)); 14 | equal.add(new Constraint(2, 4)); 15 | equal.add(new Constraint(1, 5)); 16 | 17 | notEqual.add(new Constraint(1, 5)); 18 | System.out.println(isPossible(equal, notEqual)); 19 | 20 | } 21 | 22 | public static class Constraint { 23 | int a; 24 | int b; 25 | 26 | public Constraint(int a, int b) { 27 | this.a = a; 28 | this.b = b; 29 | } 30 | } 31 | 32 | public static boolean isPossible(ArrayList equal, 33 | ArrayList notEqual) { 34 | // First build the groups 35 | HashMap> group = new HashMap>(); 36 | for (int i = 0; i < equal.size(); i++) { 37 | int a = equal.get(i).a; 38 | int b = equal.get(i).b; 39 | HashSet currentGroup1 = group.get(a); 40 | HashSet currentGroup2 = group.get(b); 41 | if (currentGroup1 == null && currentGroup2 == null) { 42 | HashSet newSet = new HashSet(); 43 | newSet.add(a); 44 | newSet.add(b); 45 | group.put(a, newSet); 46 | group.put(b, newSet); 47 | } else if (currentGroup1 == null) { 48 | currentGroup2.add(a); 49 | group.put(a, currentGroup2); 50 | } else if (currentGroup2 == null) { 51 | currentGroup1.add(b); 52 | group.put(b, currentGroup1); 53 | } else { 54 | for (Integer n : currentGroup2) { 55 | group.put(n, currentGroup1); 56 | } 57 | currentGroup1.addAll(currentGroup2); 58 | } 59 | } 60 | 61 | // Then check for inequality. 62 | for (int i = 0; i < notEqual.size(); i++) { 63 | int a = notEqual.get(i).a; 64 | int b = notEqual.get(i).b; 65 | if (group.get(a) == group.get(b)) { 66 | return false; 67 | } 68 | } 69 | return true; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/chapter16/question1607.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | public class question1607 { 4 | // See common.PartialOrdering 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/chapter16/question1608.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class question1608 { 6 | 7 | public static void main(String[] args) 8 | { 9 | GraphNode task1 = new GraphNode(1); 10 | GraphNode task2 = new GraphNode(2); 11 | GraphNode task3 = new GraphNode(3); 12 | GraphNode task4 = new GraphNode(20); 13 | task1.edges.put(task2,0); 14 | task1.edges.put(task3,0); 15 | task2.edges.put(task1,0); 16 | HashSet> tasks = new HashSet>(); 17 | tasks.add(task1); 18 | tasks.add(task2); 19 | tasks.add(task3); 20 | tasks.add(task4); 21 | System.out.println(findCompletionTime(tasks)); 22 | } 23 | 24 | public static int findCompletionTime(Set> tasks) 25 | { 26 | HashMap, Integer> completionTime = new HashMap, Integer>(); 27 | HashSet> parents = new HashSet>(); 28 | int max = Integer.MIN_VALUE; 29 | for(GraphNode node : tasks) 30 | { 31 | if(completionTime.containsKey(node)) 32 | { 33 | continue; 34 | } 35 | int result = DFS(node, completionTime,parents); 36 | if(result == -1) 37 | { 38 | // Found loop, never mind 39 | return -1; 40 | } 41 | max = Math.max(max,result); 42 | } 43 | return max; 44 | } 45 | 46 | public static int DFS(GraphNode node, HashMap, Integer> completionTime, HashSet> parents) 47 | { 48 | // If there is a loop 49 | if(parents.contains(node)) 50 | { 51 | return -1; 52 | } 53 | 54 | // Get previous calculated result 55 | Integer maxCompletionTime = completionTime.get(node); 56 | if(maxCompletionTime != null) 57 | { 58 | return maxCompletionTime; 59 | } 60 | 61 | // Add current node to parents 62 | parents.add(node); 63 | 64 | maxCompletionTime = Integer.MIN_VALUE; 65 | for(GraphNode child:node.edges.keySet()) 66 | { 67 | int childCompletionTime = DFS(child, completionTime,parents); 68 | // If a loop is already detected 69 | if(childCompletionTime == -1) 70 | { 71 | return -1; 72 | } 73 | // Take the maximum among all the children 74 | maxCompletionTime = Math.max(maxCompletionTime, childCompletionTime); 75 | } 76 | //If have no child 77 | if(node.edges.keySet().size() == 0) 78 | { 79 | maxCompletionTime = 0; 80 | } 81 | 82 | completionTime.put(node, maxCompletionTime + node.data); 83 | 84 | parents.remove(node); 85 | return maxCompletionTime + node.data; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/chapter16/question1609.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | import java.util.*; 4 | 5 | public class question1609 { 6 | 7 | public static class MetaData 8 | { 9 | int distance; 10 | int steps; 11 | GraphNode lastNode; 12 | 13 | public MetaData() 14 | { 15 | this(Integer.MAX_VALUE, Integer.MAX_VALUE, null); 16 | } 17 | 18 | public MetaData(int distance, int steps) 19 | { 20 | this(distance, steps, null); 21 | } 22 | 23 | public MetaData(int distance, int steps, GraphNode lastNode) 24 | { 25 | this.distance = distance; 26 | this.steps = steps; 27 | this.lastNode = lastNode; 28 | } 29 | } 30 | 31 | public static LinkedList> shortestPathFewestEdges(GraphNode start, GraphNode end, Set> nodes) 32 | { 33 | TreeSet> minQueue = new TreeSet>(new Comparator>(){ 34 | @Override 35 | public int compare(GraphNode o1, GraphNode o2) { 36 | int distanceDiff = o1.data.distance - o2.data.distance; 37 | if(distanceDiff != 0) 38 | { 39 | return distanceDiff; 40 | } 41 | return o1.data.steps - o2.data.steps; 42 | } 43 | }); 44 | 45 | minQueue.addAll(nodes); 46 | minQueue.remove(start); 47 | start.data.distance = 0; 48 | start.data.steps = 0; 49 | minQueue.add(start); 50 | 51 | while(minQueue.size() != 0) 52 | { 53 | GraphNode current = minQueue.pollFirst(); 54 | for(GraphNode child : current.edges.keySet()) 55 | { 56 | int newDistance = current.data.distance + current.edges.get(child); 57 | int newSteps = current.data.steps + 1; 58 | if(child.data.distance > newDistance ||(child.data.distance == newDistance && child.data.steps > newSteps)) 59 | { 60 | minQueue.remove(child); 61 | child.data.distance = newDistance; 62 | child.data.steps = newSteps; 63 | child.data.lastNode = current; 64 | minQueue.add(child); 65 | } 66 | } 67 | } 68 | 69 | LinkedList> result = new LinkedList>(); 70 | while(end != null) 71 | { 72 | result.addFirst(end); 73 | end = end.data.lastNode; 74 | } 75 | return result; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/chapter16/question1610.java: -------------------------------------------------------------------------------- 1 | package chapter16; 2 | 3 | public class question1610 { 4 | // Not implemented 5 | } 6 | -------------------------------------------------------------------------------- /src/chapter17/question1701.java: -------------------------------------------------------------------------------- 1 | package chapter17; 2 | 3 | import java.util.*; 4 | 5 | public class question1701 { 6 | 7 | public static void main(String[] args) 8 | { 9 | ArrayList votes = new ArrayList(); 10 | votes.add(7); 11 | votes.add(5); 12 | System.out.println(isDrawPossible(votes)); 13 | } 14 | 15 | public static boolean isDrawPossible(ArrayList votes) 16 | { 17 | int sum = 0; 18 | for(Integer i : votes) 19 | { 20 | sum += i; 21 | } 22 | if(sum % 2 == 1) 23 | { 24 | return false; 25 | } 26 | int half = sum/2; 27 | 28 | Boolean[] feasibility = new Boolean[half+1]; 29 | 30 | //Having 0 elements to fill 0 votes is feasible. 31 | //On the other hand, all the other values are false, 32 | //indicating it is impossible to fill 0+ votes with 0 elements 33 | feasibility[0] = true; 34 | for(int i = 1;i= currentVote ;j--) 43 | { 44 | // If the value is already attainable without the new vote, 45 | // we skip it. 46 | if(feasibility[j]) 47 | { 48 | continue; 49 | } 50 | // We update feasibility for j only when 51 | // the new vote can be included to make a difference 52 | if(feasibility[j-currentVote]) 53 | { 54 | feasibility[j] = true; 55 | } 56 | } 57 | } 58 | return feasibility[feasibility.length-1]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/chapter17/question1702.java: -------------------------------------------------------------------------------- 1 | package chapter17; 2 | 3 | public class question1702 { 4 | 5 | public static void main(String[] args) 6 | { 7 | int[] weights = new int[]{2,1}; 8 | int[] value = new int[]{1,10}; 9 | int weightGoal = 4; 10 | System.out.println(KnapSack(weights,value, weightGoal)); 11 | } 12 | 13 | public static int KnapSack(int[] weights, int[] value, int weightGoal) { 14 | // Illegal arguments 15 | if (weights.length != value.length) { 16 | return -1; 17 | } 18 | 19 | int[] valueArray = new int[weightGoal + 1]; 20 | for (int i = 0; i < weights.length; i++) { 21 | Util.Utility.print(valueArray); 22 | int currentWeight = weights[i]; 23 | // Here we started from the end, this is important 24 | // because all the values to the left of j in the array 25 | // is from the last i loop. 26 | for (int j = weightGoal; j >= weights[i]; j--) { 27 | valueArray[j] = Math.max(valueArray[j], valueArray[j 28 | - currentWeight] 29 | + value[i]); 30 | } 31 | } 32 | return valueArray[weightGoal]; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/chapter17/question1703.java: -------------------------------------------------------------------------------- 1 | package chapter17; 2 | 3 | import java.util.*; 4 | 5 | public class question1703 { 6 | 7 | public static void main(String[] args) 8 | { 9 | ArrayList list = new ArrayList(); 10 | list.add(1); 11 | list.add(2); 12 | list.add(3); 13 | list.add(5); 14 | System.out.println(divideTheSum(list)); 15 | } 16 | 17 | public static int divideTheSum(ArrayList l) 18 | { 19 | int sum = 0; 20 | for(int i = 0;i< l.size();i++) 21 | { 22 | sum += l.get(i); 23 | } 24 | boolean[] feasible = new boolean[sum+1]; 25 | feasible[0] = true; 26 | for(int i = 0;i= 0;j--) 29 | { 30 | if(feasible[j]) 31 | { 32 | feasible[j+l.get(i)] = true; 33 | } 34 | } 35 | } 36 | 37 | int half = sum/2; 38 | while(!feasible[half]) 39 | { 40 | half --; 41 | } 42 | return half; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/chapter17/question1704.java: -------------------------------------------------------------------------------- 1 | package chapter17; 2 | 3 | import java.util.*; 4 | 5 | public class question1704 { 6 | 7 | public static void main(String[] args) 8 | { 9 | Jug[] jugs = new Jug[3]; 10 | jugs[0] = new Jug(230,240); 11 | jugs[1] = new Jug(290,310); 12 | jugs[2] = new Jug(500,515); 13 | LinkedList result = new LinkedList(); 14 | HashSet infeasiblePairs = new HashSet(); 15 | Util.Utility.print(checkFeasible(jugs, 2300, 2100, result, infeasiblePairs)); 16 | } 17 | 18 | public static class Jug 19 | { 20 | int high; 21 | int low; 22 | public Jug(int high, int low) 23 | { 24 | this.high = high; 25 | this.low = low; 26 | } 27 | 28 | public int hashCode() 29 | { 30 | return high ^ low; 31 | } 32 | 33 | public boolean equals(Object o) 34 | { 35 | if(o == this) 36 | { 37 | return true; 38 | } 39 | if(! (o instanceof Jug)) 40 | { 41 | return false; 42 | } 43 | Jug other = (Jug) o; 44 | return other.high == this.high && other.low == this.low; 45 | } 46 | } 47 | 48 | public static List checkFeasible(Jug[] jugs, int high, int low, List result, HashSet infeasiblePairs) 49 | { 50 | if(high < low || high < 0 || infeasiblePairs.contains(new Jug(high, low))) 51 | { 52 | return null; 53 | } 54 | 55 | for(int i = 0;i= low) 59 | { 60 | result.add(i); 61 | return result; 62 | } 63 | int newHigh = high - j.low; 64 | int newLow = low - j.high; 65 | result.add(i); 66 | List r = checkFeasible(jugs, newHigh, newLow, result, infeasiblePairs); 67 | if(r != null) 68 | { 69 | return r; 70 | } 71 | infeasiblePairs.add(new Jug(high, low)); 72 | result.remove(result.size()-1); 73 | } 74 | return null; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/chapter17/question1708.java: -------------------------------------------------------------------------------- 1 | package chapter17; 2 | 3 | import java.util.*; 4 | 5 | public class question1708 { 6 | 7 | public static void main(String[] args) 8 | { 9 | int[][] sudoku = new int[9][9]; 10 | for(int i = 0;i<9;i++) 11 | { 12 | for(int j = 0;j<9;j++) 13 | { 14 | sudoku[i][j] = 0; 15 | } 16 | } 17 | sudoku[0][0] = 2; 18 | sudoku[8][8] = 3; 19 | Util.Utility.print(solveSudoku(sudoku)); 20 | } 21 | 22 | public static class Cell 23 | { 24 | int x; 25 | int y; 26 | public Cell(int x, int y) 27 | { 28 | this.x = x; 29 | this.y = y; 30 | } 31 | } 32 | 33 | public static int[][] solveSudoku(int[][] sudoku) 34 | { 35 | LinkedList unfilled = new LinkedList(); 36 | for(int i = 0;i 9 || sudoku[i][j] < 1) 41 | { 42 | unfilled.add(new Cell(i,j)); 43 | } 44 | } 45 | } 46 | return solveSudokuRecur(unfilled, sudoku); 47 | } 48 | 49 | public static int[][] solveSudokuRecur(LinkedList unfilled, int[][] sudoku) 50 | { 51 | if(unfilled.size() == 0) 52 | { 53 | return sudoku; 54 | } 55 | Cell cell = unfilled.peekFirst(); 56 | List possible = getPossibleValues(cell, sudoku); 57 | // Not possible 58 | if(possible.size() == 0) 59 | { 60 | return null; 61 | } 62 | unfilled.pollFirst(); 63 | for(Integer i : possible) 64 | { 65 | sudoku[cell.x][cell.y] = i; 66 | int[][] result = solveSudokuRecur(unfilled, sudoku); 67 | if(result != null) 68 | { 69 | return result; 70 | } 71 | } 72 | // We reverse the change made in this recursive call, 73 | // if there is no valid solution 74 | unfilled.addFirst(cell); 75 | sudoku[cell.x][cell.y] = 0; 76 | return null; 77 | } 78 | 79 | public static List getPossibleValues(Cell cell, int[][] sudoku) 80 | { 81 | boolean[] appeared = new boolean[10]; 82 | // Get the matches in the rows and columns 83 | for(int i = 0;i<9;i++) 84 | { 85 | appeared[sudoku[i][cell.y]] = true; 86 | appeared[sudoku[cell.x][i]] = true; 87 | } 88 | // Get the matches in the 3*3 matrix around 89 | int upperX = cell.x/3*3; 90 | int upperY = cell.y/3*3; 91 | for(int i = 0;i<3;i++) 92 | { 93 | for(int j = 0;j<3;j++) 94 | { 95 | appeared[sudoku[upperX+i][upperY+j]] = true; 96 | } 97 | } 98 | //Added the possible ones to the list 99 | LinkedList possible = new LinkedList(); 100 | for(int i = 1;i tested = new HashSet(); 13 | for (int i = 2; i <= k; i++) { 14 | int n = i; 15 | HashSet checked = new HashSet(); 16 | while (true) { 17 | if (n % 2 == 0) { 18 | n >>= 1; 19 | continue; 20 | } 21 | if (tested.contains(n) || n < i || n == 1) { 22 | break; 23 | } 24 | if (checked.contains(n)) { 25 | return false; 26 | } 27 | checked.add(n); 28 | int newN = n * 3 + 1; 29 | if (newN < n) { 30 | throw new Exception("Overflowed!"); 31 | } 32 | n = newN; 33 | } 34 | for (Integer j : checked) { 35 | tested.add(j); 36 | } 37 | tested.add(i); 38 | } 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/common/Combination.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.*; 4 | 5 | public class Combination { 6 | 7 | public static void main(String[] args) 8 | { 9 | HashSet set = new HashSet(); 10 | set.add(1); 11 | set.add(2); 12 | set.add(3); 13 | for(HashSet l : getCombination(set,2)) 14 | { 15 | Util.Utility.print(l); 16 | } 17 | } 18 | 19 | 20 | 21 | public static ArrayList>getCombination(HashSet set, int n) 22 | { 23 | if(n == 0) 24 | { 25 | ArrayList> result = new ArrayList>(); 26 | result.add(new HashSet()); 27 | return result; 28 | } 29 | 30 | ArrayList> finalResult = new ArrayList>(); 31 | for(Integer i : new ArrayList(set)) 32 | { 33 | set.remove(i); 34 | ArrayList> lastResult = getCombination((HashSet) set.clone(), n-1); 35 | for(HashSet s:lastResult) 36 | { 37 | s.add(i); 38 | } 39 | finalResult.addAll(lastResult); 40 | } 41 | return finalResult; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/common/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | public class DoublyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | DoublyLinkedList l = new DoublyLinkedList(); 7 | DoublyLinkedListNode i = new DoublyLinkedListNode(1); 8 | DoublyLinkedListNode j = new DoublyLinkedListNode(2); 9 | DoublyLinkedListNode k = new DoublyLinkedListNode(3); 10 | l.append(i); 11 | l.append(j); 12 | l.remove(j); 13 | l.append(k); 14 | l.remove(l.tail); 15 | l.remove(l.head); 16 | // l.remove(i); 17 | System.out.println(l); 18 | } 19 | 20 | public static class DoublyLinkedListNode { 21 | public T data; 22 | public DoublyLinkedListNode next; 23 | public DoublyLinkedListNode last; 24 | 25 | public DoublyLinkedListNode(T data) { 26 | this.data = data; 27 | next = null; 28 | last = null; 29 | } 30 | 31 | public String toString() { 32 | return data.toString(); 33 | } 34 | } 35 | 36 | public int size; 37 | public DoublyLinkedListNode head; 38 | public DoublyLinkedListNode tail; 39 | 40 | public DoublyLinkedList() { 41 | this.size = 0; 42 | this.head = null; 43 | this.tail = null; 44 | } 45 | 46 | public void append(DoublyLinkedListNode n) { 47 | size++; 48 | if (tail == null) { 49 | head = n; 50 | tail = n; 51 | return; 52 | } 53 | tail.next = n; 54 | n.last = tail; 55 | tail = n; 56 | } 57 | 58 | public void append(T data) { 59 | append(new DoublyLinkedListNode(data)); 60 | } 61 | 62 | public void remove(DoublyLinkedListNode n) { 63 | size--; 64 | if (n.last != null) { 65 | n.last.next = n.next; 66 | } 67 | if (n.next != null) { 68 | n.next.last = n.last; 69 | } 70 | if (n == tail) { 71 | tail = n.last; 72 | } 73 | if (n == head) { 74 | head = n.next; 75 | } 76 | n.next = null; 77 | n.last = null; 78 | } 79 | 80 | public String toString() { 81 | StringBuilder sb = new StringBuilder("{ "); 82 | if (size > 0) { 83 | DoublyLinkedListNode runner = head; 84 | while (runner != tail) { 85 | sb.append(runner + " "); 86 | runner = runner.next; 87 | } 88 | sb.append(tail); 89 | } 90 | sb.append(" }"); 91 | return sb.toString(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/common/KMP.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import Util.Utility; 4 | 5 | public class KMP { 6 | 7 | public static void main(String[] args) { 8 | String w = "abc"; 9 | String s = "cdabdabc"; 10 | System.out.println(stringMatching(w, s)); 11 | Utility.print(partialMatchTable("ababaababa")); 12 | } 13 | 14 | public static int stringMatching(String w, String s) { 15 | int[] table = partialMatchTable(w); 16 | int sp = 0; 17 | int wp = 0; 18 | while (sp < s.length()) { 19 | if (s.charAt(sp + wp) == w.charAt(wp)) { 20 | wp++; 21 | if (wp == w.length()) { 22 | return sp; 23 | } 24 | continue; 25 | } 26 | // It works because table[0] = -1 27 | sp = sp + wp - table[wp]; 28 | if (wp > 0) { 29 | wp = table[wp]; 30 | } 31 | } 32 | return -1; 33 | } 34 | 35 | public static int[] partialMatchTable(String w) { 36 | int[] table = new int[w.length()]; 37 | table[0] = -1; 38 | table[1] = 0; 39 | int lastMatch = 0; 40 | int p = 2; 41 | while (p < table.length) { 42 | if (w.charAt(p - 1) == w.charAt(lastMatch)) { 43 | lastMatch++; 44 | table[p] = lastMatch; 45 | p++; 46 | continue; 47 | } 48 | if (lastMatch != 0) { 49 | lastMatch = table[lastMatch]; 50 | continue; 51 | } 52 | table[p] = lastMatch; 53 | p++; 54 | } 55 | return table; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/common/LRU.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.HashMap; 4 | 5 | import common.DoublyLinkedList.DoublyLinkedListNode; 6 | 7 | public class LRU { 8 | DoublyLinkedList recent; 9 | HashMap> cacheMap; 10 | int cacheSize; 11 | 12 | public LRU(int cacheSize) { 13 | this.cacheSize = cacheSize; 14 | recent = new DoublyLinkedList(); 15 | cacheMap = new HashMap>(); 16 | } 17 | 18 | public T get(T key) { 19 | DoublyLinkedListNode cached = cacheMap.get(key); 20 | if (cached != null) { 21 | recent.remove(cached); 22 | recent.append(cached); 23 | return cached.data; 24 | } 25 | return null; 26 | } 27 | 28 | public void put(T key) { 29 | DoublyLinkedListNode cached = cacheMap.get(key); 30 | if (cached != null) { 31 | recent.remove(cached); 32 | } 33 | recent.append(cached); 34 | 35 | // Limit the size of the cache 36 | if (cacheMap.size() > cacheSize) { 37 | cacheMap.remove(recent.head.data); 38 | recent.remove(recent.head); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/common/MinPriorityQueue.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class MinPriorityQueue { 6 | 7 | public static void main(String[] args) { 8 | 9 | MinPriorityQueue queue = new MinPriorityQueue<>(); 10 | queue.insert(2, 2); 11 | queue.insert(3, 3); 12 | queue.insert(1, 1); 13 | queue.insert(4, 4); 14 | queue.insert(-1, -1); 15 | queue.insert(5, 5); 16 | queue.printArray(); 17 | queue.printArray(); 18 | 19 | } 20 | 21 | public ArrayList> a; 22 | 23 | public int getSize() { 24 | return a.size(); 25 | } 26 | 27 | public void printArray() { 28 | for (int i = 0; i < a.size(); i++) { 29 | System.out.print(a.get(i).key + " "); 30 | } 31 | System.out.println(); 32 | } 33 | 34 | public MinPriorityQueue() { 35 | a = new ArrayList>(); 36 | } 37 | 38 | public Node extractMin() { 39 | if (a.size() == 0) 40 | return null; 41 | Node result = a.get(0); 42 | a.set(0, a.get(a.size() - 1)); 43 | a.remove(a.size() - 1); 44 | if (a.size() > 0) 45 | minHeapify(0); 46 | return result; 47 | } 48 | 49 | public void minHeapify(int i) { 50 | 51 | Node n = a.get(i); 52 | while (true) { 53 | int l = left(i); 54 | int r = right(i); 55 | int min = i; 56 | if (l < a.size()) { 57 | Node lNode = a.get(l); 58 | if (lNode.key < n.key) { 59 | min = l; 60 | n = lNode; 61 | } 62 | } 63 | if (r < a.size()) { 64 | Node rNode = a.get(r); 65 | if (rNode.key < n.key) { 66 | min = r; 67 | n = rNode; 68 | } 69 | } 70 | if (min == i) 71 | return; 72 | swap(i, min); 73 | i = min; 74 | } 75 | } 76 | 77 | public void insert(T data, int key) { 78 | Node n = new Node(); 79 | n.key = Integer.MAX_VALUE; 80 | a.add(n); 81 | decreaseKey(a.size() - 1, key); 82 | } 83 | 84 | public boolean decreaseKey(int index, int newKey) { 85 | Node old = a.get(index); 86 | if (newKey > old.key) 87 | return false; 88 | old.key = newKey; 89 | int parent = parent(index); 90 | while (true) { 91 | if (parent < 0) 92 | return true; 93 | Node p = a.get(parent); 94 | if (p.key < old.key) 95 | return true; 96 | swap(index, parent); 97 | index = parent; 98 | parent = parent(index); 99 | } 100 | } 101 | 102 | private void swap(int m, int n) { 103 | Node temp = a.get(m); 104 | a.set(m, a.get(n)); 105 | a.set(n, temp); 106 | } 107 | 108 | private static int parent(int i) { 109 | if (i == 0) 110 | return -1; 111 | return (i - 1) / 2; 112 | } 113 | 114 | private static int left(int i) { 115 | return i * 2 + 1; 116 | } 117 | 118 | private static int right(int i) { 119 | return i * 2 + 2; 120 | } 121 | 122 | public static class Node { 123 | int key; 124 | T data; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/common/PartialOrdering.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.*; 4 | 5 | public class PartialOrdering { 6 | 7 | public static void main(String[] args) { 8 | ArrayList boxes = new ArrayList(); 9 | boxes.add(new Box(2, 3)); 10 | boxes.add(new Box(2, 3)); 11 | boxes.add(new Box(2, 3)); 12 | System.out.println(getLongest(boxes)); 13 | } 14 | 15 | // For testing 16 | public static class Box implements PartialComparable { 17 | int width; 18 | int height; 19 | 20 | public Box(int width, int height) { 21 | this.width = width; 22 | this.height = height; 23 | } 24 | 25 | @Override 26 | public int compareTo(Box o) { 27 | if (!isComparable(o)) { 28 | throw new RuntimeException("Not comparable"); 29 | } 30 | int wDiff = width - o.width; 31 | int hDiff = height - o.height; 32 | if (wDiff == 0 && hDiff == 0) { 33 | return 0; 34 | } else if (wDiff >= 0 && hDiff >= 0) { 35 | return 1; 36 | } 37 | return -1; 38 | } 39 | 40 | @Override 41 | public boolean isComparable(Box o) { 42 | if ((width >= o.width && height >= o.height) 43 | || (width <= o.width && height <= o.height)) { 44 | return true; 45 | } 46 | return false; 47 | } 48 | 49 | } 50 | 51 | public interface PartialComparable extends Comparable { 52 | boolean isComparable(T object); 53 | } 54 | 55 | public static > int getLongest(ArrayList a) { 56 | int longest = 0; 57 | HashMap cache = new HashMap(); 58 | for (int i = 0; i < a.size(); i++) { 59 | longest = Math.max(longest, topologicalDFS(a, cache, a.get(i))); 60 | } 61 | return longest; 62 | } 63 | 64 | public static > Integer topologicalDFS( 65 | ArrayList a, HashMap cache, T current) { 66 | // If already calculated, we return the result 67 | if (cache.containsKey(current)) { 68 | return cache.get(current); 69 | } 70 | // Otherwise, we get the longest result 71 | int longest = 0; 72 | for (T node : a) { 73 | if (node == current) { 74 | continue; 75 | } 76 | if (!node.isComparable(current)) { 77 | continue; 78 | } 79 | if (node.compareTo(current) > 0) { 80 | longest = Math.max(topologicalDFS(a, cache, node), longest); 81 | } 82 | } 83 | longest += 1; 84 | cache.put(current, longest); 85 | return longest; 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/common/Permutation.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.*; 4 | 5 | public class Permutation { 6 | 7 | public static void main(String[] args) 8 | { 9 | HashSet set = new HashSet(); 10 | set.add(1); 11 | set.add(2); 12 | set.add(3); 13 | for(LinkedList l : getPermutation(set)) 14 | { 15 | Util.Utility.print(l); 16 | } 17 | } 18 | 19 | public static ArrayList> getPermutation(HashSet set) 20 | { 21 | if(set.size() == 1) 22 | { 23 | LinkedList r = new LinkedList(); 24 | for(Integer i : set) 25 | { 26 | r.add(i); 27 | } 28 | ArrayList> result = new ArrayList>(); 29 | result.add(r); 30 | return result; 31 | } 32 | ArrayList> finalResult = new ArrayList>(); 33 | for(Integer i : new ArrayList(set)) 34 | { 35 | set.remove(i); 36 | ArrayList> lastResult = getPermutation(set); 37 | for(LinkedList l : lastResult) 38 | { 39 | l.add(i); 40 | } 41 | finalResult.addAll(lastResult); 42 | set.add(i); 43 | } 44 | return finalResult; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/common/PivotInRotatedArray.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | public class PivotInRotatedArray { 4 | 5 | public static void main(String[] args) { 6 | int[] a = new int[] { 4, 5 }; 7 | System.out.println(findRotationPoint(a)); 8 | } 9 | 10 | public static int findRotationPoint(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 | if (a[p] < a[m]) 18 | return a[m]; 19 | } else if (a[m] < a[p]) { 20 | q = m - 1; 21 | if (a[q] > a[m]) 22 | return a[q]; 23 | } 24 | } 25 | return -1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/common/QuickSort.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import Util.Utility; 4 | 5 | public class QuickSort { 6 | 7 | public static void main(String[] args) { 8 | int[] array = new int[] { 2, 9, 4, 2, 3, 2, 1, 4, 5, 1 }; 9 | quicksort(array, 0, array.length - 1); 10 | Utility.print(array); 11 | } 12 | 13 | public static void quicksort(int[] a, int p, int q) { 14 | if (p >= q) 15 | return; 16 | int m = partition(a, p, q); 17 | quicksort(a, p, m - 1); 18 | quicksort(a, m, q); 19 | } 20 | 21 | public static int partition(int[] a, int p, int q) { 22 | int pivot = a[(p + q) / 2]; 23 | while (p <= q) { 24 | if (a[p] < pivot) 25 | p++; 26 | else if (a[q] > pivot) 27 | q--; 28 | else { 29 | int temp = a[p]; 30 | a[p] = a[q]; 31 | a[q] = temp; 32 | p++; 33 | q--; 34 | } 35 | } 36 | return p; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/common/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import chapter07.LinkedListNode; 4 | 5 | public class ReverseLinkedList { 6 | 7 | public static void main(String[] args) { 8 | LinkedListNode n = LinkedListNode.arrayToList(new int[] { 1, 2, 3, 4, 5, 6 }); 9 | reverseLinkedListIterative(n).printNode(); 10 | } 11 | 12 | @SuppressWarnings({ "rawtypes", "unchecked" }) 13 | public static LinkedListNode reverseLinkedList(LinkedListNode n) { 14 | if (n == null) 15 | return null; 16 | if (n.next == null) 17 | return n; 18 | LinkedListNode last = n.next; 19 | LinkedListNode front = reverseLinkedList(n.next); 20 | last.next = n; 21 | n.next = null; 22 | return front; 23 | } 24 | 25 | @SuppressWarnings({ "rawtypes", "unchecked" }) 26 | public static LinkedListNode reverseLinkedListIterative(LinkedListNode n) { 27 | LinkedListNode newListStart = null; 28 | while (n != null) { 29 | LinkedListNode temp = n.next; 30 | n.next = newListStart; 31 | newListStart = n; 32 | n = temp; 33 | } 34 | return newListStart; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/common/SelectIndexEqualValue.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | public class SelectIndexEqualValue { 4 | 5 | public static void main(String[] args) { 6 | // 0, 1,2,3,4,5,6,7,8,9,10 7 | int[] a = new int[] { -2, 0, 2, 2, 2, 4, 8, 9, 10 }; 8 | System.out.println(selectDuplicate(a, 0, a.length - 1)); 9 | 10 | } 11 | 12 | public static int selectDuplicate(int[] a, int p, int q) { 13 | if (q < p) 14 | return -1; 15 | int m = (p + q) / 2; 16 | int num = a[m]; 17 | if (num == m) 18 | return m; 19 | if (num < m) { 20 | int rightResult = selectDuplicate(a, m + 1, q); 21 | if (rightResult != -1) 22 | return rightResult; 23 | int leftResult = selectDuplicate(a, Math.max(p, num), m - 1); 24 | if (leftResult != -1) 25 | return leftResult; 26 | } 27 | if (num > m) { 28 | int rightResult = selectDuplicate(a, m + 1, Math.min(q, num)); 29 | if (rightResult != -1) 30 | return rightResult; 31 | int leftResult = selectDuplicate(a, p, m - 1); 32 | return leftResult; 33 | } 34 | return -1; 35 | } 36 | 37 | /** 38 | * Find the index in array a which has the property a[i] = i. The elements 39 | * of the array must be distinct. 40 | * 41 | * @param a 42 | * the array 43 | * @return the index if such element exists, -1 otherwise. 44 | */ 45 | public static int selectDistinct(int[] a) { 46 | int m = a.length / 2; 47 | int p = 0; 48 | int q = a.length - 1; 49 | while (p <= q) { 50 | m = (p + q) / 2; 51 | int num = a[m]; 52 | if (num == m) 53 | return m; 54 | if (num < m) 55 | p = m + 1; 56 | else if (num > m) 57 | q = m - 1; 58 | } 59 | return -1; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/common/Selection.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | public class Selection { 4 | 5 | public static void main(String[] args) { 6 | int[] a = new int[] { 0, 3, 2, 1 }; 7 | System.out.println(rank(a, 0, a.length - 1, 2)); 8 | } 9 | 10 | public static int randomInt(int n) { 11 | return (int) (Math.random() * n); 12 | } 13 | 14 | public static int randomIntInRange(int min, int max) { 15 | return randomInt(max + 1 - min) + min; 16 | } 17 | 18 | public static int partition(int[] array, int left, int right, int pivot) { 19 | while (true) { 20 | while (left <= right && array[left] <= pivot) { 21 | left++; 22 | } 23 | 24 | while (left <= right && array[right] > pivot) { 25 | right--; 26 | } 27 | 28 | if (left > right) { 29 | return left - 1; 30 | } 31 | swap(array, left, right); 32 | } 33 | } 34 | 35 | public static int max(int[] array, int left, int right) { 36 | int max = Integer.MIN_VALUE; 37 | for (int i = left; i <= right; i++) { 38 | max = Math.max(array[i], max); 39 | } 40 | return max; 41 | } 42 | 43 | public static int rank(int[] array, int left, int right, int rank) { 44 | int pivot = array[randomIntInRange(left, right)]; 45 | int leftEnd = partition(array, left, right, pivot); // returns end of 46 | // left partition 47 | int leftSize = leftEnd - left + 1; 48 | // The + 1 here is used so that our index start from 0, it can be 49 | // removed 50 | if (leftSize == rank + 1) { 51 | return max(array, left, leftEnd); 52 | } else if (rank < leftSize) { 53 | return rank(array, left, leftEnd, rank); 54 | } else { 55 | return rank(array, leftEnd + 1, right, rank - leftSize); 56 | } 57 | } 58 | 59 | public static void swap(int[] a, int p, int q) { 60 | int temp = a[p]; 61 | a[p] = a[q]; 62 | a[q] = temp; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/common/ShortestPath.java: -------------------------------------------------------------------------------- 1 | package common; 2 | 3 | import java.util.*; 4 | 5 | public class ShortestPath { 6 | 7 | // See question1609 for Dijkstra with adjacency list 8 | public static int NO_PATH = -1; 9 | 10 | public static int Dijkstra(int[][] matrix, int start, int end) { 11 | HashSet unvisited = new HashSet(0); 12 | for (int i = 0; i < matrix.length; i++) { 13 | unvisited.add(i); 14 | } 15 | int[] distance = new int[matrix.length]; 16 | for (int i = 0; i < distance.length; i++) { 17 | distance[i] = Integer.MAX_VALUE; 18 | } 19 | distance[start] = 0; 20 | while (unvisited.size() != 0) { 21 | // First get the node with the shortest distance from start 22 | int shortestDistance = Integer.MAX_VALUE; 23 | int closestNode = -1; 24 | // O(N) operation here. Use min-heap to improve running time 25 | for (Integer i : unvisited) { 26 | if (shortestDistance > distance[i]) { 27 | shortestDistance = distance[i]; 28 | closestNode = i; 29 | } 30 | } 31 | 32 | unvisited.remove(closestNode); 33 | 34 | for (int i = 0; i < matrix[closestNode].length; i++) { 35 | if (matrix[closestNode][i] == NO_PATH || !unvisited.contains(i)) { 36 | continue; 37 | } 38 | int newDis = distance[closestNode] + matrix[closestNode][i]; 39 | if (newDis < distance[i]) { 40 | distance[i] = newDis; 41 | } 42 | } 43 | } 44 | return distance[end]; 45 | } 46 | } 47 | --------------------------------------------------------------------------------