├── .gitignore ├── AlgorithmsAndProblems ├── InverseLevelOrderTreeTraversal.java ├── IsIntPalindrome.java ├── ReverseInteger.java ├── findConnectingFlights.java ├── findIndexWeights.java ├── multiplyIndicesInArray.java ├── returnLastNDigits.java ├── spiralMatrix.java └── towersOfHanoiRecursive.java ├── DataStructures ├── ArraysAndStrings │ ├── Anagram │ │ └── IsAnagram.java │ ├── BinarySearch │ │ └── binarySearchAnArray.java │ ├── RandsomProblem │ │ └── RandsomProblem.java │ ├── RemoveDuplicates │ │ └── RemoveDuplicateChars.java │ ├── ReverseWords │ │ └── reverseWords.java │ ├── SubstringCheck │ │ └── checkSubstring.java │ └── UniqueCharsInString │ │ └── isCharUnique.java ├── LinkedLists │ ├── doublyLinkedList │ │ └── doubleyLinkedList.java │ ├── findNthToLastElement │ │ └── findNthToLastElement.java │ ├── removeDuplicates │ │ └── LinkedListRemoveDups.java │ ├── singlyLinkedList │ │ ├── deleteNodeLinkedList.java │ │ └── singlyLinkedList.java │ └── sortedSinglyLinkedList │ │ └── sortedLinkedList.java └── StacksAndQueues │ ├── Queue │ ├── simpleArrayQueue.java │ └── twoQueuesComparison.java │ ├── Stack │ ├── simpleStack.java │ ├── sortStackAscending.java │ ├── stackAndBracketChecker.java │ └── twoStacksOneQueue.java │ └── linkedListStack │ └── linkedListStack.java ├── README.md └── Recursion ├── Permutations.java ├── recursiveBSearch.java └── triangularNumbersRecursion.java /.gitignore: -------------------------------------------------------------------------------- 1 | /AlgorithmsAndProblems/findOverlapInRanges.java 2 | /AlgorithmsAndProblems/KnightsTour.java 3 | /AlgorithmsAndProblems/MergeOverlappingIntervals.java 4 | /AlgorithmsAndProblems/MergeStringIntervals.java -------------------------------------------------------------------------------- /AlgorithmsAndProblems/InverseLevelOrderTreeTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | /* 5 | Given the following tree, perform a Level Order Inverse traversal of the 6 | binary tree and print it out. 7 | 8 | 10 9 | 6 15 10 | 22 17 35 11 | 1 65 12 54 12 | 13 | 14 | Output should be: 15 | 1 16 | 65 17 | 12 18 | 54 19 | 22 20 | 17 21 | 35 22 | 6 23 | 15 24 | 10 25 | 26 | */ 27 | 28 | public class InverseLevelOrderTreeTraversal{ 29 | 30 | public static void main(String[] args){ 31 | 32 | TreeNode root = buildTree(); 33 | //new InverseLevelOrderTreeTraversal().printInOrder(root); 34 | new InverseLevelOrderTreeTraversal().printLevelOrderInverseTraversal(root); 35 | } 36 | 37 | 38 | //Lazy build of a tree. 39 | private static TreeNode buildTree(){ 40 | TreeNode root = new TreeNode(10); 41 | TreeNode nodeR1 = new TreeNode(15); 42 | TreeNode nodeL1 = new TreeNode(6); 43 | TreeNode nodeRR2 = new TreeNode(35); 44 | TreeNode nodeRL2 = new TreeNode(17); 45 | TreeNode nodeLL2 = new TreeNode(22); 46 | TreeNode leafLL = new TreeNode(1); 47 | TreeNode leafRL = new TreeNode(65); 48 | TreeNode leafRR1 = new TreeNode(12); 49 | TreeNode leafRR2 = new TreeNode(54); 50 | 51 | root.right = nodeR1; 52 | root.left = nodeL1; 53 | nodeL1.left = nodeLL2; 54 | nodeLL2.left = leafLL; 55 | nodeR1.left = nodeRL2; 56 | nodeR1.right = nodeRR2; 57 | nodeRL2.left = leafRL; 58 | nodeRR2.left = leafRR1; 59 | nodeRR2.right = leafRR2; 60 | 61 | return root; 62 | } 63 | 64 | 65 | /* This method prints out the tree in Inverse Level Order Traversal. 66 | It does so by somewhat of a breadth-first search, adding the next 67 | level nodes to a queue. After checking each child node and adding 68 | to the queue, the root will be pushed to a stack. 69 | This essentially adds (starting from the left), each level of 70 | nodes in the binary tree to a stack. When we are done, popping 71 | the stack will print out the binary tree in inverse level order, 72 | starting at the bottom, right-most node. 73 | */ 74 | public void printLevelOrderInverseTraversal(TreeNode root){ 75 | if(root != null){ 76 | Stack stack = new Stack<>(); 77 | Queue queue = new LinkedList<>(); 78 | 79 | //Add our root to the queue 80 | queue.add(root); 81 | 82 | while(!queue.isEmpty()){ 83 | 84 | //Get root object, removing it from the queue 85 | root = queue.poll(); 86 | 87 | //If root has a right child, add it to the queue 88 | if(root.right != null){ 89 | queue.offer(root.right); 90 | } 91 | 92 | //If root has a left child, add it to the queue 93 | if(root.left != null){ 94 | queue.offer(root.left); 95 | } 96 | 97 | //Push root to the queue 98 | stack.push(root); 99 | } 100 | 101 | while(!stack.isEmpty()){ 102 | System.out.println(stack.pop().value); 103 | } 104 | } 105 | } 106 | 107 | 108 | //TreeNode class which contains data, left and right node fields 109 | static class TreeNode{ 110 | int value; 111 | TreeNode left; 112 | TreeNode right; 113 | 114 | public TreeNode(int val){ 115 | value = val; 116 | } 117 | } 118 | } -------------------------------------------------------------------------------- /AlgorithmsAndProblems/IsIntPalindrome.java: -------------------------------------------------------------------------------- 1 | 2 | /* This algorithm returns true if the inputted integer is a palindrome, 3 | and false if not. 4 | */ 5 | 6 | 7 | class IsIntPalindrome { 8 | 9 | public static void main(String[] args){ 10 | int number = 12321; 11 | boolean palindrome = isPalindrome(number); 12 | System.out.println(palindrome); 13 | } 14 | 15 | public static boolean isPalindrome(int n){ 16 | //Negative numbers can't be palindromes 17 | if(n < 0){ 18 | return false; 19 | } 20 | 21 | //Initiliaze amount of zero's the number should contain 22 | int divider = 1; 23 | while(n / divider >= 10){ 24 | divider *= 10; 25 | } 26 | 27 | while(n != 0){ 28 | int left = n / divider; 29 | int right = n % 10; 30 | 31 | if(left != right){ 32 | return false; 33 | } 34 | 35 | n = (n % divider) / 10; 36 | divider /= 100; 37 | } 38 | 39 | return true; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /AlgorithmsAndProblems/ReverseInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a method that reverses an integer. No extra buffers or space allowed. 3 | Return 0 for Integer-overflow case 4 | */ 5 | 6 | 7 | 8 | public class ReverseInteger{ 9 | 10 | public static void main(String[] args){ 11 | int reversed = reverse(124243245); 12 | 13 | System.out.println(reversed); 14 | } 15 | 16 | public static int reverse(int num){ 17 | long rev = 0; 18 | 19 | while(num != 0){ 20 | rev = rev*10 + num%10; 21 | num = num/10; 22 | 23 | if(rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE){ 24 | return 0; 25 | } 26 | } 27 | 28 | if(num < 0){ 29 | return (int) -rev; 30 | } 31 | else{ 32 | return (int) rev; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /AlgorithmsAndProblems/findConnectingFlights.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two unsorted lists of String destinations and sources, sort the flights from start to end. 3 | No two flights are the same, and they are all one-way. Two destinations are never visited more than once. 4 | 5 | Our flights are arranged so that the first index of each subarray is the departure, and the second index 6 | of each subarray is the arrival 7 | */ 8 | 9 | import java.util.*; 10 | 11 | public class findConnectingFlights{ 12 | private static final int DEPARTURE_INDEX = 0; 13 | private static final int ARRIVAL_INDEX = 1; 14 | 15 | public static void main(String[] args){ 16 | String[][] flightsArr = {{"SFO","LAX"}, {"JSA","XGW"}, {"PXY","HTA"}, {"XGW","PXY"},{"LAX","JSA"}}; 17 | 18 | //Our starting flight 19 | int startIndex = findStartPointIndex(flightsArr); 20 | 21 | if(startIndex >= 0){ 22 | 23 | //Our starting flight set 24 | String[] startFlights = flightsArr[startIndex]; 25 | 26 | LinkedListNode head = createSortedLinkedList(flightsArr, startFlights); 27 | 28 | //Print out our linked list! 29 | while(head.next != null){ 30 | head.printNode(); 31 | head = head.next; 32 | } 33 | } 34 | else{ 35 | System.out.println("Sorry, starting flight doesn't exist."); 36 | } 37 | 38 | } 39 | 40 | 41 | public static int findStartPointIndex(String[][] flights){ 42 | 43 | //Create a hashtable and set key to the arrivals 44 | Hashtable arrivalTable = new Hashtable<>(); 45 | 46 | for(int i = 0; i < flights.length; i++){ 47 | arrivalTable.put(flights[i][ARRIVAL_INDEX], flights[i][DEPARTURE_INDEX]); 48 | } 49 | 50 | //Go through array and see if our departure exists as an arrival, if not, we have our start point 51 | for(int i = 0; i < flights.length; i++){ 52 | if(!arrivalTable.containsKey(flights[i][DEPARTURE_INDEX])){ 53 | return i; 54 | } 55 | } 56 | 57 | return -1; 58 | } 59 | 60 | 61 | public static LinkedListNode createSortedLinkedList(String[][] flights, String[] start){ 62 | 63 | //Create a hashtable and set key to the departures 64 | Hashtable departureTable = new Hashtable<>(); 65 | 66 | for(int i = 0; i < flights.length; i++){ 67 | departureTable.put(flights[i][DEPARTURE_INDEX], flights[i][ARRIVAL_INDEX]); 68 | } 69 | 70 | //Create a variable to hold our current arrival and list node as we go through the hash table 71 | String currentArrival = start[ARRIVAL_INDEX]; 72 | LinkedListNode current = new LinkedListNode(start[DEPARTURE_INDEX], start[ARRIVAL_INDEX]); 73 | LinkedListNode head = current; 74 | 75 | //Loop through our flights and create a linked list from the departures and arrivals 76 | for(int i = 0; i < flights.length; i++){ 77 | //Use our arrival to find the next linked departure 78 | String currentDeparture = departureTable.get(currentArrival); //HTA 79 | 80 | //Add it to the linked list (switch since our departure is now our arrival and vise versa) 81 | LinkedListNode temp = new LinkedListNode(currentArrival, currentDeparture); 82 | temp.previous = current; 83 | current.next = temp; 84 | current = temp; 85 | 86 | //Set our currentArrival to our new currentDeparture 87 | currentArrival = currentDeparture; //current arrival is now PXY 88 | } 89 | 90 | //return head of linked list 91 | return head; 92 | } 93 | 94 | } 95 | 96 | 97 | class LinkedListNode{ 98 | String dep; 99 | String arrival; 100 | LinkedListNode next = null; 101 | LinkedListNode previous = null; 102 | 103 | public LinkedListNode(String d, String a){ 104 | dep = d; 105 | arrival = a; 106 | } 107 | 108 | public String getDep(){ 109 | return dep; 110 | } 111 | 112 | public String getArrival(){ 113 | return arrival; 114 | } 115 | 116 | public void printNode(){ 117 | System.out.println("DEPT: " + dep + "; ARR: " + arrival); 118 | } 119 | } -------------------------------------------------------------------------------- /AlgorithmsAndProblems/findIndexWeights.java: -------------------------------------------------------------------------------- 1 | class findIndexWeights { 2 | public static void main(String[] args) { 3 | int[] arr = [1,2,4,3,2,6,43,25,14,35]; 4 | int limit = 4; 5 | findLimit(arr, limit); 6 | } 7 | 8 | public static int[] findLimit(int[] arr, int limit){ 9 | 10 | int length = arr.length; 11 | int previous = 0; 12 | int current = 1; 13 | int key; 14 | HashTable hashTable = new HashTable<>(); 15 | 16 | for(int i = 0; i < length - 1; i++){ 17 | key = limit - arr[i]; 18 | if(!hashTable.hasKey(key){ 19 | hashTable.insert(arr[i], i); 20 | } 21 | else{ 22 | return [hashTable.getValue(key), i]; 23 | } 24 | } 25 | return -1; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /AlgorithmsAndProblems/multiplyIndicesInArray.java: -------------------------------------------------------------------------------- 1 | class Pramp { 2 | public static void main(String[] args) { 3 | String pramp = "Practice Makes Perfect"; 4 | System.out.println(pramp); 5 | } 6 | 7 | public static int[] multiplyIndices(int[] arr){ 8 | int length = arr.length; 9 | int[] multiplesArr = new int[length]; 10 | 11 | for(int i = 0; i < length; i++){ 12 | int totalVals = 1; 13 | for(int j = 0; j < length; j++){ 14 | if(i != j){ 15 | totalsVals *= arr[i]; 16 | } 17 | } 18 | multiplesArr[i] = totalVals; 19 | } 20 | 21 | return multiplesArr; 22 | } 23 | 24 | 25 | public static int[] betterMultiplyIndices(int[] arr){ 26 | int length = arr.length; 27 | int[] la = new int[length]; 28 | int[] ra = new int[length]; 29 | int[] sum = new int[length]; 30 | 31 | int product = 1; 32 | for(int i = 0; i < length; i++) { 33 | la[i] = product; 34 | product*=arr[i]; 35 | } 36 | 37 | product = 1; 38 | for(int i = length -1; i >= 0; i--){ 39 | ra[i] = product; 40 | product*=arr[i]; 41 | } 42 | 43 | for(int i = 0; i solution(int[][] matrix){ 23 | 24 | List items = new ArrayList<>(); 25 | 26 | if(matrix == null || matrix.length == 0){ 27 | return items; 28 | } 29 | int topRow = 0; 30 | int bottomRow = matrix.length-1; 31 | int leftCol = 0; 32 | int rightCol = matrix[0].length-1; 33 | 34 | 35 | while(topRow <= bottomRow && leftCol <= rightCol){ 36 | 37 | if(bottomRow == 0){ 38 | for(int i = leftCol; i < rightCol+1; i++){ 39 | System.out.println("value:" + matrix[topRow][i]); 40 | items.add(matrix[topRow][i]); 41 | } 42 | System.out.println("Returning #1"); 43 | return items; 44 | } 45 | else if(rightCol == 0){ 46 | for(int i = topRow; i < bottomRow+1; i++){ 47 | items.add(matrix[i][rightCol]); 48 | } 49 | System.out.println("Returning #2"); 50 | return items; 51 | } 52 | 53 | //Top row 54 | for(int i = leftCol; i <= rightCol; i++){ 55 | items.add(matrix[topRow][i]); 56 | } 57 | topRow++; 58 | 59 | //Right col 60 | for(int i = topRow; i <= bottomRow; i++){ 61 | items.add(matrix[i][rightCol]); 62 | } 63 | rightCol--; 64 | 65 | //bottom row 66 | if(topRow <= bottomRow){ 67 | for(int i = rightCol; i <= leftCol; i--){ 68 | items.add(matrix[bottomRow][i]); 69 | } 70 | bottomRow--; 71 | } 72 | 73 | //left col 74 | if(leftCol <= rightCol){ 75 | for(int i = bottomRow; i <= topRow; i--){ 76 | items.add(matrix[i][leftCol]); 77 | } 78 | leftCol++; 79 | } 80 | } 81 | System.out.println("Returning #3"); 82 | return items; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /AlgorithmsAndProblems/towersOfHanoiRecursive.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | 3 | public static void main(String[] args) { 4 | int nDisks = 3; 5 | doTowers(nDisks, 'A', 'B', 'C'); 6 | } 7 | 8 | doTowers(3, A B C); //START 9 | doTowers(2 A C B); //line 4 10 | doTowers(1 A B C); //line 4 11 | stack = (3 A B C, 2 A C B, 1 A B C); 12 | //-> print 1 A B C in line 1 13 | pop(1, A B C); 14 | stack = (3 A B C, 2 A C B); 15 | //-> print 2 A C B in line 5 16 | doTowers(1 C A B); //line 6 17 | stack = (3 A B C, 2 A C B, 1 C A B); 18 | //-> print 1 C A B in line 1 19 | pop(1 C A B); 20 | pop(2 A C B); 21 | stack = (3 A B C); 22 | //-> print 3 A B C in line 5 23 | doTowers(2 B A C); 24 | stack = (3 A B C, 2 B A C); 25 | doTowers(1 B C A); 26 | stack = (3 A B C, 2 B A C, 1 B C A); 27 | //-> print 1 B CA in line 1 28 | pop(1 B C A); 29 | stack = (3 A B C, 2 B A C); 30 | //-> print 2 B A C in line 5 31 | doTowers(1 A B C); 32 | stack = (3 A B C, 2 B A C, 1 A B C); 33 | //-> print 1 A B C in line 1 34 | pop(1 A B C); 35 | pop(2 B A C); 36 | pop(3 A B C); 37 | 38 | 39 | public static void doTowers(int topN, char from, char inter, char to){ 40 | if(topN == 1) { //line 1 41 | System.out.println("Disk 1 from " + from + " to " + to);//line 2 42 | } 43 | else{ //line 3 44 | doTowers(topN -1, from, to, inter); //line 4 45 | System.out.println("Disk " + topN + " from " + from + " to " + to); //line5 46 | doTowers(topN - 1, inter, from, to); //line6 47 | } 48 | } 49 | } 50 | 51 | 52 | 53 | 54 | 3,4,3,4,1,2,5,6,3,4,1,2,5,6,1,2,5,6,1,2 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | Disk 1 from A to C --> line 1 63 | Disk 2 from A to B --> line 5 64 | Disk 1 from C to B --> line 1 65 | Disk 3 from A to C --> line 5 66 | Disk 1 from B to A --> line 1 67 | Disk 2 from B to C --> line 5 68 | Disk 1 from A to C --> line 1 69 | -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/Anagram/IsAnagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | //Determine if one string is an anagram of another 5 | 6 | 7 | class Main { 8 | 9 | public static void main(String[] args){ 10 | boolean isAnagram = anagram("some", "emos"); 11 | System.out.println(String.valueOf(isAnagram)); 12 | } 13 | 14 | public static boolean anagram(String s, String t) { 15 | return sort(s).equals(sort(t)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/BinarySearch/binarySearchAnArray.java: -------------------------------------------------------------------------------- 1 | //Binary search for an array 2 | 3 | 4 | 5 | Class Main { 6 | 7 | public static void main(String[] args){ 8 | int[] myArray = new int[256]; 9 | for(i = 0; i < myArray.length; i++){ 10 | myArray[i] = i; 11 | } 12 | 13 | binarySearch(myArray, 35); //should return the int 34 14 | 15 | } 16 | 17 | 18 | public static int binarySearch(int[] array, int value){ 19 | int median; 20 | int lowerbound = 0; 21 | int upperbound = array.length - 1 22 | 23 | while(lowerbound < upperbound){ 24 | median = (lowerbound + upperbound) / 2; 25 | 26 | if(value == array[median]){ 27 | return array.indexOf(median) 28 | } 29 | else{ 30 | if(value < array[median]){ 31 | upperBound = median - 1; 32 | } 33 | else if(value > array[median]){ 34 | lowerBound = median + 1; 35 | } 36 | } 37 | } 38 | return -1; 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/RandsomProblem/RandsomProblem.java: -------------------------------------------------------------------------------- 1 | //Randsom Problem 2 | 3 | 4 | class Main { 5 | 6 | public static void main(String[] args){ 7 | String magazine = "This is a magazine that has a lot of different letters"; 8 | String note = "He is mine"; 9 | boolean isPossible = isNotePossible(note.toLowerCase(), magazine.toLowerCase()); 10 | System.out.println(String.valueOf(isPossible)); 11 | } 12 | 13 | 14 | public static boolean isNotePossible(String note, String magazine) { 15 | 16 | int[] containsLetters = new int[256]; 17 | 18 | for(int i = 0; i < magazine.length(); i++){ 19 | int val = (int) (magazine.charAt(i)); 20 | containsLetters[val]++; 21 | } 22 | 23 | for(int j = 0; j < note.length(); j++){ 24 | int val = (int) (note.charAt(j)); 25 | containsLetters[val]--; 26 | if(containsLetters[val] < 0){ 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | 33 | 34 | 35 | } -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/RemoveDuplicates/RemoveDuplicateChars.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /* 4 | Design an algorithm to remove the duplicate characters in a string without using any additional buffer. 5 | One or two additional variables are fine, but an extra copy of the array is not. 6 | */ 7 | 8 | class Main { 9 | 10 | public static void main(String[] args){ 11 | String myString = "asdfnsdfnsdfksdf"; 12 | removeDuplicateChars(myString); 13 | } 14 | 15 | 16 | 17 | public static void removeDuplicateChars(String str){ 18 | //Convert string to char array (we could always use str.charAt as well) 19 | char[] chars = str.toCharArray(); 20 | 21 | if (chars == null) return; 22 | if(chars.length < 2) return; 23 | 24 | //Using a HashSet only enters non-duplicates. Making it linked retains the order 25 | Set charSet = new LinkedHashSet(); 26 | for(char c : chars){ 27 | charSet.add(c); 28 | } 29 | 30 | 31 | //Print out the non-duplicates 32 | Iterator itr = charSet.iterator(); 33 | while(itr.hasNext()){ 34 | System.out.println(itr.next()); 35 | } 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/ReverseWords/reverseWords.java: -------------------------------------------------------------------------------- 1 | class Pramp { 2 | public static void main(String[] args) { 3 | String pramp = "Practice Makes Perfect"; 4 | System.out.println(pramp); 5 | } 6 | 7 | 8 | 9 | public static String betterReverseString(String input){ 10 | String[] words = input.split(" "); 11 | String rev = ""; 12 | 13 | for(int i = words.length() -1; i >= 0; i--){ 14 | rev += words[i] + " "; 15 | } 16 | } 17 | 18 | 19 | 20 | public static String reverseString(String input){ 21 | char[] chArray = input.toCharArray(); 22 | char delimeter = " "; 23 | int start = 0; 24 | 25 | chArray = reverse(chArray, start, chArray.length -1); 26 | 27 | for(int i = 0; i < ch.Array.length; i++){ 28 | if(chArray[i] == delimeter){ 29 | int end = i-1; 30 | reverse(chArray, start, end); 31 | start = end + 1; 32 | } 33 | } 34 | } 35 | 36 | 37 | 38 | public static char[] reverse(char[] chArray, int start, int end){ 39 | for(; start < end; start ++, end--){ 40 | char temp = chArray[start]; 41 | chArray[start] = chArray[end]; 42 | chArray[end] = temp; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/SubstringCheck/checkSubstring.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | //Assume you have a method isSubstring that checks if one word is a substring of another. Given 5 | //Two string, s1 and s2, wrote code to check if s2 is a rotation of s1 using only one call to 6 | //isSubstring 7 | 8 | 9 | class Main { 10 | 11 | public static void main(String[] args){ 12 | isRotation("apple", "pleap"); 13 | } 14 | 15 | public static boolean isRotation(String s1, String s2){ 16 | int len = s1.length(); 17 | 18 | if(len == s2.length() && len > 0) { 19 | String s1s1 = s1 + s1; 20 | return isSubstring(s1s1, s2); 21 | } 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /DataStructures/ArraysAndStrings/UniqueCharsInString/isCharUnique.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | public static void main(String[] args) { 3 | String helloString = args[0]; 4 | System.out.println(isUnique(helloString)); 5 | } 6 | 7 | public static boolean isUnique(String s) { 8 | boolean[] charSet = new boolean[256]; 9 | for(int i = 0; i < s.length(); i++){ 10 | int val = s.charAt(i); 11 | if(charSet[val]){ 12 | System.out.println("Found duplicate. Duplicate Letter: " + Character.toString((char) val)); 13 | return false; 14 | } 15 | charSet[val] = true; 16 | } 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /DataStructures/LinkedLists/doublyLinkedList/doubleyLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //A doubly linked list that is also double-ended 4 | 5 | class Link{ 6 | public int data; 7 | public Link next; 8 | public Link previous; 9 | 10 | public Link(int d){ 11 | data = d; 12 | } 13 | 14 | public displayLink(){ 15 | System.out.println("Data: " + data); 16 | } 17 | } 18 | 19 | 20 | class DoublyLinkedList{ 21 | 22 | private Link first; 23 | private Link last; 24 | 25 | public DoublyLinkedList(){ 26 | first = null; 27 | last = null; 28 | } 29 | 30 | public boolean isEmpty(){ 31 | return first == null; 32 | } 33 | 34 | public void insertFirst(int data){ 35 | Link newLink = new Link(data); 36 | 37 | if(isEmpty()){ 38 | last = newLink; 39 | } 40 | else{ 41 | first.previous = newLink; 42 | } 43 | newLink.next = first; 44 | first = newLink; 45 | } 46 | 47 | public void insertLast(int data){ 48 | Link newLink = new Link(data); 49 | if(isEmpty){ 50 | first = newLink; 51 | } 52 | else{ 53 | last.next = newLink; 54 | newLink.previous = last; 55 | } 56 | last = newLink; 57 | } 58 | 59 | 60 | public Link deleteFirst(){ 61 | //Assuming a non-empty list 62 | Link temp = first; 63 | if(first.next == null){ 64 | last = null; 65 | } 66 | else{ 67 | first.next.previous = null; 68 | } 69 | first = first.next; 70 | return temp; 71 | } 72 | 73 | public Link deleteLast(){ 74 | Link temp = last; 75 | 76 | //if only one item in list 77 | if(first.next == null){ 78 | first = null; 79 | } 80 | else{ 81 | last.previous.next = null; 82 | } 83 | last = last.previous; 84 | return temp; 85 | } 86 | 87 | public boolean insertAfter(int key, int data){ 88 | Link current = first; 89 | 90 | while(current.data != key){ 91 | current = current.next; 92 | 93 | //didn't find the link 94 | if(current == null){ 95 | return false; 96 | } 97 | } 98 | 99 | Link newLink = new Link(data); 100 | 101 | if(current == last){ 102 | newLink.next = null; 103 | last = newLink; 104 | } 105 | else{ 106 | newLink.next = current.next; 107 | current.next.previous = newLink; 108 | } 109 | 110 | newLink.previous = current; 111 | current.next = newLink; 112 | return true; 113 | } 114 | 115 | public Link deleteKey(int key){ 116 | Link current = first; 117 | 118 | while(current.data != key){ 119 | current = current.next; 120 | if(current == null){ 121 | return null; 122 | } 123 | } 124 | 125 | if(current == first){ 126 | first = current.next; 127 | } 128 | else{ 129 | current.previous.next = current.next; 130 | } 131 | 132 | if(curent == last){ 133 | last = current.previous; 134 | } 135 | else{ 136 | current.next.previous = current.previous; 137 | } 138 | 139 | return current; 140 | } 141 | 142 | 143 | public void displayForward(){ 144 | Link current = first; 145 | 146 | while(current != null){ 147 | current.displayLink(); 148 | current = current.next; 149 | } 150 | } 151 | 152 | 153 | public void displayBackward(){ 154 | Link current = last; 155 | while(current != null){ 156 | current.displayLink(); 157 | current = current.previous; 158 | } 159 | } 160 | 161 | } -------------------------------------------------------------------------------- /DataStructures/LinkedLists/findNthToLastElement/findNthToLastElement.java: -------------------------------------------------------------------------------- 1 | import java.utils*; 2 | 3 | 4 | /* 5 | Implement an algorithm to find the nth to last element of a singly linked list 6 | 7 | Algorithm: 8 | 1. create two pointers, p1 and p2 9 | 2. Incremenet p2 by n-1 positions, making the distance between p1 and p2 equal to n. 10 | 3. If p2->next is equal to null, that means p2 is the last item, therefore p1 is n distance away from the last element 11 | 4. Else, keep incrementing p1 and p2 by 1 position until p2->null. 12 | */ 13 | 14 | 15 | 16 | 17 | 18 | class Main { 19 | 20 | private static void main(String[] args) { 21 | } 22 | 23 | 24 | private static LinkedListNode nthToLast(LinkedListNode head, int n){ 25 | if(head == null || n < 1){ 26 | return null; 27 | } 28 | 29 | LinkedListNode p1 = head; 30 | LinkedListNode p2 = head; 31 | 32 | //incremement p2 until we hit n-1 position (or until p2 is null) 33 | for(int j = 0; j < n-1; j++){ 34 | if(p2 == null) { 35 | return null; 36 | } 37 | p2 = p2.next; 38 | } 39 | 40 | //Incremement until p2->next is null. Only then will p1 be in the nth position 41 | //from the last node (since p2 is n-1 ahead of p1) 42 | while(p2.next != null){ 43 | p1 = p1.next; 44 | p2 = p2.next; 45 | } 46 | return p1; 47 | } 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/removeDuplicates/LinkedListRemoveDups.java: -------------------------------------------------------------------------------- 1 | import java.util*; 2 | 3 | 4 | /* 5 | Remove duplicates from an unsorted linked list 6 | */ 7 | 8 | 9 | class Main { 10 | 11 | public static void main(String[] args){ 12 | LinkedListNode node = new LinkedListNode(someData); 13 | deleteDups(node); 14 | } 15 | 16 | public static void deleteDups(LinkedListNode n) { 17 | Hashtable table = new Hashtable(); 18 | LinkedListNode previous = null; 19 | while(n != null){ 20 | if(table.containsKey(n.data)){ 21 | previous.next = n.next; 22 | } 23 | else{ 24 | table.put(n.data, true); 25 | previous = n; 26 | } 27 | n = n.next; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/singlyLinkedList/deleteNodeLinkedList.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | Node next = null; 3 | int data; 4 | 5 | public Node(int d){ 6 | this.data = d; 7 | } 8 | 9 | 10 | public void appendToTail(int d){ 11 | Node end = new Node(d); 12 | Node n = this; 13 | while(n.next != null){ 14 | n = n.next; 15 | } 16 | //After hitting last element, append our data to the tail 17 | n.next = end; 18 | } 19 | 20 | public Node deleteNode(Node head, int d){ 21 | Node n = head; 22 | 23 | if(n.data == d){ 24 | return head.next; //moved head 25 | } 26 | 27 | while(n.next != null){ 28 | if(n.next.data == d){ 29 | n.next = n.next.next; //We found our item! Time to replace with the one ahead of it 30 | return head; 31 | } 32 | n = n.next; //nullify n 33 | } 34 | return head; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /DataStructures/LinkedLists/singlyLinkedList/singlyLinkedList.java: -------------------------------------------------------------------------------- 1 | class Link { 2 | int key; 3 | int data; 4 | Link next; 5 | 6 | public Link(int key, int data){ 7 | this.key = key; 8 | this.data = data; 9 | } 10 | 11 | public void displayLink(){ 12 | System.out.println("\n{" + this.key + ", " + this.data + "}"); 13 | } 14 | } 15 | 16 | 17 | 18 | class LinkedList { 19 | private Link first; 20 | 21 | public LinkedList(){ 22 | first = null; 23 | } 24 | 25 | 26 | public void insertFirst(int key, int data){ 27 | Link newLink = new Link(key, data); 28 | newLink.next = first; 29 | first = newLink; 30 | } 31 | 32 | public Link find(int key){ 33 | Link current = first; 34 | while(current.key != key){ 35 | if(current.next == null){ 36 | return null; 37 | } 38 | else{ 39 | current = current.next; 40 | } 41 | } 42 | return current; 43 | } 44 | 45 | public Link delete(int key){ 46 | Link current = first; 47 | Link previous = first; 48 | 49 | while(current.key != key){ 50 | if(current.next == null){ 51 | return null; 52 | } 53 | else{ 54 | previous = current; 55 | current = current.next; 56 | } 57 | } 58 | 59 | if(current == first){ 60 | first = first.next; 61 | } 62 | else{ 63 | previous.next = current.next; 64 | } 65 | 66 | return current; 67 | } 68 | 69 | 70 | public void displayList(){ 71 | Link current = first; 72 | 73 | System.out.println("\nPrinting List:"); 74 | while(current != null){ 75 | current.displayLink(); 76 | current = current.next; 77 | } 78 | } 79 | } 80 | 81 | 82 | 83 | class Main { 84 | public static void main(String[] args){ 85 | LinkedList list = new LinkedList(); 86 | 87 | list.insertFirst(1, 20); 88 | list.insertFirst(1, 50); 89 | list.insertFirst(2, 64); 90 | list.insertFirst(10, 34); 91 | list.insertFirst(3, 70); 92 | 93 | list.displayList(); 94 | 95 | Link item = list.find(2); 96 | if(item != null){ 97 | System.out.println("\nItem key: " + item.key + " Item data: " + item.data); 98 | } 99 | else{ 100 | System.out.println("\nCouldn't find key"); 101 | } 102 | 103 | 104 | Link deleted = list.delete(2); 105 | if(deleted != null){ 106 | System.out.println("\nItem deleted. Item key: " + item.key + " Item data: " + item.data); 107 | } 108 | else{ 109 | System.out.println("\nCouldn't find key"); 110 | } 111 | 112 | list.displayList(); 113 | } 114 | } -------------------------------------------------------------------------------- /DataStructures/LinkedLists/sortedSinglyLinkedList/sortedLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | A sorted linked list that inserts links based on data size 4 | There are two constructors, one for initializing the list, another if an array needs to 5 | be passed in, for sorting purposes. (Inputting an unsorted array, then inserting it into 6 | a sorted linked list will sort it faster than sorting it within the array) 7 | */ 8 | 9 | 10 | class Link{ 11 | 12 | public int data; 13 | public Link next; 14 | 15 | public Link(int d){ 16 | data = d; 17 | } 18 | } 19 | 20 | 21 | class SortedLinkedList{ 22 | 23 | private Link first; 24 | 25 | public SortedLinkedList(){ 26 | first = null; 27 | } 28 | 29 | public SortedLinkedList(Link[] linkArray){ 30 | first = null; 31 | for(int i = 0; i < linkArray.length; i++){ 32 | insert(linkArray[i]); 33 | } 34 | } 35 | 36 | 37 | public void insert(Link newLink){ 38 | Link previous = null; 39 | Link current = first; 40 | 41 | while(current != null && newLink.data > current.data){ 42 | previous = current; 43 | current = current.next; 44 | } 45 | 46 | if(previous == null){ 47 | first = newLink; 48 | } 49 | else{ 50 | previous.next = newLink; 51 | } 52 | newLink.next = current; 53 | } 54 | 55 | public Link remove(){ 56 | Link temp = first; 57 | first = first.next; 58 | return temp; 59 | } 60 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Queue/simpleArrayQueue.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | //Implement a simple array queue 5 | 6 | 7 | class Queue{ 8 | private int maxSize; 9 | private int[] queArray; 10 | private int front; 11 | private int back; 12 | private int nItems; 13 | 14 | public Queue(int size){ 15 | maxSize = size; 16 | queArray = new int[maxSize]; 17 | front = 0; 18 | rear = -1; 19 | nItems = 0; 20 | } 21 | 22 | public void insert(int data){ 23 | 24 | //wrap queue if we overflow 25 | if(rear == maxSize -1){ 26 | rear = -1; 27 | } 28 | rear++; 29 | queArray[rear] = data; 30 | nItems++; 31 | } 32 | 33 | public int remove(){ 34 | int temp = queArray[front]; 35 | front++; 36 | //wrap front of queue if we overflow 37 | if(front == maxSize){ 38 | front = 0; 39 | } 40 | nItems--; 41 | 42 | return temp; 43 | } 44 | 45 | public int peekFront(){ 46 | return queArray[front]; 47 | } 48 | 49 | public boolean isEmpty(){ 50 | return nItems == 0; 51 | } 52 | 53 | public boolean isFull(){ 54 | return nItems == maxSize; 55 | } 56 | 57 | public int size(){ 58 | return nItems; 59 | } 60 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Queue/twoQueuesComparison.java: -------------------------------------------------------------------------------- 1 | /* 2 | Use the queue datastructure to implement two queues that would keep track of 3 | the oldest dogs and cats in an animal shelter. The buyer of the animal of 4 | his/her choice must be the oldest animal of that type. 5 | Implement an enqueue, dequeueAny, deqeueDog and dequeueCat method. 6 | */ 7 | 8 | 9 | public abstract class Animal { 10 | private int order; 11 | private String type; 12 | protected String name; 13 | 14 | //constructor 15 | public Animal(String n, String t){ 16 | name = n; 17 | type = t; 18 | } 19 | 20 | public void setOrder(int ord){ 21 | order = ord; 22 | } 23 | 24 | public int getOrder(){ 25 | return order; 26 | } 27 | 28 | public void setType(int t){ 29 | type = t; 30 | } 31 | 32 | public String getType(){ 33 | return type; 34 | } 35 | 36 | public boolean isOlderThan(Animal a) { 37 | return this.order < a.getOrder(); 38 | } 39 | } 40 | 41 | 42 | public class AnimalQueue { 43 | LinkedList dogs = new LinkedList<>(); 44 | LinkedList cats = new LinkedList<>(); 45 | 46 | //order acts as a timestamp 47 | private int order = 0; 48 | 49 | public void enqueue(Animal a){ 50 | a.setOrder(order); 51 | order++; 52 | 53 | if(a.getType().equals("Dog")){ 54 | dogs.addLast((Dog) a); 55 | } 56 | else{ 57 | cats.addLast((Cat) a); 58 | } 59 | } 60 | 61 | public Animal dequeueAny() { 62 | if(dogs.size() == 0){ 63 | return dequeueCats(); 64 | } 65 | else if(cats.size() == 0){ 66 | return deqeueDogs(); 67 | } 68 | 69 | Dog dog = dogs.peek(); 70 | Cat cat = cats.peek(); 71 | 72 | if(dog.isOlderThan(cat)){ 73 | return deqeueDogs(); 74 | } 75 | else{ 76 | dequeueCats(); 77 | } 78 | } 79 | 80 | public Dog dequeueDogs(){ 81 | return dogs.poll(); 82 | } 83 | 84 | public Cat dequeueCats(){ 85 | return cats.poll(); 86 | } 87 | } 88 | 89 | public class Dog extends Animal { 90 | public Dog(String n, t){ 91 | super(n, t); 92 | } 93 | } 94 | 95 | public class Cat extends Animal { 96 | public Cat(String n, t){ 97 | super(n, t); 98 | } 99 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Stack/simpleStack.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //Simple stack implementation using arrays 4 | 5 | 6 | 7 | class Stack { 8 | private int maxSize; 9 | private int[] stack; 10 | private int top; 11 | 12 | //constructor 13 | public Stack(int size){ 14 | maxSize = size; 15 | stack = new int[maxSize]; 16 | top = -1; 17 | } 18 | 19 | 20 | public void push(int d){ 21 | if(!isFull()){ 22 | top++; 23 | stack[top] = d; 24 | } 25 | } 26 | 27 | public int pop(){ 28 | if(!isEmpty()){ 29 | int temp = stack[top]; 30 | top--; 31 | return temp; 32 | } 33 | else{ 34 | return -1; 35 | } 36 | } 37 | 38 | public int peek(){ 39 | if(!isEmpty()){ 40 | return stack[top]; 41 | } 42 | else{ 43 | return -1; 44 | } 45 | } 46 | 47 | public boolean isEmpty(){ 48 | return top == -1; 49 | } 50 | 51 | public boolean isFull(){ 52 | return top == maxSize -1; 53 | } 54 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Stack/sortStackAscending.java: -------------------------------------------------------------------------------- 1 | //Sort a stack in ascending order using only one other stack 2 | //This is performed in O(n^2) time and uses O(n) space 3 | 4 | public static Stack sort(Stack firstStack){ 5 | Stack secondStack = new Stack<>(); 6 | 7 | while(!firstStack.isEmpty()){ 8 | int temp = firstStack.pop(); 9 | 10 | while(!secondStack.isEmpty() && temp < secondStack.peek()){ 11 | firstStack.push(secondStack.pop()); 12 | } 13 | secondStack.push(tmp); 14 | } 15 | return secondStack; 16 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Stack/stackAndBracketChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | Use stack to check matching brackets. 3 | First we create an instance of the Stack object. After that, we 4 | iterate through the string and switch case, then push each bracket delimeter i.e. "[,{,(..." 5 | to the Stack then break. We then switch case and, if stack is not empty, we pop the value. 6 | We must then check if the delimeters in our switch statements have their appropriate closing 7 | brackets. */ 8 | 9 | //General stack class that takes in chars 10 | class Stack { 11 | 12 | private int maxSize; 13 | private char[] stackArray; 14 | private int top; 15 | 16 | public Stack(int maxSize){ 17 | maxSize = maxSize; 18 | stackArray = new char[maxSize]; 19 | top = -1; 20 | } 21 | 22 | public void push(char value){ 23 | if(!isFull()){ 24 | top += 1; 25 | stackArray[top] = value; 26 | } 27 | } 28 | 29 | public char pop(){ 30 | if(!isEmpty()){ 31 | top -= 1; 32 | return stackArray[top]; 33 | } 34 | } 35 | 36 | public char peek(){ 37 | return stackArray[top]; 38 | } 39 | 40 | public boolean isEmpty(){ 41 | return (top == -1); 42 | } 43 | 44 | public boolean isFull(){ 45 | return (top == maxSize - 1); 46 | } 47 | } 48 | 49 | 50 | 51 | //Checks if brackets are closed 52 | class BracketChecker { 53 | private String input; 54 | 55 | public BracketChecker(String in){ 56 | input = in; 57 | } 58 | 59 | public void check(){ 60 | int stackSize = input.length(); 61 | Stack myStack = new Stack(stackSize); 62 | 63 | for(int i = 0; i < stackSize; i++){ 64 | char bracket = input.charAt(i); 65 | 66 | switch(bracket){ 67 | case '{': 68 | case '[': 69 | case '(': 70 | myStack.push(bracket); 71 | break; 72 | 73 | case '}': 74 | case ']': 75 | case ')': 76 | char bracketx = myStack.pop(); 77 | if( (bracket=='}' && bracketx != '{' || 78 | bracket==']' && bracketx != '[' || 79 | bracket==')' && bracketx != '(')){ 80 | System.out.println("Error with delimeter"); 81 | } 82 | } 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/Stack/twoStacksOneQueue.java: -------------------------------------------------------------------------------- 1 | //Implement a Queue using two stacks 2 | 3 | 4 | class myQeueue { 5 | Stack oldStack, newStack; 6 | 7 | public myQeueue(){ 8 | newStack = new Stack(); 9 | oldStack = new Stack(); 10 | } 11 | 12 | public int stackSize(){ 13 | return newStack.size() + oldStack.size(); 14 | } 15 | 16 | public void add(T value){ 17 | newStack.push(value); 18 | } 19 | 20 | private void shiftStack(){ 21 | if(oldStack.isEmpty()){ 22 | while(!newStack.isEmpty()){ 23 | oldStack.push(newStack.pop()); 24 | } 25 | } 26 | } 27 | 28 | public void peek(){ 29 | shiftStack(); 30 | oldStack.peek(); 31 | } 32 | 33 | public void remove(){ 34 | shiftStack(); 35 | oldStack.peek(); 36 | } 37 | } -------------------------------------------------------------------------------- /DataStructures/StacksAndQueues/linkedListStack/linkedListStack.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //A stack implemented by the use of a linked list. 4 | //This file contains a Link, LinkedList and Stack class 5 | 6 | 7 | class Link{ 8 | public int data; 9 | public Link next; 10 | 11 | public Link(int d){ 12 | data = d; 13 | } 14 | 15 | public void displayLink(){ 16 | System.out.println("Link contains: " + data); 17 | } 18 | 19 | } 20 | 21 | 22 | 23 | class LinkedList{ 24 | private Link first; 25 | 26 | public LinkedList(){ 27 | first = null; 28 | } 29 | 30 | public void insertFirst(int data){ 31 | Link newLink = new Link(data); 32 | newLink.next = first; 33 | first = newLink; 34 | } 35 | 36 | public int deleteFirst(){ 37 | if(!isEmpty()){ 38 | Link temp = first; 39 | first = first.next; 40 | return temp.data; 41 | } 42 | else{ 43 | return -1; 44 | } 45 | } 46 | 47 | public void displayList(){ 48 | Link current = first; 49 | while(current != null){ 50 | current.displayLink(); 51 | current = current.next; 52 | } 53 | } 54 | 55 | public boolean isEmpty(){ 56 | return first == null; 57 | } 58 | } 59 | 60 | 61 | 62 | class LinkStack{ 63 | private LinkedList stack; 64 | 65 | public LinkStack(){ 66 | stack = new LinkedList(); 67 | } 68 | 69 | public void push(int data){ 70 | stack.insertFirst(data); 71 | } 72 | 73 | public int pop(){ 74 | return stack.deleteFirst(); 75 | } 76 | 77 | public boolean isEmpty(){ 78 | return stack.isEmpty(); 79 | } 80 | 81 | public void displayStack(){ 82 | stack.displayList(); 83 | } 84 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms 2 | 3 | This repository contains problems I've outlined and solved, and ones which I find both useful and crucial to understanding data structures and algorithms. This repository is composed of the following three main directories: 4 | 5 | + Algorithms and Problems 6 | + Data Structures 7 | + Recursion 8 | 9 | Each directory has many nested sub-directories that hold relevant sub-topics. 10 | 11 | 12 | ## Study Them, Know Them, Love Them 13 | 14 | Seriously. Want to ace your interviews? Want to solve problems and bugs faster? Want to develop cleaner, better 15 | designed applications? 16 | 17 | **Then study this shit.** 18 | 19 | 20 | 21 | ![KeepCalm](http://vignette3.wikia.nocookie.net/data-structures/images/5/56/Keep-calm-and-study-data-structures-1.png/revision/latest?cb=20140919152502) 22 | -------------------------------------------------------------------------------- /Recursion/Permutations.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | class Permutations{ 5 | 6 | public static void main(String[] args){ 7 | permutateString("", "Hello"); 8 | 9 | } 10 | 11 | public static void permutateString(String start, String end){ 12 | if(end.length() <= 1){ 13 | System.out.println(start + end); 14 | } 15 | else{ 16 | for(int i = 0; i < end.length(); i++){ 17 | 18 | String newString = end.substring(0,i) + end.substring(i+1); 19 | 20 | permutateString(start + end.charAt(i), newString); 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Recursion/recursiveBSearch.java: -------------------------------------------------------------------------------- 1 | //A recursive binary search (using arrays in this example) 2 | //The function recSearch returns the index at which the dataKey is in 3 | 4 | 5 | class RecursiveBinarySearch { 6 | 7 | public static void main(String[] args){ 8 | int[] myArray = {1,3,4,5,7,8,11,15,17,23,26,28,35,47,58}; 9 | int result = recSearch(1, 0, myArray.length, myArray); 10 | System.out.println(""+result); 11 | } 12 | 13 | public static int recSearch(int dataKey, int lowerBound, int upperBound, int[] array){ 14 | int median = (lowerBound + upperBound) / 2; 15 | 16 | if(array[median] == dataKey){ 17 | return median; 18 | } 19 | else if(lowerBound > upperBound){ 20 | return -1; 21 | } 22 | else{ 23 | //Search the upper half 24 | if(array[median] < dataKey){ 25 | return recSearch(dataKey, median+1, upperBound, array); 26 | } 27 | //Search lower half 28 | else{ 29 | return recSearch(dataKey, lowerBound, median-1, array); 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Recursion/triangularNumbersRecursion.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solve the triangular numbers problem using recursion (1,3,6,10..). 3 | Write some function, say solveTriangle, that returns the nth number in the series. 4 | Example: 5 | input: n = 5 6 | output: 15 7 | */ 8 | 9 | 10 | class TriangularNumbers { 11 | 12 | public static void main(String[] args){ 13 | int nthNumber = 5; 14 | solveTriangle(nthNumber); 15 | } 16 | 17 | private static int solveTriangle(int n ){ 18 | if(n == 1){ 19 | return 1; 20 | } 21 | else{ 22 | return(n + solveTriangle(n-1)); 23 | } 24 | } 25 | } --------------------------------------------------------------------------------