├── .classpath ├── .gitignore ├── .project ├── .settings └── org.eclipse.jdt.core.prefs └── src ├── BitManipulationProblems.java ├── DeckOfCards.java ├── DynamicProgrammingAndRecursion.java ├── GraphProblems.java ├── LFUCache.java ├── LinkedListProblems.java ├── MathAndLogicProblems.java ├── MatrixProblems.java ├── SortingAlgorithms.java └── StackProblems.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | SortingAlgorithms 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.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 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.8 12 | -------------------------------------------------------------------------------- /src/BitManipulationProblems.java: -------------------------------------------------------------------------------- 1 | 2 | public class BitManipulationProblems { 3 | 4 | public static int updateBits(int n, int m, int i, int j) { 5 | int left = ~0 << (j+1); 6 | System.out.println("left: " + Integer.toBinaryString(left)); 7 | int right = ((1 << i) - 1); 8 | System.out.println("right: " + Integer.toBinaryString(right)); 9 | int mask = left | right; 10 | System.out.println("mask: " + Integer.toBinaryString(mask)); 11 | int n_cleared = n & mask; 12 | System.out.println("n_cleared: " + Integer.toBinaryString(n_cleared)); 13 | int m_shifted = m << i; 14 | System.out.println("m_shifted: " + Integer.toBinaryString(m_shifted)); 15 | return n_cleared | m_shifted; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/DeckOfCards.java: -------------------------------------------------------------------------------- 1 | 2 | public class DeckOfCards { 3 | public enum Suit { 4 | Club(0), Diamond(1), Heart(2), Spade(3); 5 | private int value; 6 | private Suit(int v) {this.value = v;} 7 | public int getValue() { return this.value; } 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/DynamicProgrammingAndRecursion.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | 4 | public class DynamicProgrammingAndRecursion { 5 | public static int getNthFibonnaci1(int n) { 6 | if(n==0) return 0; 7 | if(n==1) return 1; 8 | return getNthFibonnaci1(n-1) + getNthFibonnaci1(n-2); 9 | } 10 | 11 | public static int getNthFibonnaci2(int n) { 12 | return getNthFibonnaci2Memo(n, new int[n + 1]); 13 | } 14 | 15 | public static int getNthFibonnaci2Memo(int n, int[] memo) { 16 | if(n == 0 || n == 1) return n; 17 | 18 | if(memo[n] == 0) { 19 | memo[n] = getNthFibonnaci2Memo(n-1, memo) + getNthFibonnaci2Memo(n-2, memo); 20 | } 21 | return memo[n]; 22 | } 23 | 24 | public static int getNthFibonnaciBottomUp(int n) { 25 | if(n == 0 || n == 1) return n; 26 | 27 | int[] memo = new int[n]; 28 | memo[0] = 0; 29 | memo[1] = 1; 30 | for(int i=2; i < n; i++) { 31 | memo[i] = memo[i-1] + memo[i-2]; 32 | } 33 | 34 | return memo[n-1] + memo[n-2]; 35 | } 36 | 37 | public static int getNthFibonnaciBottomUpLessMemory(int n) { 38 | if(n == 0) return 0; 39 | int a = 0; 40 | int b = 1; 41 | 42 | for(int i=2; i < n; i++) { 43 | int c = a + b; 44 | a = b; 45 | b = c; 46 | } 47 | 48 | return a + b; 49 | } 50 | 51 | public static int countWays(int n) { 52 | int[] memo = new int[n+1]; 53 | Arrays.fill(memo, -1); 54 | return countWays(n, memo); 55 | } 56 | 57 | public static int countWays(int n, int[] memo) { 58 | if(n < 0) return 0; 59 | if(n == 0) return 1; 60 | if(memo[n] > -1) return memo[n]; 61 | memo[n] = countWays(n-1, memo) + countWays(n-2, memo) + countWays(n-3, memo); 62 | return memo[n]; 63 | } 64 | 65 | public static int magicIndex(int[] array, int start, int end) { 66 | if(end < start) return -1; 67 | int mid = (start + end)/2; 68 | if(array[mid] == mid) return mid; 69 | if(mid < array[mid]) { 70 | return magicIndex(array, start, mid-1); 71 | } 72 | if(mid > array[mid]) { 73 | return magicIndex(array, mid + 1, end); 74 | } 75 | return -1; 76 | } 77 | 78 | public static int magicIndexNotDistinct(int[] array, int start, int end) { 79 | if(end < start) return -1; 80 | int mid = (start + end)/2; 81 | if(array[mid] == mid) return mid; 82 | 83 | //Search Left 84 | int minIndex = Math.min(mid - 1, array[mid]); 85 | int left = magicIndexNotDistinct(array, start, minIndex); 86 | if(left >= 0) return left; 87 | 88 | //Search Right 89 | int maxIndex = Math.max(mid + 1, array[mid]); 90 | int right = magicIndexNotDistinct(array, maxIndex, end); 91 | return right; 92 | } 93 | 94 | public static ArrayList> getSubsets(ArrayList set) { 95 | ArrayList> allSubsets = new ArrayList>(); 96 | int i = 0; 97 | allSubsets.add(new ArrayList()); 98 | while(i < set.size()) { 99 | //add the current element on every subset and re-add 100 | ArrayList> moreSubsets = new ArrayList>(); 101 | for(ArrayList subset : allSubsets) { 102 | ArrayList newSubset = new ArrayList(); 103 | newSubset.addAll(subset); 104 | newSubset.add(set.get(i)); 105 | moreSubsets.add(newSubset); 106 | } 107 | allSubsets.addAll(moreSubsets); 108 | i++; 109 | } 110 | return allSubsets; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/GraphProblems.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | 5 | public class GraphProblems { 6 | // 7 | static public class Graph { 8 | public ArrayList nodes; 9 | } 10 | 11 | static public class directedGraph extends Graph { 12 | public void addEdge(Node node1, Node node2) { 13 | node1.children.add(node2); 14 | } 15 | } 16 | 17 | static public class UndirectedGraph extends Graph { 18 | public void addEdge(Node node1, Node node2) { 19 | node1.children.add(node2); 20 | node2.children.add(node1); 21 | } 22 | } 23 | 24 | enum State {Unvisited, Visiting, Visited} 25 | 26 | static public class Node{ 27 | public int value; 28 | public NodeState state; 29 | protected ArrayList children; 30 | 31 | public Node(int value) { 32 | this.value = value; 33 | this.children = new ArrayList<>(); 34 | this.state = NodeState.Unvisited; 35 | } 36 | 37 | public void addChild(Node e) { 38 | children.add(e); 39 | } 40 | 41 | public ArrayList getAdjacent() { 42 | return children; 43 | } 44 | } 45 | 46 | static public class TreeNode extends Node{ 47 | TreeNode parent; 48 | 49 | public TreeNode(int value) { 50 | super(value); 51 | } 52 | 53 | public void addChildLeft(TreeNode left) { 54 | //if(left != null) { 55 | this.children.add(0, left); 56 | //left.parent = this; 57 | //} 58 | } 59 | 60 | public void addChildRight(TreeNode right) { 61 | //if(right != null) { 62 | this.children.add(1, right); 63 | //right.parent = this; 64 | //} 65 | } 66 | 67 | public TreeNode getChildLeft() { 68 | if(this.children.isEmpty()) return null; 69 | return (TreeNode) this.children.get(0); 70 | } 71 | 72 | public TreeNode getChildRight() { 73 | if(this.children.isEmpty() || this.children.size() < 2) return null; 74 | return (TreeNode) this.children.get(1); 75 | } 76 | } 77 | 78 | 79 | enum NodeState {Unvisited, Visiting, Visited} 80 | 81 | public static boolean doesPathExist(Graph g, Node start, Node end) { 82 | if(start == end) return true; 83 | 84 | Queue q = new LinkedList<>(); 85 | 86 | //BFS 87 | start.state = NodeState.Visiting; 88 | q.add(start); 89 | Node u; 90 | while(!q.isEmpty()) { 91 | u = q.remove(); 92 | if(u != null) { 93 | for (Node n : u.getAdjacent()) { 94 | if(n.state == NodeState.Unvisited) { 95 | if(n == end) { 96 | return true; 97 | } else { 98 | n.state = NodeState.Visiting; 99 | q.add(n); 100 | } 101 | } 102 | } 103 | } 104 | u.state = NodeState.Visited; 105 | } 106 | return false; 107 | } 108 | 109 | public static TreeNode createMinimalBST(int[] array, int start, int end) { 110 | if(end < start) return null; 111 | 112 | int mid = (start + end)/2; 113 | TreeNode n = new TreeNode(array[mid]); 114 | n.addChildLeft(createMinimalBST(array, start, mid-1)); 115 | n.addChildRight(createMinimalBST(array, mid+1, end)); 116 | return n; 117 | } 118 | 119 | public static ArrayList> createLinkedListPerLevel(TreeNode root) { 120 | ArrayList> listPerLevel = new ArrayList>(); 121 | createLinkedListPerLevel(root, listPerLevel, 0); 122 | return listPerLevel; 123 | } 124 | 125 | private static void createLinkedListPerLevel(TreeNode node, 126 | ArrayList> listPerLevel, int level) { 127 | if(node == null) return; 128 | LinkedList list = null; 129 | if(listPerLevel.size() == level) { 130 | list = new LinkedList(); 131 | listPerLevel.add(list); 132 | } else { 133 | list = listPerLevel.get(level); 134 | } 135 | list.add(node); 136 | createLinkedListPerLevel(node.getChildLeft(), listPerLevel, level+1); 137 | createLinkedListPerLevel(node.getChildRight(), listPerLevel,level+1); 138 | } 139 | 140 | public static int checkHeight(TreeNode root) { 141 | if(root == null) return -1; 142 | 143 | int leftHeight = checkHeight(root.getChildLeft()); 144 | if(leftHeight == Integer.MIN_VALUE) return Integer.MIN_VALUE; 145 | 146 | int rightHeight = checkHeight(root.getChildRight()); 147 | if(rightHeight == Integer.MIN_VALUE) return Integer.MIN_VALUE; 148 | 149 | int heightDiff = leftHeight - rightHeight; 150 | if(Math.abs(heightDiff) > 1) return Integer.MIN_VALUE; 151 | else return Math.max(leftHeight, rightHeight) + 1; 152 | } 153 | 154 | public static boolean isBalanced(TreeNode root) { 155 | return checkHeight(root) != Integer.MIN_VALUE; 156 | } 157 | 158 | public static boolean isValidBST(TreeNode root) { 159 | return checkBST(root, null, null); 160 | } 161 | 162 | public static boolean checkBST(TreeNode node, Integer min, Integer max) { 163 | if(node == null) return true; 164 | 165 | if(min != null && node.value <= min || max != null && node.value > max) { 166 | return false; 167 | } 168 | 169 | if(!checkBST(node.getChildLeft(), min, node.value) || 170 | !checkBST(node.getChildRight(), node.value, max)) { 171 | return false; 172 | } 173 | 174 | return true; 175 | } 176 | 177 | public static TreeNode getCommonAncestor(TreeNode a, TreeNode b) { 178 | int delta = depth(a) - depth(b); 179 | TreeNode first = (delta > 0) ? b : a; //shallower node 180 | TreeNode second = (delta > 0) ? a : b; //deeper node 181 | 182 | //Bring the deeper node up to the shallower node well 183 | while(delta > 0 && second != null) { 184 | second = second.parent; 185 | delta--; 186 | } 187 | 188 | while(first != second && first != null && second != null) { 189 | first = first.parent; 190 | second = second.parent; 191 | } 192 | 193 | return first == null || second == null ? null : first; 194 | } 195 | 196 | public static int depth(TreeNode node) { 197 | int depth = 0; 198 | while(node.parent != null) { 199 | node = node.parent; 200 | depth++; 201 | } 202 | return depth; 203 | } 204 | 205 | public static void inOrderTraversal(TreeNode root) { 206 | if(root != null) { 207 | inOrderTraversal(root.getChildLeft()); 208 | System.out.print(root.value); 209 | inOrderTraversal(root.getChildRight()); 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/LFUCache.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class LFUCache { 4 | // int capacity = 0; 5 | // HashMap values, frequency; 6 | // 7 | // public LFUCache(int capacity) { 8 | // this.capacity = capacity; 9 | // this.values = new HashMap<>(); 10 | // this.frequency = new HashMap<>(); 11 | // } 12 | // 13 | // public int get(int key) { 14 | // if(!this.values.containsKey(key)) return -1; 15 | // if(frequency) 16 | // return values.get(key); 17 | // } 18 | // 19 | // public void set(int key, int value) { 20 | // if(values.size) 21 | // } 22 | } 23 | -------------------------------------------------------------------------------- /src/LinkedListProblems.java: -------------------------------------------------------------------------------- 1 | public class LinkedListProblems { 2 | 3 | public static LinkedListNode createLinkedList(int[] data) { 4 | LinkedListNode head = null; 5 | LinkedListNode tail = null; 6 | for(int i=0; i < data.length; i++) { 7 | LinkedListNode newNode = new LinkedListNode(data[i]); 8 | if(head == null) head = newNode; 9 | if(tail != null) tail.next = newNode; 10 | tail = newNode; 11 | } 12 | return head; 13 | } 14 | 15 | public static void printLinkedList(LinkedListNode head) { 16 | LinkedListNode node = head; 17 | System.out.print("LinkedList: "); 18 | while(node != null) { 19 | System.out.print(node.data + " "); 20 | node = node.next; 21 | } 22 | } 23 | 24 | public static void removeDups(LinkedListNode head) { 25 | LinkedListNode current = head; 26 | while(current != null) { 27 | LinkedListNode runner = current; 28 | while(runner.next != null) { 29 | if(runner.next.data == current.data) { 30 | //remove it 31 | runner.next = runner.next.next; 32 | } else { 33 | runner = runner.next; 34 | } 35 | } 36 | current = current.next; 37 | } 38 | } 39 | 40 | public static LinkedListNode getElementAtIndexFromEnd(LinkedListNode head, int k) { 41 | LinkedListNode p1 = head, p2 = head; 42 | 43 | //traverse p1 k up 44 | for(int i=0; i <= k; i++) { 45 | if(p1 == null) return null; //list shorter than k 46 | p1 = p1.next; 47 | } 48 | 49 | //traverse p2 for remainder of p1 50 | while(p1 != null) { 51 | p1 = p1.next; 52 | p2 = p2.next; 53 | } 54 | 55 | return p2; 56 | } 57 | 58 | public static LinkedListNode getMiddleNode(LinkedListNode head) { 59 | LinkedListNode current = head; 60 | int length = 1; 61 | //Get length of the Linked List 62 | while(current != null) { 63 | length++; 64 | current = current.next; 65 | } 66 | 67 | int mid = length/2; 68 | current = head; 69 | for(int i=0; i> dropsByDay = new ArrayList>(); 18 | private int id; 19 | 20 | public TestStrip(int id) {this.id = id;} 21 | public int getld() { return id; } 22 | 23 | /* Re size list of days/drops to be large enough. */ 24 | private void sizeDropsForDay(int day) { 25 | while (dropsByDay.size() <= day) { 26 | dropsByDay.add(new ArrayList()); 27 | } 28 | } 29 | 30 | /* Add drop from bottle on specific day. */ 31 | public void addDropOnDay(int day, Bottle bottle) { 32 | sizeDropsForDay(day); 33 | ArrayList drops = dropsByDay.get(day); 34 | drops.add(bottle); 35 | } 36 | 37 | /* Checks if any of the bottles in the set are poisoned. */ 38 | private boolean hasPoison(ArrayList bottles) { 39 | for (Bottle b : bottles) { 40 | if (b.isPoisoned()) { 41 | return true; 42 | } 43 | } 44 | 45 | return false; 46 | } 47 | 48 | /* Get s bottles used in the test DAYS_FaR_RESULT days ago. */ 49 | public ArrayList getLastWeeksBottles(int day) { 50 | if (day < DAYS_FOR_RESULT) { 51 | return null; 52 | } 53 | return dropsByDay.get(day - DAYS_FOR_RESULT); 54 | } 55 | 56 | /* Checks for poisoned bottles since before DAYS FOR RESULT */ 57 | public boolean isPositiveOnDay(int day) { 58 | int testDay = day - DAYS_FOR_RESULT; 59 | if (testDay < 0 && testDay >= dropsByDay.size()) { 60 | return false; 61 | } 62 | 63 | for (int d = 0; d <= testDay; d++) { 64 | ArrayList bottles = dropsByDay.get(d); 65 | if (hasPoison(bottles)) { 66 | return true; 67 | } 68 | } 69 | 70 | return false; 71 | } 72 | } 73 | 74 | public static boolean isPrimeNaive(int n) { 75 | if(n < 2) return false; 76 | 77 | for(int i=2; i < n; i++) { 78 | if(n % i == 0) return false; 79 | } 80 | 81 | return true; 82 | } 83 | 84 | public static boolean isPrimeBetter(int n) { 85 | boolean[] flags = new boolean[n + 1]; 86 | int prime = 2; 87 | while(prime <= Math.sqrt(n)) { 88 | //check all number divisible by prime 89 | for(int i = prime * prime; i <= n; i += prime) { 90 | if(i == n) return false; 91 | } 92 | 93 | //get next prime 94 | int next = prime + 1; 95 | while(next < n && !flags[next]) { 96 | next++; 97 | } 98 | prime = next; 99 | } 100 | return true; 101 | } 102 | 103 | public static double runFamilies(int n) { 104 | int boys = 0, girls = 0; 105 | for(int i=0; i < n; i++) { 106 | int[] genders = runSingleFamily(); 107 | girls += genders[0]; 108 | boys += genders[0]; 109 | } 110 | 111 | return girls / (double) (boys + girls); 112 | } 113 | 114 | public static int[] runSingleFamily() { 115 | int boys=0, girls=0; 116 | Random random = new Random(); 117 | while(girls <= 0) { 118 | if(random.nextBoolean()) girls ++; 119 | else boys++; 120 | } 121 | 122 | return new int[]{girls, boys}; 123 | } 124 | 125 | public static boolean[] hundredDoors() { 126 | boolean[] doors = new boolean[100]; 127 | 128 | //Open all doors 129 | for(int i=0; i<100; i++) { 130 | doors[i] = true; 131 | } 132 | 133 | //close every second 134 | for(int i=1; i < 100; i += 2) { 135 | doors[i] = false; 136 | } 137 | 138 | // 139 | for(int i=2; i < 100; i++) { 140 | for(int j=i; j<=100; j += i+1) { 141 | doors[i] = !doors[i]; 142 | } 143 | } 144 | 145 | return doors; 146 | } 147 | 148 | 149 | } 150 | -------------------------------------------------------------------------------- /src/MatrixProblems.java: -------------------------------------------------------------------------------- 1 | import java.awt.List; 2 | 3 | public class MatrixProblems { 4 | public static boolean rotateMatrix(int[][] matrix) { 5 | if(matrix.length == 0 || matrix.length != matrix[0].length) return false; 6 | int n = matrix.length; 7 | 8 | for(int layer=0; layer < n/2; layer ++) { 9 | int first = layer; 10 | int last = n - 1 - layer; 11 | for(int i=first; i < last; i++) { 12 | int offset = i - first; 13 | int top = matrix[first][i]; //save top 14 | matrix[first][i] = matrix[last-offset][first]; //left to top 15 | matrix[last-offset][first] = matrix[last][last-offset]; //bottom to left 16 | matrix[last][last-offset] = matrix[i][last];//right to bottom 17 | matrix[i][last] = top;//top to right 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | public static void zeroMatrix(int[][] matrix) { 24 | Coordinate[] zeroCoords = new Coordinate[matrix.length * matrix[0].length]; 25 | 26 | //Get all zero coordinates 27 | int coordCount = 0; 28 | for(int i=0; i < matrix.length; i++) { 29 | for(int j=0; j < matrix[0].length; j++) { 30 | if(matrix[i][j] == 0) { 31 | zeroCoords[coordCount] = new MatrixProblems.Coordinate(i, j); 32 | coordCount++; 33 | } 34 | } 35 | } 36 | 37 | //Zero rows and columns 38 | for(int i=0; i < coordCount; i++) { 39 | zeroRow(zeroCoords[i].x, matrix); 40 | zeroColumn(zeroCoords[i].y, matrix); 41 | } 42 | } 43 | 44 | private static void zeroRow(int x, int[][] matrix) { 45 | for(int i=0; i < matrix[0].length; i++) { 46 | matrix[x][i] = 0; 47 | } 48 | } 49 | 50 | private static void zeroColumn(int y, int[][] matrix) { 51 | for(int i=0; i < matrix.length; i++) { 52 | matrix[i][y] = 0; 53 | } 54 | } 55 | 56 | private static class Coordinate { 57 | int x; 58 | int y; 59 | 60 | public Coordinate(int x, int y) { 61 | this.x = x; 62 | this.y = y; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/SortingAlgorithms.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Stack; 6 | 7 | public class SortingAlgorithms { 8 | 9 | public static void main(String[] args) { 10 | System.out.println("Hello World"); 11 | 12 | int[] array = {7,2,1,6,8,5,3,4}; 13 | quickSort(array, 0, 7); 14 | System.out.print("quickSort: "); 15 | for(int i=0; i < array.length; i++) { 16 | System.out.print(array[i] + " "); 17 | } 18 | 19 | array = new int[]{7,2,1,6,8,5,3,4}; 20 | mergeSort(array); 21 | System.out.print("mergeSort: "); 22 | for(int i=0; i < array.length; i++) { 23 | System.out.print(array[i] + " "); 24 | } 25 | 26 | System.out.print("Searched 7 in array: " + binarySearch(7, array)); 27 | 28 | System.out.print("Fibonaci at 9: " + getFibonaci(9)[9]); 29 | 30 | array = new int[]{3,4,5,6,1,2}; 31 | System.out.print("Searched 2 in array: " + shiftedBinarySearch(2, array)); 32 | 33 | char[] testString = new char[]{'t', 'e', 's','t','s','t','r','i','n','g'}; 34 | System.out.println(areAllCharsInStringUnique(testString)); 35 | 36 | String testStr1 = "abcdefg"; 37 | String testStr2 = "gfedcab"; 38 | System.out.println(isPermutation(testStr1, testStr2)); 39 | 40 | testStr1 = "Mr John Smith "; 41 | char[] input = testStr1.toCharArray(); 42 | urlify(input, 13); 43 | testStr1 = new String(input); 44 | System.out.println(testStr1); 45 | 46 | testStr1 = "tactcoapapa"; 47 | System.out.println("isPermutationPalindrome: " + isPermutationPalindrome(testStr1)); 48 | 49 | testStr1 = "pale"; 50 | testStr2 = "bae"; 51 | System.out.println("isOneEdit Away: " + isOneEditAway(testStr1, testStr2)) ; 52 | 53 | testStr1 = "aabbccddeefff"; 54 | System.out.println("compressed String: " + basicStringCompression(testStr1)); 55 | 56 | //Matrices 57 | int[][] matrix = new int[][]{{1,2,3,4}, 58 | {1,2,3,4}, 59 | {1,2,3,4}, 60 | {1,2,3,4}}; 61 | if(MatrixProblems.rotateMatrix(matrix)) { 62 | printMatrix(matrix); 63 | } 64 | 65 | matrix = new int[][]{{1,2,3,4}, 66 | {1,0,3,4}, 67 | {2,4,2,0}, 68 | {4,5,2,1}}; 69 | MatrixProblems.zeroMatrix(matrix); 70 | printMatrix(matrix); 71 | 72 | //LinkedList 73 | LinkedListProblems.LinkedListNode linkedList = LinkedListProblems.createLinkedList(new int[]{2,3,1,2,4,5,12}); 74 | LinkedListProblems.printLinkedList(linkedList); 75 | LinkedListProblems.removeDups(linkedList); 76 | LinkedListProblems.printLinkedList(linkedList); 77 | System.out.println("Element at 3 from back is: " + LinkedListProblems.getElementAtIndexFromEnd(linkedList, 3).data); 78 | 79 | linkedList = LinkedListProblems.createLinkedList(new int[]{2,3,1,2,4,5,12}); 80 | LinkedListProblems.LinkedListNode mid = LinkedListProblems.getMiddleNode(linkedList); 81 | System.out.println("Delete " + mid.data + " from "); 82 | LinkedListProblems.printLinkedList(linkedList); 83 | if(LinkedListProblems.deleteNode(mid)) { 84 | LinkedListProblems.printLinkedList(linkedList); 85 | } 86 | 87 | // linkedList = createLinkedList(new int[]{2,3,1,2,4,5,12}); 88 | // printLinkedList(linkedList); 89 | // LinkedListNode partitioned = partition(linkedList, 2); 90 | // printLinkedList(partitioned); 91 | 92 | int number = 12345; 93 | System.out.println("Reverse " + number + ": " + reverseInt(number)); 94 | 95 | String s = "tree"; 96 | String freqSortedString = frequencySort(s); 97 | System.out.println("freqSortedString: " + freqSortedString); 98 | 99 | int[] nums = {1,1,1,2,2,3}; 100 | List topkFrequent = topKFrequent(nums, 2); 101 | for(Integer i : topkFrequent) { 102 | System.out.print(i + " "); 103 | } 104 | 105 | StackProblems.StackWithMin stackMin = new StackProblems.StackWithMin(); 106 | stackMin.push(7); 107 | stackMin.push(9); 108 | stackMin.push(10); 109 | System.out.println("Stack Min: " + stackMin.min()); 110 | 111 | Stack testStack = new Stack(); 112 | testStack.push(4); 113 | testStack.push(2); 114 | testStack.push(9); 115 | testStack.push(7); 116 | StackProblems.sortStack(testStack); 117 | StackProblems.printStack(testStack); 118 | 119 | System.out.println(Integer.toBinaryString(BitManipulationProblems.updateBits(0b10000000000, 0b10011, 2, 6))); 120 | 121 | System.out.println("Is 97 a prime? (Naive)" + MathAndLogicProblems.isPrimeNaive(97)); 122 | System.out.println("Is 97 a prime? (Smart)" + MathAndLogicProblems.isPrimeNaive(97)); 123 | 124 | System.out.println("Gender Ratio: " + MathAndLogicProblems.runFamilies(100)); 125 | 126 | boolean[] doors = MathAndLogicProblems.hundredDoors(); 127 | int openCount = 0; 128 | for(int i=0; i> levels = GraphProblems.createLinkedListPerLevel(root); 139 | for(LinkedList list : levels) { 140 | for(GraphProblems.TreeNode node : list) { 141 | System.out.print(node.value + " "); 142 | } 143 | System.out.print("\n"); 144 | } 145 | 146 | System.out.println("Is Balanced? : " + GraphProblems.isBalanced(root)); 147 | System.out.println("Is BST? : " + GraphProblems.isValidBST(root)); 148 | 149 | //System.out.println(GraphProblems.getCommonAncestor(root.getChildRight().getChildLeft(), root.getChildLeft().getChildLeft()).value); 150 | 151 | //Magic Index 152 | int[] magicArray = {-2,-1,1,3,7,9,23,25,27}; 153 | System.out.println("Magic Index: " + DynamicProgrammingAndRecursion.magicIndex(magicArray, 0, magicArray.length-1)); 154 | int[] magicArrayNotDistinct = {-10,-5,2,2,2,3,4,7,9,12,13}; 155 | System.out.println("Magic Index not distinct: " + DynamicProgrammingAndRecursion.magicIndexNotDistinct(magicArrayNotDistinct, 0, magicArray.length-1)); 156 | 157 | System.out.println(convert("PAYPALISHIRING", 3)); 158 | System.out.println(convertTwo("PAYPALISHIRING", 3)); 159 | 160 | System.out.println("intToRoman: " + intToRoman(3999)); 161 | System.out.println("romanToInt: " + romanToInt("DCXXI")); 162 | 163 | ArrayList testArray = new ArrayList<>(); 164 | testArray.add(1); 165 | testArray.add(2); 166 | testArray.add(3); 167 | for(ArrayList subSet : DynamicProgrammingAndRecursion.getSubsets(testArray)) { 168 | System.out.print("{"); 169 | for(Integer i=0; i < subSet.size() ; i++) { 170 | System.out.print(subSet.get(i) + ", "); 171 | } 172 | System.out.print("}, "); 173 | } 174 | } 175 | 176 | private static void printMatrix(int[][] matrix) { 177 | for(int i=0; i < matrix.length; i++) { 178 | for(int j=0; j < matrix[0].length; j++) { 179 | System.out.print(matrix[i][j]); 180 | } 181 | System.out.print('\n'); 182 | } 183 | } 184 | 185 | private static void quickSort(int[] array, int start, int end) { 186 | if(start > end) { 187 | int pIndex = partition(array, start, end); 188 | quickSort(array, start, pIndex-1); 189 | quickSort(array, pIndex+1, end); 190 | } 191 | } 192 | 193 | private static int partition(int[] array, int start, int end) { 194 | int pivot = array[end]; 195 | int pIndex = start; 196 | for(int i=start; i charCountMap = new HashMap(); 338 | 339 | for(char c : str1.toCharArray()) { 340 | Character cTemp = new Character(c); 341 | if (charCountMap.containsKey(cTemp)) 342 | charCountMap.put(cTemp, new Integer(charCountMap.get(cTemp) + 1)); 343 | else charCountMap.put(cTemp, new Integer(1)); 344 | } 345 | 346 | for(char c : str2.toCharArray()) { 347 | Character cTemp = new Character(c); 348 | if(!charCountMap.containsKey(cTemp) || charCountMap.get(cTemp) == 0) 349 | return false; 350 | } 351 | 352 | return true; 353 | } 354 | 355 | private static void urlify(char[] str, int length) { 356 | int spaceCount = 0, index = 0; 357 | 358 | //Count number of spaces in given length to add space 359 | for(int i=0; i= 0; i--) { 367 | if(str[i] == ' ') { 368 | str[index - 1] = '0'; 369 | str[index - 2] = '2'; 370 | str[index - 3] = '%'; 371 | index = index - 3; 372 | } else { 373 | str[index-1] = str[i]; 374 | index--; 375 | } 376 | } 377 | 378 | } 379 | 380 | private static boolean isPermutationPalindrome(String str) { 381 | HashMap charCountMap = new HashMap(); 382 | 383 | //Count Chars 384 | for(int i=0; i < str.length(); i++) { 385 | Character cTemp = new Character(str.charAt(i)); 386 | int count = (charCountMap.containsKey(cTemp)) ? 387 | charCountMap.get(cTemp).intValue() + 1 : 1; 388 | charCountMap.put(cTemp, count); 389 | } 390 | 391 | //look for odd counts (cannot be greater than 1) 392 | boolean foundOdd = false; 393 | for(Character c : charCountMap.keySet()) { 394 | if(charCountMap.get(c).intValue() % 2 == 1) { 395 | if(foundOdd) return false; 396 | foundOdd = true; 397 | } 398 | } 399 | 400 | return true; 401 | } 402 | 403 | private static boolean isOneEditAway(String str1, String str2) { 404 | if(str2.length() > str1.length() + 1 || str2.length() < str1.length() - 1) { 405 | //String is too big or too small 406 | return false; 407 | } 408 | 409 | //if replacement 410 | if(str1.length() == str2.length()) { 411 | boolean charDifferentFound = false; 412 | for(int i=0; i < str1.length(); i++) { 413 | if(str1.charAt(i) != str2.charAt(i)){ 414 | if(charDifferentFound) return false; 415 | charDifferentFound = true; 416 | } 417 | } 418 | } else if(str1.length() > str2.length()) { 419 | //removal 420 | return isOneInsertAway(str2, str1); 421 | } else { 422 | //insertion 423 | return isOneInsertAway(str1, str2); 424 | } 425 | 426 | return true; 427 | } 428 | 429 | private static boolean isOneInsertAway(String str1, String str2) { 430 | int index1 = 0; 431 | int index2 = 0; 432 | 433 | while(index1 < str1.length() && index2 < str2.length()) { 434 | if(str1.charAt(index1) != str2.charAt(index2)) { 435 | if(index1 != index2) return false; 436 | index2++; 437 | } else { 438 | index1++; 439 | index2++; 440 | } 441 | } 442 | 443 | return true; 444 | } 445 | 446 | private static String basicStringCompression(String str) { 447 | StringBuilder compressed = new StringBuilder(); 448 | int countConsecutive = 0; 449 | for(int i=0; i < str.length(); i++) { 450 | countConsecutive++; 451 | if(i+1 >= str.length() || str.charAt(i) != str.charAt(i+1)) { 452 | compressed.append(str.charAt(i)); 453 | compressed.append(countConsecutive); 454 | countConsecutive = 0; 455 | } 456 | } 457 | 458 | return (compressed.length() < str.length()) ? compressed.toString() : str; 459 | } 460 | 461 | private static int reverseInt(int number) { 462 | int length = (int)(Math.log10(number)); 463 | int reversed = 0; 464 | while(number > 0) { 465 | int digit = number % 10; 466 | number /= 10; 467 | reversed += (digit * Math.pow(10.0, length)); 468 | length--; 469 | } 470 | 471 | return reversed; 472 | } 473 | 474 | private static String frequencySort(String s) { 475 | if(s.length() <= 1) return s; 476 | 477 | HashMap characterCount = new HashMap(); 478 | 479 | //Count Characters 480 | for(int i=0; i < s.length(); i++) { 481 | Character c = new Character(s.charAt(i)); 482 | int count = (characterCount.containsKey(c)) ? 483 | characterCount.get(c).intValue() + 1 : 1; 484 | characterCount.put(c, count); 485 | } 486 | 487 | //Bucket Sort 488 | List [] bucketList = new List[s.length() - 1]; 489 | for(Character c : characterCount.keySet()) { 490 | int count = characterCount.get(c); 491 | if(bucketList[count] == null) { 492 | bucketList[count] = new ArrayList(); 493 | } 494 | bucketList[count].add(c); 495 | } 496 | 497 | //Create sorted string 498 | StringBuilder sb = new StringBuilder(); 499 | for(int i=bucketList.length-1; i >= 0; i--) { 500 | if(bucketList[i] != null) { 501 | for(Character c : bucketList[i]) { 502 | for(int j=0; j < characterCount.get(c); j++) { 503 | sb.append(c); 504 | } 505 | } 506 | } 507 | } 508 | 509 | return sb.toString(); 510 | } 511 | 512 | private static List topKFrequent(int[] nums, int k) { 513 | if(nums.length <= k) { 514 | List intList = new ArrayList(); 515 | for (int index = 0; index < nums.length; index++) 516 | { 517 | intList.add(nums[index]); 518 | } 519 | return intList; 520 | } 521 | HashMap numCount = new HashMap(); 522 | 523 | //Count numbers 524 | for(int i=0; i[] countBuckets = new List[nums.length]; 532 | for(Integer i : numCount.keySet()) { 533 | if(countBuckets[numCount.get(i)] == null) { 534 | countBuckets[numCount.get(i)] = new ArrayList(); 535 | } 536 | countBuckets[numCount.get(i)].add(i); 537 | } 538 | 539 | //Create return list 540 | int returnSize = 0; 541 | ArrayList ret = new ArrayList(); 542 | for(int i=countBuckets.length-1; i >=0; i--) { 543 | if(countBuckets[i] != null) { 544 | for(Integer num : countBuckets[i]) { 545 | ret.add(num); 546 | returnSize++; 547 | if(returnSize >= k) return ret; 548 | } 549 | } 550 | } 551 | 552 | return ret; 553 | } 554 | 555 | public static String convert(String s, int numRows) { 556 | if(s == null) return ""; 557 | if(s.isEmpty() || s.length() == 1) return s; 558 | char[] charArray = s.toCharArray(); 559 | char[][] charMatrix = new char[numRows][s.length()]; 560 | 561 | int i=0,col=0; 562 | while(i < s.length()) { 563 | //down 564 | for(int j=0; j < numRows && i < s.length(); j++) { 565 | System.out.println("i: " + i + ", j: " + j + ", col: " + col); 566 | charMatrix[j][col] = charArray[i]; 567 | i++; 568 | } 569 | 570 | //across 571 | col++; 572 | for(int j=numRows-2; j > 0 && i < s.length(); j--) { 573 | System.out.println("i: " + i + ", j: " + j + ", col: " + col); 574 | charMatrix[j][col] = charArray[i]; 575 | i++; 576 | col++; 577 | } 578 | } 579 | 580 | //Copy characters to string 581 | StringBuilder sb = new StringBuilder(); 582 | for(int j=0; j < charMatrix.length; j++) { 583 | for(int k=0; k < charMatrix[0].length; k++) { 584 | if(charMatrix[j][k] != '\u0000') sb.append(charMatrix[j][k]); 585 | } 586 | } 587 | 588 | return sb.toString(); 589 | } 590 | 591 | public static String convertTwo(String s, int nRows) { 592 | if(nRows <= 1) return s; 593 | String result = ""; 594 | //the size of a cycle(period) 595 | int cycle = 2 * nRows - 2; 596 | for(int i = 0; i < nRows; ++i) 597 | { 598 | for(int j = i; j < s.length(); j = j + cycle){ 599 | result = result + s.charAt(j); 600 | int secondJ = (j - i) + cycle - i; 601 | if(i != 0 && i != nRows-1 && secondJ < s.length()) 602 | result = result + s.charAt(secondJ); 603 | } 604 | } 605 | return result; 606 | } 607 | 608 | public static String intToRoman(int num) { 609 | String[] thousands = new String[] {"", "M", "MM", "MMM"}; 610 | String[] hundreds = new String[] {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 611 | String[] tens = new String[] {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 612 | String[] ones = new String[] {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 613 | return thousands[num/1000] + hundreds[(num%1000)/100] + tens[(num%100)/10] + ones[(num%10)]; 614 | } 615 | 616 | public static int romanToInt(String s) { 617 | int num = 0, i = 0; 618 | char[] c = s.toCharArray(); 619 | while(i < c.length) { 620 | if(c[i] == 'M') num += 1000; 621 | else if(c[i] == 'D') num += 500; 622 | else if(c[i] == 'C') { 623 | if(i < c.length - 1 && (c[i+1] == 'M' || c[i+1] == 'D')) { 624 | num += (c[i+1] == 'M') ? 900 : 400; 625 | i++; 626 | } else { 627 | num += 100; 628 | } 629 | } else if (c[i] == 'X') { 630 | if(i < c.length - 1 && (c[i+1] == 'C' || c[i+1] == 'L')) { 631 | num += (c[i+1] == 'C') ? 90 : 40; 632 | i++; 633 | } else { 634 | num += 10; 635 | }; 636 | } else if (c[i] == 'I'){ 637 | if(i < c.length - 1 && (c[i+1] == 'X' || c[i+1] == 'V')) { 638 | num += (c[i+1] == 'X') ? 9 : 4; 639 | i++; 640 | } else { 641 | num += 1; 642 | } 643 | } else { 644 | num += (c[i] == 'D') ? 500 : (c[i] == 'L') ? 50 : 5; 645 | } 646 | if(i < c.length) i++; 647 | } 648 | 649 | return num; 650 | } 651 | } 652 | -------------------------------------------------------------------------------- /src/StackProblems.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.Stack; 4 | 5 | public class StackProblems { 6 | public static class StackWithMin extends Stack { 7 | public void push(int value) { 8 | super.push(new NodeWithMin(value, Math.min(value, min()))); 9 | } 10 | 11 | public int min() { 12 | if(this.isEmpty()) return Integer.MAX_VALUE; 13 | return peek().min; 14 | } 15 | } 16 | 17 | private static class NodeWithMin { 18 | public int value; 19 | public int min; 20 | public NodeWithMin(int value, int min) { 21 | this.value = value; 22 | this.min = min; 23 | } 24 | } 25 | 26 | public static class StackWithCapacity extends Stack { 27 | int capacity; 28 | 29 | public StackWithCapacity(int capacity) { 30 | super(); 31 | this.capacity = capacity; 32 | } 33 | 34 | public boolean isFull() { 35 | return size() >= capacity; 36 | } 37 | } 38 | 39 | public class AnimalShelter { 40 | LinkedList cats = new LinkedList<>(); 41 | LinkedList dogs = new LinkedList<>(); 42 | int order = 0; 43 | 44 | public void enqueue(Animal a) { 45 | a.setOrder(order); 46 | order++; 47 | if(a.type == AnimalType.CAT) { 48 | cats.add(a); 49 | } else { 50 | dogs.add(a); 51 | } 52 | } 53 | 54 | public Animal dequeueAny() throws Exception { 55 | if(cats.isEmpty() && dogs.isEmpty()) throw new Exception("Empty Shelter"); 56 | if(cats.isEmpty()) return dogs.removeFirst(); 57 | if(dogs.isEmpty()) return cats.removeFirst(); 58 | 59 | //Both have animals 60 | if(cats.getFirst().getOrder() < dogs.getFirst().getOrder()) return cats.removeFirst(); 61 | return dogs.removeFirst(); 62 | } 63 | 64 | public Animal dequeueCat() throws Exception { 65 | if(cats.isEmpty()) throw new Exception("No cats."); 66 | return cats.removeFirst(); 67 | } 68 | 69 | public Animal dequeueDog() throws Exception { 70 | if(dogs.isEmpty()) throw new Exception("No dogs."); 71 | return dogs.removeFirst(); 72 | } 73 | } 74 | 75 | public class Animal { 76 | 77 | public AnimalType type; 78 | private int order; 79 | 80 | public Animal(AnimalType type) { 81 | this.type = type; 82 | } 83 | 84 | public int getOrder() { 85 | return order; 86 | } 87 | 88 | public void setOrder(int order) { 89 | this.order = order; 90 | } 91 | } 92 | 93 | public enum AnimalType { 94 | CAT, 95 | DOG 96 | } 97 | 98 | public static class SetOfStacks { 99 | ArrayList stacks = new ArrayList(); 100 | int capacity = 0; 101 | 102 | public SetOfStacks(int capacity) { 103 | this.capacity = capacity; 104 | } 105 | 106 | private StackWithCapacity getLastStack() { 107 | if(stacks.size() == 0) { 108 | stacks.add(new StackWithCapacity(capacity)); 109 | } 110 | return stacks.get(stacks.size() - 1); 111 | } 112 | 113 | public boolean isEmpty() { 114 | return getLastStack().isEmpty(); 115 | } 116 | 117 | public void push(int value) { 118 | StackWithCapacity currentStack = getLastStack(); 119 | if(!currentStack.isFull()) { 120 | currentStack.push(value); 121 | } else { 122 | StackWithCapacity newStack = new StackWithCapacity(capacity); 123 | newStack.push(value); 124 | stacks.add(newStack); 125 | } 126 | } 127 | 128 | public int pop() throws Exception { 129 | StackWithCapacity currentStack = getLastStack(); 130 | if(currentStack.isEmpty()) throw new Exception("Empty Stack"); 131 | int value = currentStack.pop(); 132 | if(currentStack.size() == 0) stacks.remove(stacks.size() - 1); 133 | return value; 134 | } 135 | 136 | public int popAt(int index) { 137 | StackWithCapacity stackAtIndex = stacks.get(index); 138 | int value = stackAtIndex.pop(); 139 | if(stackAtIndex.size() == 0) stacks.remove(stackAtIndex); 140 | return value; 141 | } 142 | } 143 | 144 | public static void sortStack(Stack inputStack) { 145 | Stack sortedStack = new Stack(); 146 | while(!inputStack.isEmpty()) { 147 | int temp = inputStack.pop(); 148 | while(!sortedStack.isEmpty() && sortedStack.peek() > temp) { 149 | inputStack.push(sortedStack.pop()); 150 | } 151 | sortedStack.push(temp); 152 | } 153 | 154 | //Copy the elements from R back into s 155 | while(!sortedStack.isEmpty()) { 156 | inputStack.push(sortedStack.pop()); 157 | } 158 | } 159 | 160 | public static void printStack(Stack s) { 161 | Stack tempStack = new Stack(); 162 | while(!s.isEmpty()) { 163 | int temp = s.pop(); 164 | System.out.print(temp + ", "); 165 | tempStack.push(temp); 166 | } 167 | 168 | //Copy Elements back 169 | while(!tempStack.isEmpty()) { 170 | s.push(tempStack.pop()); 171 | } 172 | } 173 | } 174 | --------------------------------------------------------------------------------