├── .gitignore ├── Hello.java ├── README.md ├── arrays ├── IntersectionTwoArrays.java ├── MaxContigSumArrayIterative.java ├── MaxContigSumArrayRecursive.java ├── MaxIncrementalSubsequence.java ├── MaxSum3Array.java ├── PlatformsTrainStation.java ├── SetMatrixToZero.java ├── Sum3EqualsZero.java ├── find_local_min.cpp ├── find_ones_in_matrix.cpp ├── majority_element.cpp ├── max_contig_sum_iterative.py ├── max_contig_sum_naive.py ├── max_contig_sum_recursive.py ├── max_difference.cpp └── python │ ├── add_kth_row_pascals_triangle.py │ ├── add_one_to_number.py │ ├── first_missing_integer.py │ ├── intersection_two_arrays.py │ ├── largest_connected_group.py │ ├── largest_connected_group_dfs.py │ ├── largest_number.py │ ├── max_contig_sum.py │ ├── max_gap_hunan.py │ ├── max_sum_3.py │ ├── maximum_consecutive_gap.py │ ├── merge_intervals.py │ ├── merge_logs.py │ ├── pascals_triangle.py │ ├── set_matrix_to_zero.py │ ├── spiral_matrix.py │ └── sum3_equals_zero.py ├── dynamic └── python │ └── coin_change.py ├── graphs ├── BFS.java ├── ChessMoves.java ├── DFS.java ├── DFS1.java ├── Graph.java ├── TopologicalSort.java ├── Vertex.java ├── lockers.py └── python │ ├── Graph.py │ ├── Vertex.py │ ├── bfs.py │ ├── dfs.py │ └── pretty_print.py ├── hashtables ├── ChainingHashTable.java ├── HashTable.java ├── HashTableTest.java ├── OpenAddressHashTable.java ├── OpenAddressHashTableTest.java ├── Pair.java └── python │ ├── entry.py │ ├── hash_table.py │ ├── hash_table_addressing.py │ └── hash_table_chaining.py ├── heaps ├── BinaryHeap.cpp ├── BinaryHeap.java └── python │ ├── Heap.py │ ├── delete_ith.py │ ├── median.py │ ├── merge_k_sorted.py │ └── test_data.py ├── javalang └── Hello.java ├── lists ├── CircularLinkedList.java ├── CloneLinkedList.java ├── DeleteNode.java ├── LinkedListBasics.java ├── Node.java ├── NodeInteger.java ├── RemoveDuplicates.java ├── ReverseLinkedList.java ├── SinglyLinkedList.java ├── SinglyLinkedListInteger.java ├── SumTwoLists.cpp ├── SumTwoLists.java ├── __init__.py ├── find_intersection.cpp └── python │ ├── DoublyNode.py │ ├── LinkedList.py │ ├── Node.py │ ├── __init__.py │ ├── circular_has_cycle.py │ ├── compare_two_lists.py │ ├── delete_kth_node.py │ ├── find_intersection.py │ ├── get_max_value.py │ ├── insert_doubly_linked_node.py │ ├── insert_nth_node.py │ ├── merge_sort_linked_list.py │ ├── merge_sorted_linked_lists.py │ ├── nth_node_from_tail.py │ ├── remove_duplicates.py │ ├── reverse_doubly_linked_list.py │ ├── reverse_linked_list.py │ └── sum_two_lists.py ├── math ├── Counter.java ├── FindMissingInteger.java ├── PowersOfTwo.java ├── SumTwoArrays.java ├── SwapIntegers.java ├── p99WebsiteLatency.java ├── python │ ├── binary_to_decimal.py │ ├── excel_column_number.py │ ├── gcd.py │ ├── get_all_primes.py │ ├── grid_unique_paths.py │ ├── integer_palindrome.py │ ├── prime_sum.py │ └── rearrange_array.py └── smallest_num_greaterThan_k.cpp ├── powerset ├── PowersetBitwiseOperators.java ├── PowersetIterative.java ├── PowersetRecursive.java ├── iterative_mike_1.py ├── powerset.py ├── powerset_bitwise_operators.py ├── powerset_iterative.py ├── powerset_recursive.py └── pset_binary.py ├── queues ├── Node.java ├── Queue.java ├── QueueWithArray.java ├── QueueWithLinkedList.java ├── __init__.py └── python │ ├── Node.py │ ├── Queue.py │ ├── __init__.py │ └── queue_w_stacks.py ├── recursion ├── CentsCombosN.java ├── Fibonacci.java ├── PaintFill.java ├── PowersetBinary.java ├── PowersetIterative.java ├── PowersetRecursive.java ├── QueensChess.java ├── RobotSquares.java ├── StringPermutations.java ├── ValidPairsParentheses.java └── python │ ├── binary_strings.py │ ├── connected_cells.py │ ├── kary_string.py │ └── permutate.py ├── searching ├── BinarySearch.java ├── BinarySearchPivot.java ├── BitonicSearch.java └── python │ ├── binary_search.py │ ├── binary_search_w_pivot.py │ ├── count_element_occurence.py │ ├── get_sqrt.py │ └── search_matrix.py ├── sorting ├── BubbleSort.java ├── BucketSort.java ├── CountingSort.java ├── InsertionSort.java ├── MergeSort.java ├── QuickSort.java ├── SelectionSort.java ├── SelectionSortString.java ├── ShellSort.java ├── SortArray012.java └── python │ ├── bubble.py │ ├── bucket.py │ ├── counting.py │ ├── heap.py │ ├── insertion.py │ ├── merge.py │ ├── quicksort.py │ ├── selection.py │ ├── shell.py │ ├── silly_sort.py │ └── sort012.py ├── stacks ├── EvaluateExpression.java ├── Node.java ├── QueueUsingStacks.java ├── SetOfStacks.java ├── SortStack.java ├── Stack.java ├── StackWithMax.java ├── StackWithMin.java ├── TowersOfHanoi.java ├── __init__.py └── python │ ├── Node.py │ ├── Stack.py │ ├── __init__.py │ ├── evaluate_expression.py │ ├── set_of_stacks.py │ ├── sort_stack.py │ ├── stack_w_max.py │ └── stacks_w_array.py ├── strings ├── FirstUniqueChar.java ├── IsRotation.java ├── LongestSubstringNoDupes.java ├── RemoveDuplicates.java ├── ReplaceSpaces.java ├── ReverseString.java ├── ReverseWords.java ├── RotateString.java ├── isAnagram.java ├── python │ ├── anagram.py │ ├── csv_parser.py │ ├── first_unique_char.py │ ├── interpret_symbols.py │ ├── is_rotation.py │ ├── longest_substring_no_dupes.py │ ├── remove_dupes.py │ ├── replace_spaces.py │ ├── reverse_sentence.py │ └── reverse_string.py ├── reverse_string_inplace.cpp └── string_replace_space.cpp └── trees ├── BinarySearchTree.java ├── BinaryTree.java ├── BinaryTreeNode.java ├── BuildBinarySearchTree.java ├── BuildParseTreeMath.java ├── ExpressionTree.java ├── FirstAncestor.cpp ├── FirstAncestor.java ├── IsBalanced.java ├── IsSubtree.java ├── MaxWeightSubtree.java ├── MinHeightTree.java ├── MirrorBinaryTree.java ├── PrintPathToKey.java ├── Tree.java ├── TreeNode.java ├── TreeTest.java ├── TreeTraversals.java ├── bst_sum_to_k.cpp ├── count_nodes_k_distance_away.cpp ├── find_paths.cpp ├── in_order_traversal.cpp ├── python ├── AVL_Tree.py ├── LCA.py ├── Node.py ├── build_bst.py ├── build_tree.py ├── deepest_node.py ├── diameter.py ├── expression_tree.py ├── find_element.py ├── in_order.py ├── is_bst.py ├── kth_smallest.py ├── level_order.py ├── max_element.py ├── max_path_sum.py ├── post_order.py ├── pre_order.py ├── print_upside_down.py ├── test_data.py ├── tree_depth.py └── zigzag_tree.py └── sub_tree.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.class 3 | *.idea 4 | *pyc 5 | .gitconfig -------------------------------------------------------------------------------- /Hello.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.io.*; //InputStream, InputStreamReader, BufferedReader 5 | import math.Counter; 6 | 7 | public class Hello { 8 | 9 | public int count = 0; 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println("Hello World!"); 14 | System.out.println(Integer.toBinaryString(8)); 15 | 16 | List l1 = new ArrayList(); 17 | l1.add("A"); 18 | l1.add("B"); 19 | l1.add("C"); 20 | List l2 = new ArrayList(l1); 21 | for (String s : l2) { 22 | System.out.println(s); 23 | } 24 | 25 | int i = 4; 26 | String iStr = String.valueOf(i); 27 | System.out.println(iStr instanceof String); 28 | 29 | Integer iInt = Integer.parseInt(iStr); 30 | System.out.println(iInt instanceof Integer); 31 | 32 | Double j = 4.5; 33 | String dStr = Double.toString(i); 34 | System.out.println(dStr instanceof String); 35 | 36 | Double doub = Double.parseDouble(dStr); 37 | System.out.println(doub instanceof Double); 38 | 39 | String f = "README.md"; 40 | readFile(f); 41 | 42 | System.out.println("====================="); 43 | 44 | String s = "A"; 45 | changeStr(s); 46 | System.out.println(s.equals("A")); 47 | 48 | Counter c = new Counter(); 49 | increment(c); 50 | System.out.println(c.count); 51 | 52 | } 53 | 54 | public static void changeStr(String s) { 55 | s = "e"; 56 | } 57 | 58 | public static void increment(Counter c) { 59 | c.count = 3; 60 | } 61 | 62 | public static void readFile(String filename) { 63 | try { 64 | InputStream input = new FileInputStream(filename); 65 | InputStreamReader reader = new InputStreamReader(input); 66 | BufferedReader buffer = new BufferedReader(reader); 67 | String line = buffer.readLine(); 68 | while (line != null) { 69 | System.out.println(line); 70 | line = buffer.readLine(); 71 | } 72 | } catch (IOException e) { 73 | //do nothing 74 | } 75 | } 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /arrays/MaxContigSumArrayIterative.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class MaxContigSumArrayIterative { 5 | 6 | public static void main(String[] args) { 7 | 8 | System.out.println("Starting Tests!"); 9 | testGetMaxContigSum(); 10 | 11 | } 12 | 13 | public static int getMaxContigSum(List nums) { 14 | int maxSum = nums.get(0); 15 | int curSum = 0; 16 | 17 | for (int e : nums) { 18 | 19 | if (curSum + e < e) { 20 | curSum = e; 21 | } else { 22 | curSum = curSum + e; 23 | } 24 | 25 | if (curSum > maxSum) { 26 | maxSum = curSum; 27 | } 28 | } 29 | 30 | return maxSum; 31 | } 32 | 33 | public static void testGetMaxContigSum() { 34 | List nums1 = new ArrayList(); 35 | nums1.add(0); 36 | nums1.add(4); 37 | nums1.add(-2); 38 | nums1.add(1); 39 | nums1.add(4); 40 | System.out.println(getMaxContigSum(nums1) == 7); 41 | 42 | nums1.clear(); 43 | 44 | nums1.add(-7); 45 | System.out.println(getMaxContigSum(nums1) == -7); 46 | 47 | nums1.clear(); 48 | 49 | nums1.add(1); 50 | nums1.add(1); 51 | nums1.add(1); 52 | 53 | System.out.println(getMaxContigSum(nums1) == 3); 54 | 55 | nums1.clear(); 56 | 57 | nums1.add(0); 58 | nums1.add(4); 59 | nums1.add(-6); 60 | nums1.add(8); 61 | 62 | System.out.println(getMaxContigSum(nums1) == 8); 63 | 64 | nums1.clear(); 65 | 66 | nums1.add(1); 67 | nums1.add(1); 68 | nums1.add(1); 69 | nums1.add(-3); 70 | nums1.add(1); 71 | nums1.add(1); 72 | nums1.add(1); 73 | 74 | System.out.println(getMaxContigSum(nums1) == 3); 75 | 76 | nums1.clear(); 77 | 78 | nums1.add(0); 79 | nums1.add(-2); 80 | nums1.add(5); 81 | nums1.add(-4); 82 | nums1.add(-3); 83 | 84 | System.out.println(getMaxContigSum(nums1) == 5); 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /arrays/MaxIncrementalSubsequence.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.*; 4 | 5 | public class MaxIncrementalSubsequence { 6 | 7 | public static void main(String[] args) { 8 | MaxIncrementalSubsequence max = new MaxIncrementalSubsequence(); 9 | int[] a1 = {0,2,1,3,4,5,0,1}; 10 | System.out.println(max.getMaxLength(a1) == 4); 11 | int[] b1 = max.getMaxLengthSubsequence(a1); 12 | int[] sub = {1,3,4,5}; 13 | System.out.println(Arrays.equals(sub,b1)); 14 | } 15 | public int getMaxLength(int[] arr) { 16 | int max = 0; 17 | int curStart = 0; 18 | int curEnd = 1; 19 | for (int i=0; i max) { 23 | max = curEnd-curStart; 24 | } 25 | } else { 26 | curStart = i+1; 27 | curEnd = i+2; 28 | } 29 | } 30 | return max; 31 | } 32 | 33 | public int[] getMaxLengthSubsequence(int[] arr) { 34 | if (arr == null || arr.length == 0) { 35 | return null; 36 | } 37 | int maxStart = 0; 38 | int maxEnd = 1; 39 | int curStart = 0; 40 | int curEnd = 1; 41 | for (int i=0; i maxEnd-maxStart) { 45 | maxStart = curStart; 46 | maxEnd = curEnd; 47 | } 48 | } else { 49 | curStart = i+1; 50 | curEnd = i+2; 51 | } 52 | } 53 | return Arrays.copyOfRange(arr,maxStart,maxEnd); 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /arrays/MaxSum3Array.java: -------------------------------------------------------------------------------- 1 | public class MaxSum3Array { 2 | 3 | public static void main(String[] args) { 4 | int[] arr1 = {1,3,5,-3,2}; 5 | int max1 = getMaxSum(arr1); 6 | System.out.println(max1); 7 | } 8 | 9 | public static int getMaxSum(int[] arr) { 10 | int len = arr.length; 11 | Integer maxSum = null; 12 | for (int i=0; i maxSum) { 17 | maxSum = curSum; 18 | } 19 | } 20 | } 21 | } 22 | 23 | return maxSum; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /arrays/SetMatrixToZero.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | //import org.apache.commons.lang3.ArrayUtils; 3 | 4 | public class SetMatrixToZero { 5 | 6 | public static void main(String[] args) { 7 | int[][] in1 = { 8 | { 0, 2, 3 }, 9 | { 4, 5, 6 }, 10 | { 7, 8, 4 } 11 | }; 12 | int[][] out1 = { 13 | { 0, 0, 0 }, 14 | { 0, 5, 6 }, 15 | { 0, 8, 4 } 16 | }; 17 | in1 = setMatrixToZero(in1); 18 | for (int i=0; ij) { 20 | curSum = arr[i] + arr[j] + arr[k]; 21 | if (curSum == 0) { 22 | return true; 23 | } else if (curSum < 0) { 24 | j++; 25 | } else { 26 | k--; 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /arrays/find_local_min.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // function to find A local minimum in a array of distinct elements 7 | // use binary search. 8 | 9 | int find_local_min(int *array,int left,int right){ 10 | if (left == right) 11 | return left; 12 | if (right-left ==1){ 13 | if (array[left] < array[right]) 14 | return left; 15 | else 16 | return right; 17 | } 18 | int mid = left + (right-left) / 2; 19 | int result = -1; 20 | if (array[mid-1] > array[mid] && array[mid+1] > array[mid]) 21 | result = mid; 22 | else{ 23 | if (array[mid-1] < array[mid]) 24 | result = find_local_min(array,left,mid-1); 25 | else if (array[mid+1] < array[mid]) 26 | result = find_local_min(array,mid+1,right); 27 | } 28 | return result; 29 | } 30 | 31 | int main() { 32 | int array[] = {11,5,12,7,4,0,6}; 33 | cout << find_local_min(array,0,7); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /arrays/find_ones_in_matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Program that takes in a 2D SORTED matrix of integers 8 | // Goal: find the row with the most number of ones 9 | 10 | 11 | int find_row(vector >&tmp){ 12 | if (tmp.size() == 0){ 13 | return -1; 14 | } 15 | else { 16 | int max = 0; 17 | int count = 0; 18 | int index = -1; 19 | for (int x=0;x max){ 25 | max = count; 26 | index = x; 27 | } 28 | count = 0; 29 | } 30 | return index; 31 | } 32 | 33 | } 34 | 35 | int main() { 36 | //constructing a matrix 37 | int myints0[] = {0,2,6}; 38 | int myints1[] = {1,1,2}; // index 1 is the answer 39 | int myints2[] = {1,3,5,12}; 40 | vector tmp0 (myints0,myints0+3); 41 | vector tmp1 (myints1,myints1+3); 42 | vector tmp2 (myints2,myints2+4); 43 | vector > matrix; 44 | matrix.push_back(tmp0); 45 | matrix.push_back(tmp1); 46 | matrix.push_back(tmp2); 47 | 48 | 49 | cout << "index with the most ones: " << find_row(matrix) << endl; 50 | 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /arrays/majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Moore's Voting algorithm 9 | // 1. Get an element occuring most of the time in the array. 10 | // This phase will make sure that if there is a majority element 11 | // then it will return that only. 12 | // 2. Check if the element obtained from step 1 is the majority element 13 | 14 | // Function to check if the candidate occurs more than n/2 times 15 | // where n is the size of the vector 16 | bool isMajority(vector &tmp,int candidate){ 17 | int i, count =0; 18 | for(i = 0; i < tmp.size(); i++){ 19 | if (tmp[i] == candidate) 20 | count++; 21 | } 22 | if (count > tmp.size()/2) 23 | return 1; 24 | else 25 | return 0; 26 | } 27 | // function to find candidate for the majority 28 | int findCandidate(vector &tmp){ 29 | int maj_index=0, count=1; 30 | int i; 31 | for (i=1; i &tmp){ 48 | // find candidate for Majority 49 | int candidate = findCandidate(tmp); 50 | 51 | // Print candidate if it is majority 52 | if (isMajority(tmp,candidate)) 53 | cout << candidate << " is Majority element" << endl; 54 | else 55 | cout << "No majority element." << endl; 56 | } 57 | 58 | int main() { 59 | int myints[] = {1,3,3,1,2}; 60 | vector tmp (myints,myints+3); 61 | printMajority(tmp); 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /arrays/max_contig_sum_iterative.py: -------------------------------------------------------------------------------- 1 | # Linear 2 | # Find largest sum of contiguous ints 3 | # list = [0,4,-2,1,4]. = 7 4 | 5 | def large_contig_sum(l1): 6 | maxSum = l1[0] 7 | curSum = 0 8 | for e in l1: 9 | if curSum + e < e: 10 | curSum = e 11 | else: 12 | curSum += e 13 | if curSum > maxSum: 14 | maxSum = curSum 15 | return maxSum 16 | 17 | 18 | list1 = [0,4,-2,1,4] # 7 19 | list2 = [0,-1,-2,9,8,4,-1,-6] 20 | list3 = [0,4,-6,3,8,9] 21 | list4 = [0,4,-6, 9] 22 | list5 = [0,4,9] 23 | list6 = [7] 24 | list7 = [-7] 25 | list8 = [-3,-4,-2,-5, 0] 26 | list9 = [1,1,1,1,1] 27 | list10 = [9,8,-6,-2,-20,16,-2] 28 | list11 = [1,1,1,-3,1,1,1] 29 | list12 = [0,-2,5,-4,-3] 30 | print large_contig_sum(list1) == 7 31 | print large_contig_sum(list2) == 21 32 | print large_contig_sum(list3) == 20 33 | print large_contig_sum(list4) == 9 34 | print large_contig_sum(list5) == 13 35 | print large_contig_sum(list6) == 7 36 | print large_contig_sum(list7) == -7 37 | print large_contig_sum(list9) == 5 38 | print large_contig_sum(list10) == 17 39 | print large_contig_sum(list11) == 3 40 | print large_contig_sum(list12) == 5 41 | -------------------------------------------------------------------------------- /arrays/max_contig_sum_naive.py: -------------------------------------------------------------------------------- 1 | # Find largest sum of contiguous ints 2 | #list = [0,4,-2,1,4]. = 7 3 | 4 | def large_contig_sum(l1): 5 | maxSum = l1[0] 6 | curSum = 0 7 | n = len(l1) 8 | i = 1 #length of chunk 9 | while i <= n: 10 | j = 0 11 | while j <= n-i: 12 | k = 0 13 | while k < i: 14 | curSum += l1[j+k] 15 | k += 1 16 | if curSum > maxSum: 17 | maxSum = curSum 18 | curSum = 0 19 | j += 1 20 | i += 1 21 | return maxSum 22 | 23 | 24 | list1 = [0,4,-2,1,4] # 7 25 | list2 = [0,-1,-2,9,8,4,-1,-6] 26 | list3 = [0,4,-6,3,8,9] 27 | list4 = [0,4,-6, 9] 28 | list5 = [0,4,9] 29 | list6 = [7] 30 | list7 = [-7] 31 | print large_contig_sum(list1) == 7 32 | print large_contig_sum(list2) == 21 33 | print large_contig_sum(list3) == 20 34 | print large_contig_sum(list4) == 9 35 | print large_contig_sum(list5) == 13 36 | print large_contig_sum(list6) == 7 37 | print large_contig_sum(list7) == -7 38 | -------------------------------------------------------------------------------- /arrays/max_contig_sum_recursive.py: -------------------------------------------------------------------------------- 1 | # Recursive 2 | # Find largest sum of contiguous ints 3 | # list = [0,4,-2,1,4]. = 7 4 | 5 | def large_contig_sum(l1, maxSum, curSum): 6 | if len(l1) == 0: 7 | return maxSum 8 | elif curSum + l1[0] < l1[0]: 9 | curSum = l1[0] 10 | else: 11 | curSum += l1[0] 12 | 13 | if curSum > maxSum: 14 | return large_contig_sum(l1[1:], curSum, curSum) 15 | else: 16 | return large_contig_sum(l1[1:], maxSum, curSum) 17 | 18 | 19 | list1 = [0,4,-2,1,4] 20 | list2 = [0,-1,-2,9,8,4,-1,-6] 21 | list3 = [0,4,-6,3,8,9] 22 | list4 = [0,4,-6, 9] 23 | list5 = [0,4,9] 24 | list6 = [7] 25 | list7 = [-7] 26 | list8 = [-3,-4,-2,-5, 0] 27 | list9 = [1,1,1,1,1] 28 | list10 = [9,8,-6,-2,-20,16,-2] 29 | list11 = [1,1,1,-3,1,1,1] 30 | list12 = [0,-2,5,-4,-3] 31 | print large_contig_sum(list1, list1[0], 0) == 7 32 | print large_contig_sum(list2, 0, 0) == 21 33 | print large_contig_sum(list3, 0, 0) == 20 34 | print large_contig_sum(list4, 0, 0) == 9 35 | print large_contig_sum(list5, 0, 0) == 13 36 | print large_contig_sum(list6, 0, 0) == 7 37 | print large_contig_sum(list7, list7[0], 0) == -7 38 | print large_contig_sum(list8, 0, 0) == 0 39 | print large_contig_sum(list9, 0, 0) == 5 40 | print large_contig_sum(list10, 0, 0) == 17 41 | print large_contig_sum(list11, 0, 0) == 3 42 | print large_contig_sum(list12, 0, 0) == 5 43 | -------------------------------------------------------------------------------- /arrays/max_difference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | // Given an array, find the maximum difference between two array // elements given the second element comes after the first 8 | 9 | // ex. array= [1,2,3,4,5,6,7] 10 | // answer = 7-1 11 | 12 | int max_difference(int *array,int size){ 13 | int min=100; 14 | int max=0; 15 | 16 | // find min and max of array 17 | for (int x=0;x max) 21 | max = array[x]; 22 | } 23 | cout << max << "-" << min << endl; 24 | return max-min; 25 | } 26 | 27 | 28 | int main() { 29 | int array[] = {1,2,3,4,5,6,7}; 30 | cout << max_difference(array,7); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /arrays/python/add_kth_row_pascals_triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a list of integers 4 | def getRow(self, A): 5 | res = [] 6 | i = 0 7 | while i <= A: 8 | res = self.compute_next(res) 9 | res += [1] 10 | i += 1 11 | return res 12 | 13 | def compute_next(self, A): 14 | prior_num = 0 15 | for i in range(len(A)): 16 | cur_num = prior_num + A[i] 17 | prior_num = A[i] 18 | A[i] = cur_num 19 | return A -------------------------------------------------------------------------------- /arrays/python/add_one_to_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative number represented as an array of digits, 3 | 4 | add 1 to the number ( increment the number represented by the digits ). 5 | 6 | The digits are stored such that the most significant digit is at the head of the list. 7 | 8 | Example: 9 | 10 | If the vector has [1, 2, 3] 11 | 12 | the returned vector should be [1, 2, 4] 13 | 14 | as 123 + 1 = 124. 15 | 16 | CASES: 17 | --------- 18 | [] = [1] 19 | [1] = [2] 20 | [0 0 0] = [1] 21 | [9 9 9] = [1 0 0 0] 22 | [1 2 3] = [1 2 4] 23 | [0 1 2 3] = [1 2 4] 24 | """ 25 | 26 | class Solution: 27 | # @param A : list of integers 28 | # @return a list of integers 29 | def plusOne(self, A): 30 | if len(A) == 0: 31 | return [1] 32 | i = len(A)-1 33 | found = False 34 | while i >= 0: 35 | if A[i] == 9: 36 | A[i] = 0 37 | i -= 1 38 | else: 39 | A[i] += 1 40 | found = True 41 | break 42 | if not found: 43 | return [1] + A 44 | i = 0 45 | while A[i] == 0: 46 | i += 1 47 | return A[i:] 48 | -------------------------------------------------------------------------------- /arrays/python/largest_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | For example: 5 | 6 | Given [3, 30, 34, 5, 9], the largest formed number is 9534330. 7 | 8 | Note: The result may be very large, so you need to return a string instead of an integer. 9 | """ 10 | 11 | 12 | class CompareNode: 13 | def __init__(self, val): 14 | self.val = str(val) 15 | 16 | def __gt__(self, other): 17 | a_greater_option = self.val + other.val 18 | b_greater_option = other.val + self.val 19 | return a_greater_option > b_greater_option 20 | 21 | class Solution: 22 | # @param A : tuple of integers 23 | # @return a strings 24 | def get_list_from_tuple(self, tup): 25 | l1 = [] 26 | for i in range(len(tup)): 27 | l1.append(CompareNode(tup[i])) 28 | return l1 29 | 30 | def convert_to_str(self, A): 31 | string = "" 32 | for node in A: 33 | string += str(node.val) 34 | return string 35 | 36 | def largestNumber(self, A): 37 | if A.count(0) == len(A): 38 | return "0" 39 | A = self.get_list_from_tuple(A) 40 | A.sort(reverse=True) 41 | return self.convert_to_str(A) 42 | 43 | 44 | sol = Solution() 45 | 46 | def test_largest_number(): 47 | print sol.largestNumber((3,30,34,5,9)) 48 | print sol.largestNumber((3,)) 49 | print sol.largestNumber((9, 99, 999, 9999, 9998)) 50 | print sol.largestNumber((0,0,0,0,0)) 51 | 52 | if __name__ == "__main__": 53 | test_largest_number() -------------------------------------------------------------------------------- /arrays/python/max_sum_3.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | MaxSum3Array 4 | 5 | Given array of integers, return max sum of 3 element subset 6 | 7 | Approaches 8 | 1) Sort and return last 3 elems (n log n) 9 | 2) Nested loop (n^3) 10 | """ 11 | 12 | def max_sum_3_sort(arr): 13 | arr = sorted(arr) 14 | return sum(arr[len(arr)-3:]) 15 | 16 | def max_sum_3_loops(arr): 17 | if len(arr) < 3: 18 | raise Exception("Array size less than 3!") 19 | max_sum = sum(arr[:3]) 20 | for i in range(len(arr)-2): 21 | for j in range(i+1, len(arr)-1): 22 | for k in range(j+1, len(arr)): 23 | cur_sum = arr[i] + arr[j] + arr[k] 24 | max_sum = max(cur_sum, max_sum) 25 | return max_sum 26 | 27 | def max_sum_3_linear(arr): 28 | max_elems = sorted(arr[:3]) 29 | for num in arr[3:]: 30 | if num > max_elems[0]: 31 | max_elems[0] = num 32 | elif num > max_elems[1]: 33 | max_elems[1] = num 34 | elif num > max_elems[2]: 35 | max_elems[2] = num 36 | return sum(max_elems) 37 | 38 | 39 | 40 | 41 | #Tests 42 | 43 | a1 = [1,4,3,2] 44 | a2 = [-9,1,7,3,3,9] 45 | a3 = [1,3] 46 | 47 | def test_max_sum_3_sort(): 48 | assert max_sum_3_sort(a1) == 9 49 | assert max_sum_3_sort(a2) == 19 50 | 51 | def test_max_sum_3_loops(): 52 | assert max_sum_3_loops(a1) == 9 53 | assert max_sum_3_loops(a2) == 19 54 | 55 | def test_max_sum_3_linear(): 56 | assert max_sum_3_linear(a1) == 9 57 | assert max_sum_3_linear(a2) == 19 58 | 59 | if __name__ == "__main__": 60 | test_max_sum_3_sort() 61 | test_max_sum_3_loops() 62 | test_max_sum_3_linear() -------------------------------------------------------------------------------- /arrays/python/pascals_triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pascals Rows 3 | 4 | Given numRows, generate the first numRows of Pascal's triangle. 5 | 6 | Pascal's triangle : To generate A[C] in row R, sum up A'[C] and A'[C-1] from previous row R - 1. 7 | 8 | Example: 9 | 10 | Given numRows = 5, 11 | 12 | Return 13 | 14 | [ 15 | [1], 16 | [1,1], 17 | [1,2,1], 18 | [1,3,3,1], 19 | [1,4,6,4,1] 20 | ] 21 | input = 9 22 | [1 ] 23 | [1 1 ] 24 | [1 2 1 ] 25 | [1 3 3 1 ] 26 | [1 4 6 4 1 ] 27 | [1 5 10 10 5 1 ] 28 | [1 6 15 20 15 6 1 ] 29 | [1 7 21 35 35 21 7 1 ] 30 | [1 8 28 56 70 56 28 8 1 ] 31 | 32 | 33 | Observations 34 | 1) input 9, ouput 9 arrays 35 | 2) each output arry is a mirror image of itself forward and backwards 36 | 37 | """ 38 | 39 | class Solution: 40 | # @param A : integer 41 | # @return a list of list of integers 42 | def generate(self, A): 43 | if A == 0: 44 | return [] 45 | out = [[1]] 46 | for i in range(1,A): 47 | row = [1] 48 | k = 1 49 | while k < i: 50 | row.append(out[-1][k-1] + out[-1][k]) 51 | k+=1 52 | row.append(1) 53 | out.append(row) 54 | return out 55 | 56 | sol = Solution() 57 | assert sol.generate(5) == [ 58 | [1], 59 | [1,1], 60 | [1,2,1], 61 | [1,3,3,1], 62 | [1,4,6,4,1] 63 | ] -------------------------------------------------------------------------------- /arrays/python/set_matrix_to_zero.py: -------------------------------------------------------------------------------- 1 | """ 2 | SetMatrixToZero 3 | 4 | If an element in a M x N matrix is zero, set its entire row and column to zero 5 | 6 | Cases 7 | 1) BAD INPUT - Empty matrix 8 | 2) BAD INPUT - Not a matrix [1,2,3,4] 9 | 3) One element - [[1]] 10 | 4) No zeros - [[1,3], 11 | [1,2]] 12 | 5) All zeros - [[0,0], 13 | [0,0]] 14 | 6) Multiple zero same row 15 | 7) Multiple zero same col 16 | 17 | Approach 18 | 1) Store two sets, rows_to_zero, cols_to_zero 19 | 2) Loop through matrix, if find zero, add row + col to Sets_To_Zero 20 | 3) Create Two Helper method, set_row_to_zero(row_no), set_col_to_zero(col_no) 21 | 4) Loop through row_to_zero, call helper 22 | 5) Loop through col_to_zero, call helper 23 | """ 24 | 25 | 26 | def set_matrix_to_zero(matrix): 27 | rows_to_zero = set() 28 | cols_to_zero = set() 29 | for row in range(len(matrix)): 30 | for col in range(len(matrix[0])): 31 | if matrix[row][col] == 0: 32 | if row not in rows_to_zero: 33 | rows_to_zero.add(row) 34 | if col not in cols_to_zero: 35 | cols_to_zero.add(col) 36 | for row_no in rows_to_zero: 37 | set_row_to_zero(matrix, row_no) 38 | for col_no in cols_to_zero: 39 | set_col_to_zero(matrix, col_no) 40 | return matrix 41 | 42 | def set_row_to_zero(matrix, row_no): 43 | for col_no in range(len(matrix[row_no])): 44 | matrix[row_no][col_no] = 0 45 | 46 | def set_col_to_zero(matrix, col_no): 47 | for row_no in range(len(matrix)): 48 | matrix[row_no][col_no] = 0 49 | 50 | 51 | # Tests 52 | 53 | m1 = [ 54 | [1,0,0,1], 55 | [0,1,1,1], 56 | [1,1,1,1], 57 | [1,1,1,1]] 58 | 59 | a1 = [ 60 | [0,0,0,0], 61 | [0,0,0,0], 62 | [0,0,0,1], 63 | [0,0,0,1] 64 | ] 65 | 66 | 67 | def test_set_matrix_to_zero(): 68 | assert set_matrix_to_zero(m1) == a1 69 | 70 | if __name__ == "__main__": 71 | test_set_matrix_to_zero() -------------------------------------------------------------------------------- /arrays/python/sum3_equals_zero.py: -------------------------------------------------------------------------------- 1 | 2 | def sum3_equals_zero_naive(arr): 3 | #[1,2,3] 4 | """ 5 | Given array of integers, return true if 6 | any 3 elements in array sum to zero 7 | """ 8 | if arr is None or len(arr) < 3: 9 | return False 10 | #3 loops 11 | i = 0 12 | while i < len(arr)-2: 13 | j = i+1 14 | while j < len(arr)-1: 15 | k = j+1 16 | while k < len(arr): 17 | sum_arr = arr[i] + arr[j] + arr[k] 18 | if sum_arr == 0: 19 | return True 20 | k+=1 21 | j+=1 22 | i+=1 23 | return False 24 | 25 | def test_sum3_equals_zero_naive(): 26 | a1 = [] #False 27 | a2 = [1] #False 28 | a3 = [1,2] #False 29 | a4 = [1,2,3] #False 30 | a5 = [-1,0,1] #True 31 | a6 = [-5,3,-1,99,0] #False 32 | a7 = [-1,0,1,-5,5] #True 33 | 34 | assert sum3_equals_zero_naive(a1) == False 35 | assert sum3_equals_zero_naive(a2) == False 36 | assert sum3_equals_zero_naive(a3) == False 37 | assert sum3_equals_zero_naive(a4) == False 38 | assert sum3_equals_zero_naive(a5) == True 39 | assert sum3_equals_zero_naive(a6) == False 40 | assert sum3_equals_zero_naive(a7) == True 41 | 42 | if __name__ == "__main__": 43 | test_sum3_equals_zero_naive() -------------------------------------------------------------------------------- /dynamic/python/coin_change.py: -------------------------------------------------------------------------------- 1 | 2 | def coin(goal, cursum, coins): 3 | if len(coins) == 0: 4 | return 0 5 | if cursum > goal: 6 | return 0 7 | if cursum == goal: 8 | return 1 9 | return coin(goal, cursum+coins[0], coins) + coin(goal, cursum, coins[1:]) 10 | 11 | 12 | print coin(100,0,[25,10,5,1]) 13 | -------------------------------------------------------------------------------- /graphs/BFS.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | import java.util.Queue; 6 | import java.util.LinkedList; 7 | import java.util.Set; 8 | 9 | public class BFS { 10 | 11 | public static void main(String[] args) { 12 | Graph g1 = new Graph(); 13 | Vertex v1 = g1.addVertex("A"); 14 | Vertex v2 = g1.addVertex("B"); 15 | Vertex v3 = g1.addVertex("C"); 16 | Vertex v4 = g1.addVertex("D"); 17 | Vertex v5 = g1.addVertex("E"); 18 | 19 | g1.addEdge(v1.getKey(),v2.getKey(),2); 20 | g1.addEdge(v1.getKey(),v3.getKey(),2); 21 | g1.addEdge(v2.getKey(),v3.getKey(),2); 22 | g1.addEdge(v2.getKey(),v4.getKey(),2); 23 | g1.addEdge(v3.getKey(),v4.getKey(),2); 24 | g1.addEdge(v4.getKey(),v5.getKey(),2); 25 | printGraph(g1); 26 | 27 | Vertex ans = BFS(g1,v1,"E"); 28 | System.out.println(ans.getKey().equals("E")); 29 | System.out.println(ans.getDistance() == 3); 30 | 31 | } 32 | 33 | public static Vertex BFS(Graph G, Vertex start, String val) { 34 | Queue queue = new LinkedList(); 35 | start.setDistance(0); 36 | queue.add(start); 37 | Vertex curVertex = start; 38 | while (queue.size() > 0) { 39 | curVertex = queue.poll(); 40 | if (curVertex.getKey() == val) { 41 | return curVertex; 42 | } 43 | for (String key : curVertex.getNeighbors()) { 44 | Vertex tmp = G.getVertex(key); 45 | if (tmp.getColor() == "white") { 46 | tmp.setColor("gray"); 47 | tmp.setDistance(curVertex.getDistance() + 1); 48 | queue.add(tmp); 49 | } 50 | } 51 | } 52 | return null; 53 | } 54 | 55 | public static void printGraph(Graph g) { 56 | Set vertices = g.getVertices(); 57 | for ( String vertex : vertices ) { 58 | System.out.print(vertex + " --> [ "); 59 | Vertex v = g.getVertex(vertex); 60 | for ( String neighbor : v.getNeighbors() ) { 61 | System.out.print("(" + neighbor + "," + v.getCost(neighbor) + ") "); 62 | } 63 | System.out.println("]\n"); 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /graphs/Graph.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import java.util.Map; 4 | import java.util.HashMap; 5 | import java.util.Set; 6 | import java.util.List; 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | 10 | 11 | public class Graph { 12 | 13 | Map vertices = new HashMap(); 14 | int numVertices = 0; 15 | 16 | 17 | public static void main(String[] args) { 18 | Graph g1 = new Graph(); 19 | Vertex v1 = g1.addVertex("A"); 20 | Vertex v2 = g1.addVertex("B"); 21 | Vertex v3 = g1.addVertex("C"); 22 | Vertex v4 = g1.addVertex("D"); 23 | 24 | g1.addEdge(v1.getKey(),v2.getKey(),9); 25 | g1.addEdge(v1.getKey(),v3.getKey(),2); 26 | printGraph(g1); 27 | System.out.println(v3.getIncomingEdges().size() == 1); 28 | v3.removeIncomingEdge(v1); 29 | System.out.println(v3.getIncomingEdges().size() == 0); 30 | 31 | } 32 | 33 | public Vertex addVertex(String key) { 34 | Vertex newVertex = new Vertex(key); 35 | vertices.put(key, newVertex); 36 | numVertices++; 37 | return newVertex; 38 | } 39 | 40 | public Vertex getVertex(String key) { 41 | return vertices.get(key); 42 | } 43 | 44 | public Set getVertices() { 45 | return vertices.keySet(); 46 | } 47 | 48 | public Collection getVerticesVals() { 49 | return vertices.values(); 50 | } 51 | 52 | public void addEdge(String from, String to, int cost) { 53 | if (!vertices.containsKey(to)) { 54 | addVertex(to); 55 | } 56 | Vertex toVertex = getVertex(to); 57 | Vertex fro = vertices.get(from); 58 | fro.addNeighbor(to, cost); 59 | toVertex.addIncomingEdge(fro); 60 | } 61 | 62 | public static void printGraph(Graph g) { 63 | Set vertices = g.getVertices(); 64 | for ( String vertex : vertices ) { 65 | System.out.print(vertex + " --> [ "); 66 | Vertex v = g.getVertex(vertex); 67 | for ( String neighbor : v.getNeighbors() ) { 68 | System.out.print("(" + neighbor + "," + v.getCost(neighbor) + ") "); 69 | } 70 | System.out.println("]\n"); 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /graphs/Vertex.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import java.util.Map; 4 | import java.util.HashMap; 5 | import java.util.Set; 6 | import java.util.List; 7 | import java.util.ArrayList; 8 | 9 | public class Vertex { 10 | 11 | String key; 12 | Map edges = new HashMap(); 13 | List incomingEdges = new ArrayList(); 14 | int totalEdges = 0; 15 | int distance; 16 | String color = "white"; 17 | Vertex predecessor; 18 | 19 | 20 | public Vertex(String key) { 21 | this.key = key; 22 | } 23 | public String getKey() { 24 | return this.key; 25 | } 26 | public void addNeighbor(String key, int weight) { 27 | this.edges.put(key,weight); 28 | totalEdges++; 29 | } 30 | public Set getNeighbors() { 31 | return this.edges.keySet(); //returns set of Keys 32 | } 33 | public Integer getCost(String neighbor) { 34 | return this.edges.get(neighbor); 35 | } 36 | public int getDistance() { 37 | return this.distance; 38 | } 39 | public String getColor() { 40 | return this.color; 41 | } 42 | public Vertex getPredecessor() { 43 | return this.predecessor; 44 | } 45 | public void setDistance(int distance) { 46 | this.distance = distance; 47 | } 48 | public void setColor(String color) { 49 | this.color = color; 50 | } 51 | public void setPredecessor(Vertex pred) { 52 | this.predecessor = pred; 53 | } 54 | public void addIncomingEdge(Vertex v) { 55 | this.incomingEdges.add(v); 56 | } 57 | public void removeIncomingEdge(Vertex v) { 58 | this.incomingEdges.remove(v); 59 | } 60 | public List getIncomingEdges() { 61 | return this.incomingEdges; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /graphs/python/Vertex.py: -------------------------------------------------------------------------------- 1 | class Vertex(object): 2 | def __init__(self, key): 3 | self.key = key 4 | self.neighbors = {} 5 | self.distance = 0 6 | self.predecessor = None 7 | 8 | def add_neighbor(self, neighbor, weight=0): 9 | self.neighbors[neighbor] = weight 10 | 11 | def add_neighbors(self, neighbors): 12 | for n in neighbors: 13 | self.add_neighbor(n) 14 | 15 | def get_neighbors(self): 16 | return self.neighbors 17 | 18 | def get_key(self): 19 | return self.key 20 | 21 | def get_weight(self, neighbor): 22 | return self.neighbors[neighbor] 23 | 24 | def __str__(self): 25 | return str(self.key) + ' neighbors: ' + str([x.key for x in self.neighbors]) 26 | 27 | 28 | if __name__ == "__main__": 29 | v1 = Vertex("A") 30 | v2 = Vertex("B") 31 | v3 = Vertex("C") 32 | v1.add_neighbor(v2,5) 33 | v1.add_neighbor(v3,10) 34 | v2.add_neighbor(v1,2) 35 | 36 | print v1 37 | print v2 38 | 39 | assert v1.get_weight(v2) == 5 40 | assert v1.get_weight(v3) == 10 41 | assert v2.get_weight(v1) == 2 42 | assert v1.get_key() == "A" 43 | assert v1.get_neighbors()[v2] == 5 44 | assert v1.get_neighbors()[v3] == 10 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /graphs/python/bfs.py: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | from Graph import build_test_graph 3 | from Vertex import Vertex 4 | 5 | def bfs(vertex, value): 6 | """ 7 | Input: starting Vertex, value to find 8 | Output: return closest Vertex that contains value 9 | 10 | Graph is a digraph. So it has cycles. Values can repeat. 11 | """ 12 | neighbors = [] 13 | visited = set() #all unique elements 14 | neighbors.append(vertex) 15 | while len(neighbors) > 0: 16 | vertex = neighbors.pop(0) 17 | if vertex.key == value: 18 | return vertex 19 | for neighbor in vertex.neighbors: 20 | if neighbor not in visited: 21 | neighbor.predecessor = vertex 22 | neighbor.distance = vertex.distance+1 23 | neighbors.append(neighbor) 24 | visited.add(neighbor) 25 | 26 | return None 27 | 28 | 29 | 30 | 31 | def test_bfs(): 32 | graph = build_test_graph() 33 | print graph 34 | 35 | vertices = graph.vertices 36 | v1 = vertices["A"] 37 | v2 = vertices["B"] 38 | v3 = vertices["C"] 39 | v4 = vertices["D"] 40 | v5 = vertices["E"] 41 | 42 | assert bfs(v1,"B") == v2 43 | assert bfs(v1,"C") == v3 44 | assert bfs(v1,"D") == v4 45 | assert bfs(v1,"E") == v5 46 | 47 | assert bfs(v2,"A") == v1 48 | assert bfs(v3,"A") == v1 49 | assert bfs(v3,"E") == v5 50 | 51 | if __name__ == "__main__": 52 | test_bfs() 53 | 54 | -------------------------------------------------------------------------------- /graphs/python/pretty_print.py: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | from Graph import build_test_graph 3 | from Vertex import Vertex 4 | 5 | """ 6 | Pretty Print 7 | 8 | Starting with a single Vertex, implement a method that prints out a 9 | string representation of a Graph that resembles a visual web 10 | 11 | Approach: 12 | 1) Using BFS, extract all unique vertices from the graph into set 13 | 2) Loop through vertices, plot each vertex into a arbitrary coordinates in matrix 14 | 3) Rearrange vertices in matrix until correctly positions 15 | 4) Pass matrix into format string method to print output 16 | 17 | """ 18 | 19 | def extract_vertices(vertex): 20 | """ 21 | Input: starting Vertex, value to find 22 | Output: return closest Vertex that contains value 23 | 24 | Graph is a digraph. So it has cycles. Values can repeat. 25 | """ 26 | neighbors = [] 27 | visited = set() #all unique elements 28 | neighbors.append(vertex) 29 | while len(neighbors) > 0: 30 | vertex = neighbors.pop(0) 31 | for neighbor in vertex.neighbors: 32 | if neighbor not in visited: 33 | neighbors.append(neighbor) 34 | visited.add(neighbor) 35 | return visited 36 | 37 | def plot_to_array(vertices): 38 | return [] 39 | 40 | def pretty_print(vertices_arr=[]): 41 | print vertices_arr 42 | 43 | 44 | 45 | def test_pretty_print(): 46 | graph = build_test_graph() 47 | graph.pretty_print() 48 | 49 | vertices = graph.vertices 50 | v1 = vertices[0] #A 51 | v2 = vertices[1] #B 52 | v3 = vertices[2] #C 53 | v4 = vertices[3] #D 54 | v5 = vertices[4] #E 55 | 56 | vertices_set = extract_vertices(graph.vertices[0]) 57 | print vertices_set 58 | 59 | if __name__ == "__main__": 60 | test_pretty_print() 61 | 62 | -------------------------------------------------------------------------------- /hashtables/ChainingHashTable.java: -------------------------------------------------------------------------------- 1 | package hashtables; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.LinkedList; 5 | import java.util.Arrays; 6 | 7 | 8 | public class ChainingHashTable implements HashTable { 9 | 10 | public Pair[] table; 11 | public static int BUCKETS = 10; 12 | 13 | public ChainingHashTable() { 14 | table = new Pair[BUCKETS]; 15 | } 16 | 17 | public void put(String key, String val) { 18 | Pair p = new Pair(key, val); 19 | int bucket = getBucketFromKey(key); 20 | if (table[bucket] == null) { 21 | table[bucket] = p; 22 | } else { 23 | Pair next = table[bucket]; 24 | while (next.getNext() != null) { 25 | next = next.getNext(); 26 | } 27 | next.setNext(p); 28 | } 29 | } 30 | 31 | public String get(String key) { 32 | int bucket = getBucketFromKey(key); 33 | if (table[bucket] == null) { 34 | return null; 35 | } else { 36 | Pair tmp = table[bucket]; 37 | while (tmp.getKey() != key) { 38 | tmp = tmp.getNext(); 39 | } 40 | if (tmp == null) { 41 | return null; 42 | } else { 43 | return tmp.getValue(); 44 | } 45 | } 46 | } 47 | 48 | public void remove(String key) { 49 | int bucket = getBucketFromKey(key); 50 | Pair prior = table[bucket]; 51 | Pair cur = table[bucket]; 52 | if (cur.getKey() == key) { 53 | table[bucket] = cur.getNext(); 54 | } else { 55 | while (cur.getKey() != key) { 56 | prior = cur; 57 | cur = cur.getNext(); 58 | } 59 | prior.setNext(cur.getNext()); 60 | } 61 | } 62 | 63 | public int getBucketFromKey(String key) { 64 | int sum = 0; 65 | int ascii; 66 | for (int i=0; i "); 36 | tmp = tmp.getNext(); 37 | } 38 | } 39 | System.out.println("\n------"); 40 | 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /hashtables/OpenAddressHashTable.java: -------------------------------------------------------------------------------- 1 | package hashtables; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.LinkedList; 5 | import java.util.Arrays; 6 | 7 | 8 | public class OpenAddressHashTable implements HashTable { 9 | 10 | public Pair[] table; 11 | public static int BUCKETS = 10; 12 | 13 | public OpenAddressHashTable() { 14 | table = new Pair[BUCKETS]; 15 | } 16 | 17 | public void put(String key, String val) { 18 | Pair p = new Pair(key, val); 19 | int bucket = getBucketFromKey(key); 20 | while (table[bucket] != null && table[bucket].getKey() != "DELETED") { 21 | bucket++; 22 | } 23 | table[bucket] = p; 24 | } 25 | 26 | public String get(String key) { 27 | int bucket = getBucketFromKey(key); 28 | while (table[bucket] != null && table[bucket].getKey() != key) { 29 | bucket++; 30 | } 31 | if (table[bucket] == null) { 32 | return null; 33 | } else { 34 | return table[bucket].getValue(); 35 | } 36 | } 37 | 38 | public void remove(String key) { 39 | int bucket = getBucketFromKey(key); 40 | while (table[bucket] != null && table[bucket].getKey() != key) { 41 | bucket++; 42 | } 43 | if (table[bucket] != null) { 44 | Pair deleted = new Pair("DELETED","DELETED"); 45 | table[bucket] = deleted; 46 | } 47 | } 48 | 49 | public int getBucketFromKey(String key) { 50 | int sum = 0; 51 | int ascii; 52 | for (int i=0; i 0: 20 | path_to_i.insert(0,i) 21 | i = i//2 22 | 23 | elem = None 24 | for i in path_to_i: 25 | if i % 2 == 0: 26 | elem = heap.get_left(i) 27 | else: 28 | elem = heap.get_right(i) 29 | heap.delete(elem) 30 | print "OUTPUT: " + str(heap.heap) 31 | return heap 32 | 33 | heap = delete_ith(mx_hp, 4) 34 | 35 | -------------------------------------------------------------------------------- /heaps/python/merge_k_sorted.py: -------------------------------------------------------------------------------- 1 | from Heap import Heap 2 | 3 | class MinMergeHeap(Heap): 4 | def __init__(self): 5 | Heap.__init__(self, "MIN_MERGE_HEAP") 6 | 7 | def get_min(self): 8 | return self.get_top() 9 | 10 | def delete_min(self): 11 | return self.delete(1) 12 | 13 | def compare_to(self, a, b): 14 | return a[0] < b[0] 15 | 16 | def build_merge_heap(arr): 17 | heap = MinMergeHeap() 18 | for i in range(len(arr)): 19 | heap.insert([arr[i],i]) 20 | return heap 21 | 22 | def merge_k_sorted(lists): 23 | heap = MinMergeHeap() 24 | 25 | # Add first element from each 26 | # list To Min Heap 27 | for k in range(len(lists)): 28 | if len(lists[k]) > 0: 29 | val = lists[k][0] 30 | pos_in_k = 0 31 | elem = [val,k,pos_in_k] 32 | heap.insert(elem) 33 | 34 | result = [] 35 | while heap.size > 0: 36 | next = heap.delete_min() 37 | val = next[0] 38 | k = next[1] 39 | pos_in_k = next[2] 40 | result.append(val) 41 | if pos_in_k+1 < len(lists[k]): 42 | new_pos_in_k = pos_in_k+1 43 | new_val = lists[k][new_pos_in_k] 44 | heap.insert([new_val,k,new_pos_in_k]) 45 | return result 46 | 47 | 48 | 49 | ##Tests 50 | 51 | h1 = build_merge_heap([0, 9, 5, 6, 2, 3]) 52 | assert h1.delete_min() == [0,0] 53 | assert h1.delete_min() == [2,4] 54 | assert h1.delete_min() == [3,5] 55 | 56 | 57 | A = [1,3,5] 58 | B = [2,4,6] 59 | C = [0,3] 60 | arrs = [A,B,C] 61 | print merge_k_sorted(arrs) 62 | 63 | 64 | -------------------------------------------------------------------------------- /heaps/python/test_data.py: -------------------------------------------------------------------------------- 1 | from Heap import MaxHeap, MinHeap 2 | from Heap import build_heap 3 | 4 | mx_hp = build_heap([0, 9, 5, 6, 2, 3],"MAX_HEAP") 5 | mn_hp = build_heap([0, 9, 5, 6, 2, 3],"MIN_HEAP") 6 | -------------------------------------------------------------------------------- /lists/CircularLinkedList.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.HashMap; 4 | 5 | public class CircularLinkedList { 6 | 7 | public static void main(String[] args) { 8 | SinglyLinkedList l1 = new SinglyLinkedList(); 9 | Node head = new Node("A"); 10 | l1.setHead(head); 11 | Node n1 = new Node("B"); 12 | head.setNext(n1); 13 | Node n2 = new Node("E"); 14 | n1.setNext(n2); 15 | Node n3 = new Node("C"); 16 | n2.setNext(n3); 17 | n3.setNext(n1); 18 | //System.out.println(getFirstNode(l1).getValue()); 19 | System.out.println(isCircular(l1)); 20 | } 21 | 22 | public static Node getFirstNode(SinglyLinkedList list) { 23 | HashMap map = new HashMap(); 24 | Node next = list.getHead(); 25 | while (next != null) { 26 | if (map.containsKey(next.getValue())) { 27 | return next; 28 | } else { 29 | map.put(next.getValue(),next.getValue()); 30 | next = next.getNext(); 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | public static boolean isCircular(SinglyLinkedList list) { 37 | Node f = list.getHead(); 38 | Node s = list.getHead(); 39 | while (f != null && f.getNext() != null) { 40 | f = f.getNext().getNext(); 41 | s = s.getNext(); 42 | if (s == f) { 43 | return true; 44 | } 45 | } 46 | return false; 47 | } 48 | 49 | public static Node getFirstNodeNoBuffer(SinglyLinkedList list) { 50 | 51 | return null; 52 | } 53 | 54 | public static void printLinkedList(SinglyLinkedList list) { 55 | Node next = list.getHead(); 56 | while (next != null) { 57 | System.out.print(next.getValue() + " --> "); 58 | next = next.getNext(); 59 | } 60 | System.out.println(""); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /lists/CloneLinkedList.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.*; 4 | 5 | public class CloneLinkedList { 6 | 7 | public static void main(String[] args) { 8 | CloneLinkedList clone = new CloneLinkedList(); 9 | Node n1 = new Node("A"); 10 | Node n2 = new Node("B"); 11 | Node n3 = new Node("C"); 12 | Node n4 = new Node("D"); 13 | n1.next = n2; 14 | n2.next = n3; 15 | n3.next = n4; 16 | n4.next = null; 17 | 18 | n1.random = n3; 19 | n2.random = n4; 20 | n3.random = n1; 21 | n4.random = n2; 22 | clone.printLinkedList(n1); 23 | 24 | Node copy = clone.getCopyOfList(n1); 25 | clone.printLinkedList(copy); 26 | } 27 | 28 | public static class Node { 29 | public T value; 30 | public Node next; 31 | public Node random; 32 | public Node(T val) { 33 | this.value = val; 34 | } 35 | } 36 | 37 | public Node getCopyOfList(Node firstOrg) { 38 | List> orgs = new ArrayList(); 39 | List> copies = new ArrayList(); 40 | Node firstCopy = new Node(firstOrg.value); 41 | Node org = firstOrg; 42 | Node copy = firstCopy; 43 | while (org.next != null) { 44 | Node newCopy = new Node(org.next.value); 45 | copy.next = newCopy; 46 | copies.add(copy); 47 | orgs.add(org); 48 | copy = copy.next; 49 | org = org.next; 50 | } 51 | copies.add(copy); 52 | orgs.add(org); 53 | 54 | copy = firstCopy; 55 | org = firstOrg; 56 | while (org != null) { 57 | int randIndex = orgs.indexOf(org.random); 58 | copy.random = orgs.get(randIndex); 59 | org = org.next; 60 | copy = copy.next; 61 | } 62 | return firstCopy; 63 | } 64 | 65 | public void printLinkedList(Node first) { 66 | while (first != null) { 67 | System.out.print(first.value + "(" + first.random.value + ")" + " --> "); 68 | first = first.next; 69 | } 70 | System.out.println(); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /lists/DeleteNode.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | import java.util.HashMap; 4 | 5 | public class DeleteNode { 6 | 7 | public static void main(String[] args) { 8 | SinglyLinkedList l1 = new SinglyLinkedList(); 9 | Node head = new Node("A"); 10 | l1.setHead(head); 11 | Node n1 = new Node("B"); 12 | head.setNext(n1); 13 | Node n2 = new Node("B"); 14 | n1.setNext(n2); 15 | Node n3 = new Node("C"); 16 | n2.setNext(n3); 17 | Node n4 = new Node("C"); 18 | n3.setNext(n4); 19 | n4.setNext(new Node("B")); 20 | printLinkedList(l1); 21 | deleteNode(n2); 22 | printLinkedList(l1); 23 | } 24 | 25 | public static void deleteNode(Node node) { 26 | Node next = node.getNext(); 27 | node.setValue(next.getValue()); 28 | node.setNext(next.getNext()); 29 | } 30 | 31 | public static void printLinkedList(SinglyLinkedList list) { 32 | Node next = list.getHead(); 33 | while (next != null) { 34 | System.out.print(next.getValue() + " --> "); 35 | next = next.getNext(); 36 | } 37 | System.out.println(""); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /lists/Node.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | public class Node { 4 | public Node next; 5 | public Node prior; 6 | public T value; 7 | 8 | public Node(T value) { 9 | this.value = value; 10 | } 11 | 12 | public void setNext(Node next) { 13 | this.next = next; 14 | } 15 | public void setPrior(Node prior) { 16 | this.prior = prior; 17 | } 18 | public void setValue(T value) { 19 | this.value = value; 20 | } 21 | public T getValue() { 22 | return this.value; 23 | } 24 | public Node getNext() { 25 | return this.next; 26 | } 27 | public Node getPrior() { 28 | return this.prior; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lists/NodeInteger.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | public class NodeInteger { 4 | NodeInteger next; 5 | NodeInteger prior; 6 | int value; 7 | int min; 8 | 9 | public NodeInteger(int value) { 10 | this.value = value; 11 | } 12 | 13 | public void setNext(NodeInteger next) { 14 | this.next = next; 15 | } 16 | public void setPrior(NodeInteger prior) { 17 | this.prior = prior; 18 | } 19 | public void setMin(int val) { 20 | this.min = val; 21 | } 22 | public int getMin() { 23 | return this.min; 24 | } 25 | public void setValue(int value) { 26 | this.value = value; 27 | } 28 | public int getValue() { 29 | return this.value; 30 | } 31 | public NodeInteger getNext() { 32 | return this.next; 33 | } 34 | public NodeInteger getPrior() { 35 | return this.prior; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /lists/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | public class ReverseLinkedList { 4 | 5 | public static void main(String[] args) { 6 | ReverseLinkedList rev = new ReverseLinkedList(); 7 | Node n1 = new Node("A"); 8 | Node n2 = new Node("B"); 9 | Node n3 = new Node("C"); 10 | Node n4 = new Node("D"); 11 | n1.next = n2; 12 | n2.next = n3; 13 | n3.next = n4; 14 | n4.next = null; 15 | rev.printLinkedList(n1); 16 | Node r1 = rev.reverseIterative(n1); 17 | rev.printLinkedList(r1); 18 | Node o1 = rev.reverseRecursive(r1,null); 19 | rev.printLinkedList(o1); 20 | Node r2 = rev.reverseRecursive2(o1); 21 | rev.printLinkedList(r2); 22 | } 23 | 24 | public Node reverseIterative(Node first) { 25 | if (first == null) { 26 | return null; 27 | } 28 | Node last = null; 29 | Node cur = first; 30 | while (cur != null) { 31 | Node next = cur.next; 32 | cur.next = last; 33 | last = cur; 34 | cur = next; 35 | } 36 | return last; 37 | } 38 | 39 | public Node reverseRecursive(Node cur, Node last) { 40 | if (cur == null) { 41 | return last; 42 | } 43 | Node next = cur.next; 44 | cur.next = last; 45 | return reverseRecursive(next, cur); 46 | } 47 | 48 | public Node reverseRecursive2(Node cur) { 49 | if (cur == null) { 50 | return null; 51 | } 52 | if (cur.next == null) { 53 | return cur; 54 | } 55 | Node next = cur.next; 56 | Node rest = reverseRecursive2(next); 57 | next.next = cur; 58 | cur.next = null; 59 | return rest; 60 | } 61 | 62 | public void printLinkedList(Node next) { 63 | while (next != null) { 64 | System.out.print(next.getValue() + " --> "); 65 | next = next.getNext(); 66 | } 67 | System.out.println(); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /lists/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | class SinglyLinkedList { 4 | Node head; 5 | public void setHead(Node head) { 6 | this.head = head; 7 | } 8 | public Node getHead() { 9 | return this.head; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /lists/SinglyLinkedListInteger.java: -------------------------------------------------------------------------------- 1 | package lists; 2 | 3 | class SinglyLinkedListInteger { 4 | NodeInteger head; 5 | public void setHead(NodeInteger head) { 6 | this.head = head; 7 | } 8 | public NodeInteger getHead() { 9 | return this.head; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /lists/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/lists/__init__.py -------------------------------------------------------------------------------- /lists/find_intersection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Quick node class 8 | struct Node { 9 | int value; 10 | Node *next; 11 | }; 12 | // Creates new nodes 13 | struct Node* newNode(int data) 14 | { 15 | struct Node* temp = new struct Node; 16 | temp->value = data; 17 | temp->next = NULL; 18 | } 19 | 20 | struct Node* find_intersection(Node *L1, Node *L2){ 21 | if (L1 == NULL || L2 == NULL) 22 | return NULL; 23 | int size1=0; 24 | int size2=0; 25 | 26 | Node* tmp1 = L1; 27 | Node* tmp2 = L2; 28 | // find sizes of the lists 29 | while (tmp1->next != NULL){ 30 | tmp1=tmp1->next; 31 | size1++; 32 | } 33 | while (tmp2->next != NULL){ 34 | tmp2=tmp2->next; 35 | size2++; 36 | } 37 | tmp1=L1; 38 | tmp2=L2; 39 | int difference = abs(size1-size2); 40 | //make the lists the same size 41 | if (size1 > size2){ 42 | for (int x=0;xnext; 44 | } 45 | if (size2 > size1){ 46 | for (int x=0;xnext; 48 | } 49 | // move both pointers through lists until they are the same node 50 | while (tmp1->next!=NULL && tmp2->next!= NULL){ 51 | if (tmp1 == tmp2){ 52 | cout << "success!\n"; 53 | return tmp1; 54 | } 55 | tmp1=tmp1->next; 56 | tmp2=tmp2->next; 57 | } 58 | 59 | cout << "no intersection found" << endl; 60 | return NULL; 61 | } 62 | 63 | int main(){ 64 | // create 2 Linked lists using Nodes 65 | struct Node *head1 = new struct Node; 66 | struct Node *head2 = new struct Node; 67 | // Construct linked list 1->0->1->8 68 | head2 = newNode(1); 69 | head2->next = newNode(0); 70 | head2->next->next = newNode(1); 71 | head2->next->next->next = newNode(8); 72 | 73 | // Construct linked list 1->2->1->8 74 | // where the second 1 is the intersection 75 | head1 = newNode(1); 76 | head1->next = newNode(2); 77 | head1->next->next = head2->next->next; 78 | 79 | find_intersection(head1,head2); 80 | 81 | return 0; 82 | } -------------------------------------------------------------------------------- /lists/python/DoublyNode.py: -------------------------------------------------------------------------------- 1 | class DoublyNode: 2 | def __init__(self, value, next=None, prev=None): 3 | self.value = value 4 | self.next = next 5 | self.prev = prev 6 | 7 | def get_value(self): 8 | return self.value 9 | 10 | def set_value(self, value): 11 | self.value = value 12 | 13 | def get_next(self): 14 | return self.next 15 | 16 | def set_next(self, next): 17 | self.next = next -------------------------------------------------------------------------------- /lists/python/Node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value, next=None): 3 | self.value = value 4 | self.next = next 5 | 6 | def get_value(self): 7 | return self.value 8 | 9 | def set_value(self, value): 10 | self.value = value 11 | 12 | def get_next(self): 13 | return self.next 14 | 15 | def set_next(self, next): 16 | self.next = next 17 | 18 | 19 | # Tests 20 | 21 | def test_get_set_node(): 22 | second_node = Node("B") 23 | head = Node("A", second_node) 24 | 25 | assert head.get_next() == second_node 26 | assert head.value == "A" 27 | 28 | head.set_value("Z") 29 | new_node = Node("C", second_node) 30 | head.set_next(new_node) 31 | 32 | assert head.value == "Z" 33 | assert head.get_next() == new_node 34 | 35 | next = head.get_next() 36 | assert next == new_node 37 | assert next.get_next() == second_node 38 | 39 | next = next.get_next() 40 | assert next == second_node 41 | assert next.get_next() is None 42 | 43 | if __name__ == "__main__": 44 | test_get_set_node() 45 | -------------------------------------------------------------------------------- /lists/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/lists/python/__init__.py -------------------------------------------------------------------------------- /lists/python/compare_two_lists.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from Node import Node 4 | 5 | """ 6 | Return True if Each Lists Contains 7 | The Same Values in the Same Order 8 | """ 9 | 10 | def compare_lists_recursive(headA, headB): 11 | if headA == None and headB == None: 12 | return True 13 | elif headA is None or headB is None: 14 | return False 15 | elif headA.value != headB.value: 16 | return False 17 | return compare_lists_recursive(headA.next, headB.next) 18 | 19 | def compare_lists_iterative(headA, headB): 20 | while headA is not None: 21 | if headB is None or headB.value != headA.value: 22 | return False 23 | headA = headA.next 24 | headB = headB.next 25 | return headB is None 26 | 27 | 28 | 29 | #Tests 30 | 31 | def test_compare_lists_recursive(): 32 | llA = build_ll_from_lst([2,4]) 33 | llB = build_ll_from_lst([2,4]) 34 | headA = llA.head 35 | headB = llB.head 36 | assert compare_lists_recursive(headA, headB) 37 | 38 | llA = build_ll_from_lst([2]) 39 | llB = build_ll_from_lst([2,4]) 40 | headA = llA.head 41 | headB = llB.head 42 | assert not compare_lists_recursive(headA, headB) 43 | 44 | def test_compare_lists_iterative(): 45 | llA = build_ll_from_lst([2,4]) 46 | llB = build_ll_from_lst([2,4]) 47 | headA = llA.head 48 | headB = llB.head 49 | assert compare_lists_iterative(headA, headB) 50 | 51 | llA = build_ll_from_lst([2]) 52 | llB = build_ll_from_lst([2,4]) 53 | headA = llA.head 54 | headB = llB.head 55 | assert not compare_lists_iterative(headA, headB) 56 | 57 | 58 | if __name__ == "__main__": 59 | test_compare_lists_recursive() 60 | test_compare_lists_iterative() 61 | 62 | -------------------------------------------------------------------------------- /lists/python/delete_kth_node.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from LinkedList import get_test_linked_list 4 | from Node import Node 5 | 6 | """ 7 | Delete Kth Node in LinkedList 8 | 9 | You're given the pointer to the head node of a linked list and 10 | the position of a node to delete. Delete the node at the given 11 | position and return the head node. A position of 0 indicates head, 12 | a position of 1 indicates one node away from the head and so on. 13 | """ 14 | 15 | def delete_kth_node(ll, k): 16 | '''Delete 0th node means 1st node''' 17 | i = 0 18 | node = ll.head 19 | if node is None: 20 | return ll 21 | if k == 0: 22 | ll.set_head(node.get_next()) 23 | return ll 24 | while i < k-1 and node.get_next() is not None: 25 | node = node.get_next() 26 | i += 1 27 | if node.get_next() is not None: 28 | new_next = node.get_next().get_next() 29 | node.set_next(new_next) 30 | return ll 31 | 32 | 33 | 34 | #Tests 35 | 36 | def test_delete_kth_node__empty_list(): 37 | # None --> 38 | empty_list = LinkedList() 39 | delete_kth_node(empty_list, 3) 40 | assert empty_list.head is None 41 | 42 | def test_delete_kth_node__one_element(): 43 | # A --> None 44 | head = Node("A") 45 | test_list = LinkedList(head) 46 | delete_kth_node(test_list, 1) 47 | assert test_list.head == head 48 | 49 | delete_kth_node(test_list, 3) 50 | assert test_list.head == head 51 | 52 | delete_kth_node(test_list, 0) 53 | assert test_list.head == None 54 | 55 | def test_delete_kth_node__three_elements(): 56 | # A --> B --> C --> None 57 | test_list = get_test_linked_list() 58 | delete_kth_node(test_list,4) 59 | delete_kth_node(test_list,3) 60 | delete_kth_node(test_list,1) 61 | delete_kth_node(test_list,0) 62 | assert test_list.head.value == "C" 63 | 64 | 65 | if __name__ == "__main__": 66 | test_delete_kth_node__empty_list() 67 | test_delete_kth_node__one_element() 68 | test_delete_kth_node__three_elements() 69 | -------------------------------------------------------------------------------- /lists/python/find_intersection.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from Node import Node 4 | 5 | """ 6 | Given pointers to the head nodes of 2 linked lists that merge 7 | together at some point, find the Node where the two lists merge. 8 | 9 | Assumptions: 10 | 1) Head nodes will not be NULL 11 | 2) Lists will always merge at some point 12 | 13 | Approaches: 14 | 1) Hashmap + 2 loops - Loop through first LL and add all object hash ids + value 15 | to hashmap. Loop through second and check if ID is in hashmap. Return value associated 16 | with first node found (since that would be first intersection) 17 | 2) O(1) space, but O(n^2) time? For each node in L1, loop through L2 and until NULL and check 18 | for intersection. Keep going until first intersection is found. Average case not terrible... 19 | 3) Linear time? Recursive? 20 | 21 | [List #1] a--->b--->c 22 | \ 23 | x--->y--->z--->NULL 24 | / 25 | [List #2] p--->q 26 | 27 | 1 28 | \ 29 | 2--->3--->NULL 30 | / 31 | 1 32 | #Returns 2 33 | 34 | 1--->2 35 | \ 36 | 3--->Null 37 | / 38 | 1 39 | #Returns 3 40 | 41 | """ 42 | 43 | def find_intersection_hashmap(headA, headB): 44 | hashmap = {} 45 | while headA is not None: 46 | hashmap[id(headA)] = headA.value 47 | headA = headA.next 48 | 49 | while headB is not None: 50 | hash_id = id(headB) 51 | if hashmap.get(hash_id) is not None: 52 | return hashmap[hash_id] 53 | headB = headB.next 54 | return None 55 | 56 | 57 | 58 | #Tests 59 | 60 | def test_find_intersection_hashmap(): 61 | fourth_node = Node("D") 62 | third_node = Node("C", fourth_node) 63 | second_node = Node("B", third_node) 64 | head1 = Node("A", second_node) 65 | 66 | second_node2 = Node("B2", third_node) 67 | head2 = Node("A2", second_node2) 68 | 69 | assert find_intersection_hashmap(head1, head2) == "C" 70 | 71 | 72 | 73 | if __name__ == "__main__": 74 | test_find_intersection_hashmap() 75 | 76 | -------------------------------------------------------------------------------- /lists/python/get_max_value.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | from LinkedList import LinkedList, build_ll_from_lst 4 | 5 | def get_max_value_in_list_iterative(node): 6 | max_val = node.value 7 | while node != None: 8 | if node.value > max_val: 9 | max_val = node.value 10 | node = node.get_next() 11 | return max_val 12 | 13 | def get_max_value_in_list_recursive(node): 14 | if node == None: 15 | return -sys.maxint 16 | else: 17 | return max(node.value, get_max_value_in_list_recursive( 18 | node.get_next())) 19 | 20 | 21 | 22 | # Tests 23 | 24 | def test_get_max_value_in_list_iterative(): 25 | l1 = build_ll_from_lst([1,2,3]) 26 | node = l1.head 27 | assert get_max_value_in_list_iterative(node) == 3 28 | 29 | l1 = build_ll_from_lst([1]) 30 | node = l1.head 31 | assert get_max_value_in_list_iterative(node) == 1 32 | 33 | l1 = build_ll_from_lst([1,3]) 34 | node = l1.head.get_next() 35 | assert get_max_value_in_list_iterative(node) == 3 36 | 37 | def test_get_max_value_in_list_recursive(): 38 | l1 = build_ll_from_lst([1,2,3]) 39 | node = l1.head 40 | assert get_max_value_in_list_recursive(node) == 3 41 | 42 | l1 = build_ll_from_lst([1]) 43 | node = l1.head 44 | assert get_max_value_in_list_recursive(node) == 1 45 | 46 | l1 = build_ll_from_lst([1,3]) 47 | node = l1.head.get_next() 48 | assert get_max_value_in_list_recursive(node) == 3 49 | 50 | 51 | if __name__ == "__main__": 52 | test_get_max_value_in_list_iterative() 53 | test_get_max_value_in_list_recursive() 54 | -------------------------------------------------------------------------------- /lists/python/insert_doubly_linked_node.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_doubly_ll_from_lst 3 | from DoublyNode import DoublyNode 4 | 5 | 6 | """ 7 | Insert node into a sorted doubly linked list 8 | 9 | You're given the pointer to the head node of a sorted doubly 10 | linked list and an integer to insert into the list. Create a node 11 | and insert it into the appropriate position in the list. 12 | The head node might be NULL to indicate that the list is empty. 13 | """ 14 | 15 | 16 | def insert_node_into_sorted_doubly_ll(ll, new_node): 17 | if ll.head is None: 18 | return LinkedList(new_node) 19 | prev_node = ll.head 20 | cur_node = ll.head.next 21 | while cur_node is not None: 22 | if new_node.value <= cur_node.value: 23 | prev_node.next = new_node 24 | new_node.next = cur_node 25 | new_node.prev = prev_node 26 | cur_node.prev = new_node 27 | return ll 28 | prev_node = cur_node 29 | cur_node = cur_node.next 30 | prev_node.next = new_node 31 | new_node.prev = prev_node 32 | return ll 33 | 34 | 35 | 36 | # Tests 37 | 38 | def test_insert_node_into_sorted_doubly_ll(): 39 | inputlist = build_doubly_ll_from_lst([]) 40 | answerlist = build_doubly_ll_from_lst([1]) 41 | outputlist = insert_node_into_sorted_doubly_ll(inputlist, DoublyNode(1)) 42 | assert answerlist.lists_eq(outputlist) 43 | 44 | inputlist = build_doubly_ll_from_lst([1,2,4]) 45 | answerlist = build_doubly_ll_from_lst([1,2,3,4]) 46 | outputlist = insert_node_into_sorted_doubly_ll(inputlist,DoublyNode(3)) 47 | assert answerlist.lists_eq(outputlist) 48 | 49 | inputlist = build_doubly_ll_from_lst([1,2,4]) 50 | answerlist = build_doubly_ll_from_lst([1,2,4,6]) 51 | outputlist = insert_node_into_sorted_doubly_ll(inputlist,DoublyNode(6)) 52 | assert answerlist.lists_eq(outputlist) 53 | 54 | if __name__ == "__main__": 55 | test_insert_node_into_sorted_doubly_ll() -------------------------------------------------------------------------------- /lists/python/insert_nth_node.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from Node import Node 4 | 5 | 6 | """ 7 | Insert Node at Nth Position in LinkedList 8 | 9 | You're given the pointer to the head node of a linked list, 10 | an integer to add to the list and the position at which the 11 | integer must be inserted. Create a new node with the given integer, 12 | insert this node at the desired position and return the head node. 13 | A position of 0 indicates head, a position of 1 indicates one node 14 | away from the head and so on. 15 | """ 16 | 17 | def insert_nth(head, val, position): 18 | """ 19 | Insert value at position N in list 20 | pos = 0 == head 21 | """ 22 | if head is None or position == 0: 23 | return LinkedList(Node(val, head)) 24 | i = 1 25 | prior_node = head 26 | cur_node = head.next 27 | while i < position: 28 | prior_node = cur_node 29 | cur_node = cur_node.next 30 | i+=1 31 | new_node = Node(val, cur_node) 32 | prior_node.next = new_node 33 | return LinkedList(head) 34 | 35 | 36 | 37 | # Tests 38 | 39 | def test_insert_nth(): 40 | inputlist = build_ll_from_lst([1,2,4]) 41 | answerlist = build_ll_from_lst([1,2,3,4]) 42 | outputlist = insert_nth(inputlist.head, 3,2) 43 | assert answerlist.lists_eq(outputlist) 44 | 45 | inputlist = build_ll_from_lst([1,2,4]) 46 | answerlist = build_ll_from_lst([0,1,2,4]) 47 | outputlist = insert_nth(inputlist.head, 0,0) 48 | assert answerlist.lists_eq(outputlist) 49 | 50 | if __name__ == "__main__": 51 | test_insert_nth() -------------------------------------------------------------------------------- /lists/python/merge_sort_linked_list.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from Node import Node 3 | from LinkedList import build_ll_from_lst 4 | 5 | """ 6 | Merge Sort Linked List 7 | """ 8 | 9 | def sort(head): 10 | if head == None: 11 | return None 12 | if head.next == None: 13 | return head 14 | mid = get_middle_node(head) 15 | left = sort(head) 16 | right = sort(mid) 17 | return merge(left, right) 18 | 19 | def merge(left, right): 20 | before_head = Node(None) 21 | cur = before_head 22 | while left != None: 23 | if right == None or left.value <= right.value: 24 | cur.next = left 25 | left = left.next 26 | else: 27 | cur.next = right 28 | right = right.next 29 | cur = cur.next 30 | cur.next = right 31 | return before_head.next 32 | 33 | def get_middle_node(head): 34 | before_slow = head 35 | slow = head 36 | fast = head 37 | while fast != None: 38 | fast = fast.next 39 | if fast != None: 40 | before_slow = slow 41 | fast = fast.next 42 | slow = slow.next 43 | before_slow.next = None 44 | return slow 45 | 46 | 47 | 48 | ## Test Get Middle Node 49 | t0 = build_ll_from_lst([5,3,6,2]) 50 | print get_middle_node(t0.head).value == 6 51 | 52 | 53 | ## Test Merge 54 | t1 = build_ll_from_lst([1,3,4,6]).head 55 | t2 = build_ll_from_lst([2,3,5]).head 56 | print LinkedList(merge(t1,t2)).get_linked_list_str() 57 | 58 | ## Test Sort 59 | t4 = build_ll_from_lst([5,3,6,2,14,7,2,3]) 60 | t5 = build_ll_from_lst([3,2,1]) 61 | t6 = build_ll_from_lst([3,2,2,3]) 62 | t7 = build_ll_from_lst([1]) 63 | t8 = build_ll_from_lst([4,2,3,1,6,3,2]) 64 | print LinkedList(sort(t4.head)).get_linked_list_str() 65 | print LinkedList(sort(t5.head)).get_linked_list_str() 66 | print LinkedList(sort(t6.head)).get_linked_list_str() 67 | print LinkedList(sort(t7.head)).get_linked_list_str() 68 | print LinkedList(sort(t8.head)).get_linked_list_str() 69 | -------------------------------------------------------------------------------- /lists/python/nth_node_from_tail.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from Node import Node 4 | 5 | """ 6 | Return data in Nth node from the end 7 | head could be None as well for empty list 8 | 9 | # Approaches 10 | 1) Use a queue to keek track of last pos_from_tail values, then dequeue at end 11 | 2) Use list, then return list[len(list)-pos_from_tail] 12 | 3) Two loops. Find length, then stop when you get to Node (if you can't use data structure) 13 | """ 14 | 15 | def get_nth_node_from_tail(node, pos_from_tail): 16 | if node is None: 17 | return None 18 | vals_list = [] 19 | while node is not None: 20 | vals_list.append(node.value) 21 | node = node.next 22 | return vals_list[len(vals_list) - pos_from_tail - 1] 23 | 24 | 25 | 26 | # Tests 27 | 28 | def test_get_nth_node_from_tail(): 29 | l1 = build_ll_from_lst([1,2,3]) 30 | node = l1.head 31 | assert get_nth_node_from_tail(node,0) == 3 32 | assert get_nth_node_from_tail(node,1) == 2 33 | assert get_nth_node_from_tail(node,2) == 1 34 | 35 | if __name__ == "__main__": 36 | test_get_nth_node_from_tail() -------------------------------------------------------------------------------- /lists/python/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_ll_from_lst 3 | from Node import Node 4 | 5 | 6 | 7 | def remove_duplicates_sorted(head): 8 | start = head 9 | while head is not None: 10 | while head.next is not None and \ 11 | head.value == head.next.value: 12 | head.next = head.next.next 13 | head = head.next 14 | return LinkedList(start) 15 | 16 | def remove_duplicates_unsorted(head): 17 | if head is None: 18 | return LinkedList(head) 19 | hashmap = {} 20 | hashmap[head.value] = 1 21 | prior = head 22 | cur = head.next 23 | while cur is not None: 24 | if hashmap.get(cur.value) is not None: 25 | prior.next = cur.next 26 | else: 27 | hashmap[cur.value] = 1 28 | prior = cur 29 | cur = cur.next 30 | return LinkedList(head) 31 | 32 | 33 | 34 | #Tests 35 | 36 | def test_remove_duplicates_sorted(): 37 | l1 = build_ll_from_lst([1,2,2,3,3,4]) 38 | l2 = build_ll_from_lst([1,1,1,1,1,1,1]) 39 | l3 = build_ll_from_lst([2,3,3,4,6]) 40 | l4 = build_ll_from_lst([10]) 41 | 42 | a1 = build_ll_from_lst([1,2,3,4]) 43 | a2 = build_ll_from_lst([1]) 44 | a3 = build_ll_from_lst([2,3,4,6]) 45 | a4 = build_ll_from_lst([10]) 46 | 47 | assert remove_duplicates_sorted(l1.head).lists_eq(a1) 48 | assert remove_duplicates_sorted(l2.head).lists_eq(a2) 49 | assert remove_duplicates_sorted(l3.head).lists_eq(a3) 50 | assert remove_duplicates_sorted(l4.head).lists_eq(a4) 51 | 52 | def test_remove_duplicates_unsorted(): 53 | l1 = build_ll_from_lst([1,2,4,2,1,3,7,3,4]) 54 | l2 = build_ll_from_lst([1,1,1,1,1,1,1]) 55 | l3 = build_ll_from_lst([6,2,4,3,3,4,6]) 56 | l4 = build_ll_from_lst([10]) 57 | 58 | a1 = build_ll_from_lst([1,2,4,3,7]) 59 | a2 = build_ll_from_lst([1]) 60 | a3 = build_ll_from_lst([6,2,4,3]) 61 | a4 = build_ll_from_lst([10]) 62 | 63 | assert remove_duplicates_unsorted(l1.head).lists_eq(a1) 64 | assert remove_duplicates_unsorted(l2.head).lists_eq(a2) 65 | assert remove_duplicates_unsorted(l3.head).lists_eq(a3) 66 | assert remove_duplicates_unsorted(l4.head).lists_eq(a4) 67 | 68 | if __name__ == "__main__": 69 | test_remove_duplicates_sorted() 70 | test_remove_duplicates_unsorted() 71 | -------------------------------------------------------------------------------- /lists/python/reverse_doubly_linked_list.py: -------------------------------------------------------------------------------- 1 | from LinkedList import LinkedList 2 | from LinkedList import build_doubly_ll_from_lst 3 | from DoublyNode import DoublyNode 4 | 5 | 6 | """ 7 | Reverse a doubly linked list 8 | 9 | The head node might be NULL to indicate that the list is empty. 10 | ----------- 11 | None <- A <-> B <-> C -> None 12 | 13 | None <- C <-> B <-> A -> None 14 | 15 | p c n 16 | 1 <-> 2 -> None 17 | 18 | 2 <-> 1 -> None 19 | """ 20 | 21 | def reverse_doubly_ll(ll): 22 | if ll.head is None or ll.head.next is None: 23 | return ll 24 | cur_node = ll.head 25 | while cur_node is not None: 26 | prev_node = cur_node 27 | next_node = cur_node.next 28 | cur_node.next = cur_node.prev 29 | cur_node.prev = cur_node.next 30 | cur_node = next_node 31 | return LinkedList(prev_node) 32 | 33 | 34 | 35 | 36 | # Tests 37 | 38 | def test_reverse_doubly_ll(): 39 | inputlist = build_doubly_ll_from_lst([]) 40 | answerlist = build_doubly_ll_from_lst([]) 41 | outputlist = reverse_doubly_ll(inputlist) 42 | assert answerlist.lists_eq(outputlist) 43 | 44 | inputlist = build_doubly_ll_from_lst([1]) 45 | answerlist = build_doubly_ll_from_lst([1]) 46 | outputlist = reverse_doubly_ll(inputlist) 47 | assert answerlist.lists_eq(outputlist) 48 | 49 | inputlist = build_doubly_ll_from_lst([1,2,4]) 50 | answerlist = build_doubly_ll_from_lst([4,2,1]) 51 | outputlist = reverse_doubly_ll(inputlist) 52 | assert answerlist.lists_eq(outputlist) 53 | 54 | inputlist = build_doubly_ll_from_lst([1,2]) 55 | answerlist = build_doubly_ll_from_lst([2,1]) 56 | outputlist = reverse_doubly_ll(inputlist) 57 | assert answerlist.lists_eq(outputlist) 58 | 59 | inputlist = build_doubly_ll_from_lst([1,1,1]) 60 | answerlist = build_doubly_ll_from_lst([1,1,1]) 61 | outputlist = reverse_doubly_ll(inputlist) 62 | assert answerlist.lists_eq(outputlist) 63 | 64 | if __name__ == "__main__": 65 | test_reverse_doubly_ll() -------------------------------------------------------------------------------- /math/Counter.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | public class Counter { 4 | 5 | public int count = 0; 6 | 7 | public static void main(String[] args) {} 8 | 9 | public void increment() { 10 | this.count++; 11 | } 12 | public int tally() { 13 | return this.count; 14 | } 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /math/PowersOfTwo.java: -------------------------------------------------------------------------------- 1 | public class PowersOfTwo { 2 | 3 | public static void main(String[] args) { 4 | int in = 3; 5 | int out = 256; 6 | System.out.println(getPowerOfTwo(in) == out); 7 | } 8 | 9 | /* 10 | * Compute 2^2^n in linear time 11 | */ 12 | public static int getPowerOfTwo(int n) { 13 | if (n == 0) { 14 | return 2; 15 | } else { 16 | return getPowerOfTwo(n-1) * getPowerOfTwo(n-1); 17 | } 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /math/SwapIntegers.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | public class SwapIntegers { 4 | 5 | public static void main(String[] args) { 6 | int[] arr = new int[5]; 7 | int a = 4; 8 | int b = 3; 9 | arr[1] = a; 10 | arr[3] = b; 11 | arr = swapIntegers(arr, 1, 3); 12 | System.out.println(arr[1] == b && arr[3] == a); 13 | 14 | arr[1] = -7; 15 | arr[3] = -3; 16 | arr = swapIntegers(arr, 1, 3); 17 | System.out.println(arr[1] == -3 && arr[3] == -7); 18 | } 19 | 20 | /* 21 | * Swap two integers in an array without using tmp variables 22 | */ 23 | public static int[] swapIntegers(int[] arr, int a, int b) { 24 | arr[a] = arr[a] + arr[b]; //4 + 3 = 7 25 | arr[b] = arr[a] - arr[b]; //7 - 3 = 4 26 | arr[a] = arr[a] - arr[b]; //7 - 4 = 3 27 | return arr; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /math/python/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | import math 2 | """ 3 | IN: integer representing binary number 4 | OUT: integer representing deimal number 5 | """ 6 | def binary_to_decimal(binary): 7 | decimal = 0 8 | exponent = 0 9 | while binary > 0: 10 | last_digit = binary % 10 11 | decimal += (last_digit * math.pow(2,exponent)) 12 | binary /= 10 13 | exponent += 1 14 | return int(decimal) 15 | 16 | def decimal_to_binary(decimal): 17 | if decimal == 0: 18 | return "0" 19 | binary = "" 20 | while decimal > 0: 21 | digit = decimal % 2 22 | decimal = decimal / 2 23 | binary = str(digit) + binary 24 | return binary 25 | 26 | def decimal_to_hexadecimal(decimal): 27 | if decimal == 0: 28 | return "0" 29 | binary = "" 30 | while decimal > 0: 31 | digit = decimal % 2 32 | decimal = decimal / 2 33 | binary = str(digit) + binary 34 | return binary 35 | 36 | print binary_to_decimal(101010) 37 | print binary_to_decimal(1) 38 | print binary_to_decimal(0) 39 | print binary_to_decimal(111) 40 | 41 | print decimal_to_binary(10) 42 | print decimal_to_binary(0) 43 | print decimal_to_binary(1) -------------------------------------------------------------------------------- /math/python/excel_column_number.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def column_title_to_num(A): 4 | L="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 5 | total = 0 6 | exponent = len(A)-1 7 | for char in A: 8 | decimal = L.find(char)+1 #ord(char)-ord("A")+1 9 | total += (decimal * math.pow(26,exponent)) 10 | exponent-=1 11 | return int(total) 12 | 13 | print column_title_to_num("A") == 1 14 | print column_title_to_num("Z") == 26 15 | print column_title_to_num("AA") == 27 16 | print column_title_to_num("AB") == 28 17 | print column_title_to_num("ZZZZZ") -------------------------------------------------------------------------------- /math/python/gcd.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def gcd(A, B): 4 | if A == 0: 5 | return B 6 | if B == 0: 7 | return A 8 | max_found = 1 9 | if A < B: 10 | small = A 11 | large = B 12 | else: 13 | small = B 14 | large = A 15 | stop = int(math.sqrt(small)) 16 | i = 1 17 | while i <= stop: 18 | sf = i 19 | lf = small/i 20 | if small % lf == 0 and large % lf == 0: 21 | return lf 22 | if small % sf == 0 and large % sf == 0: 23 | if sf > max_found: 24 | max_found = sf 25 | i+=1 26 | return max_found 27 | 28 | 29 | 30 | """ 31 | Euclid's GCD 32 | ------------- 33 | gcd(16,12) 34 | 16 % 12 == 4 35 | gcd(12,4) 36 | 12 % 4 == 0 37 | gcd(4,0) 38 | return small == 4 39 | """ 40 | def gcd_euclids(large, small): 41 | if small == 0: 42 | return large 43 | return gcd(small, large % small) 44 | 45 | 46 | print "gcd_better-----" 47 | print gcd_euclids(12,15) 48 | print gcd_euclids(9,3) 49 | print gcd_euclids(9,6) 50 | print gcd_euclids(16,12) 51 | print gcd_euclids(16,8) 52 | print gcd_euclids(16,16) 53 | print gcd_euclids(16,1) 54 | print gcd_euclids(16,0) 55 | print gcd_euclids(7,5) 56 | 57 | print "gcd--------" 58 | print gcd(16,12) 59 | print gcd(16,8) 60 | print gcd(16,16) 61 | print gcd(16,1) 62 | print gcd(16,0) 63 | print gcd(7,5) -------------------------------------------------------------------------------- /math/python/get_all_primes.py: -------------------------------------------------------------------------------- 1 | #A == Integer 2 | #Get all primes up to A 3 | #interviewbit.com/problems/prime-numbers/ 4 | def sieve(A): 5 | primes = [] 6 | nums = [n for n in range(A+1)] 7 | for i in range(2, len(nums)): 8 | if nums[i] is not None: 9 | primes.append(nums[i]) 10 | set_multiples_to_none(nums[i], nums) 11 | return primes 12 | 13 | def set_multiples_to_none(n, nums): 14 | i=2 15 | while n*i < len(nums): 16 | nums[n*i] = None 17 | i+=1 18 | 19 | 20 | print sieve(10) == [2,3,5,7] -------------------------------------------------------------------------------- /math/python/grid_unique_paths.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | # @param A : integer 5 | # @param B : integer 6 | # @return an integer 7 | def uniquePathsRecurse(self, A, B): 8 | if A == 1 or B == 1: 9 | return 1 10 | paths = 0 11 | if B-1 > 0: 12 | paths += self.uniquePathsRecurse(A,B-1) 13 | if A-1 > 0: 14 | paths += self.uniquePathsRecurse(A-1, B) 15 | return paths 16 | 17 | def uniquePathsMath(self, A, B): 18 | down = A-1 19 | right = B-1 #M 20 | total_steps = down + right #N 21 | return math.factorial(total_steps) / (math.factorial(right) \ 22 | * math.factorial(total_steps - right)) 23 | 24 | def uniquePathsDP(self, A, B): 25 | grid = [[0 for X in range(B)] for x in range(A)] 26 | #set first row to zero 27 | for i in range(len(grid[0])): 28 | grid[0][i] = 1 29 | #set first col to zero 30 | for i in range(len(grid)): 31 | grid[i][0] = 1 32 | row = 1 33 | col = 1 34 | while row < A: 35 | i = col 36 | while i < B: 37 | above = grid[row-1][i] 38 | left = grid[row][i-1] 39 | grid[row][i] = above + left 40 | i+=1 41 | row+=1 42 | return grid[A-1][B-1] 43 | 44 | 45 | sol = Solution() 46 | print sol.uniquePathsRecurse(9, 15) == 319770 47 | print sol.uniquePathsMath(9, 15) == 319770 48 | print sol.uniquePathsDP(9, 15) == 319770 -------------------------------------------------------------------------------- /math/python/integer_palindrome.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | # @param A : integer 5 | # @return a boolean value ( True / False ) 6 | def get_digit_count(self, num): 7 | if num == 0: 8 | return 1 9 | count = 0 10 | while num > 0: 11 | count += 1 12 | num /= 10 13 | return count 14 | 15 | def reverse_num(self, num): 16 | tens = self.get_digit_count(num)-1 17 | reversed_num = 0 18 | while num > 0: 19 | digit = num % 10 20 | reversed_num += (digit * math.pow(10,tens)) 21 | tens -= 1 22 | num /= 10 23 | return reversed_num 24 | 25 | def isPalindrome(self, num): 26 | if num < 0: 27 | return False 28 | return self.reverse_num(num) == num 29 | 30 | sol = Solution() 31 | print sol.isPalindrome(12121) 32 | print sol.isPalindrome(1) 33 | print sol.isPalindrome(0) 34 | print sol.isPalindrome(00) 35 | print sol.isPalindrome(111) 36 | print sol.isPalindrome(11) 37 | print sol.isPalindrome(101) 38 | #False 39 | print sol.isPalindrome(1000021) -------------------------------------------------------------------------------- /math/python/prime_sum.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | # @param A : integer 5 | # @return a list of integers 6 | def primesum(self, A): 7 | if A <= 2: 8 | return [] 9 | prime = 2 10 | while not self.is_prime(A - prime): 11 | prime = self.get_next_prime(prime) 12 | return [prime, A-prime] 13 | 14 | def get_next_prime(self, n): 15 | i = n + 1 16 | while True: 17 | if self.is_prime(i): 18 | return i 19 | i+=1 20 | 21 | def is_prime(self, n): 22 | if n < 2: 23 | return False 24 | i = 2 25 | while i <= int(math.sqrt(n)): 26 | if n % i == 0: 27 | return False 28 | i+=1 29 | return True 30 | 31 | 32 | sol = Solution() 33 | 34 | print sol.primesum(34) == [3,31] 35 | print sol.primesum(4) == [2,2] -------------------------------------------------------------------------------- /math/python/rearrange_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # Modify the array A which is passed by reference. 4 | # You do not need to return anything in this case. 5 | def arrange(self, A): 6 | i = 0 7 | while i < len(A): 8 | if i == A[i]: 9 | i+=1 10 | else: 11 | tmp = A[i] 12 | A[i] = A[tmp] 13 | A[tmp] = tmp 14 | 15 | def arrangeRecursive(self, A): 16 | self.recurse(A, 0) 17 | 18 | def recurse(self, A, cur_index): 19 | """ 20 | In-place arrange but O(n) space 21 | """ 22 | if cur_index >= len(A): 23 | return 24 | override = A[A[cur_index]] 25 | self.recurse(A,cur_index+1) 26 | A[cur_index] = override 27 | return 28 | 29 | sol = Solution() 30 | 31 | A = [4,0,2,1,3] 32 | sol.arrange(A) 33 | print A 34 | 35 | A = [4,0,2,1,3] 36 | sol.arrangeRecursive(A) 37 | print A -------------------------------------------------------------------------------- /math/smallest_num_greaterThan_k.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find the smallest number which greater than a given number 2 | // and has same set of digits as given number 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Utility function to swap two digits 9 | void swap(char *a, char *b) 10 | { 11 | char temp = *a; 12 | *a = *b; 13 | *b = temp; 14 | } 15 | 16 | // Given a number as a char array number[], this function finds the 17 | // next greater number. It modifies the same array to store the result 18 | void findNext(char number[], int n) 19 | { 20 | int i, j; 21 | 22 | // I) Start from the right most digit and find the first digit that is 23 | // smaller than the digit next to it. 24 | for (i = n-1; i > 0; i--) 25 | if (number[i] > number[i-1]) 26 | break; 27 | 28 | // If no such digit is found, then all digits are in descending order 29 | // means there cannot be a greater number with same set of digits 30 | if (i==0) 31 | { 32 | cout << "Next number is not possible"; 33 | return; 34 | } 35 | 36 | // II) Find the smallest digit on right side of (i-1)'th digit that is 37 | // greater than number[i-1] 38 | int x = number[i-1], smallest = i; 39 | for (j = i+1; j < n; j++) 40 | if (number[j] > x && number[j] < number[smallest]) 41 | smallest = j; 42 | 43 | // III) Swap the above found smallest digit with number[i-1] 44 | swap(&number[smallest], &number[i-1]); 45 | 46 | // IV) Sort the digits after (i-1) in ascending order 47 | sort(number + i, number + n); 48 | 49 | cout << "Next number with same set of digits is " << number; 50 | 51 | return; 52 | } 53 | 54 | // Driver program to test above function 55 | int main() 56 | { 57 | char digits[] = "534976"; 58 | int n = strlen(digits); 59 | findNext(digits, n); 60 | return 0; 61 | } -------------------------------------------------------------------------------- /powerset/PowersetIterative.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | 4 | public class PowersetIterative { 5 | public static String[] set1; 6 | 7 | public static void main(String[] m) { 8 | set1 = new String[6]; 9 | set1[0] = "a"; 10 | set1[1] = "b"; 11 | set1[2] = "c"; 12 | set1[3] = "d"; 13 | set1[4] = "e"; 14 | set1[5] = "f"; 15 | ArrayList pset = getPowerset(set1); 16 | System.out.println(pset.size()); 17 | for (String[] arr : pset) { 18 | System.out.print(Arrays.toString(arr) + " "); 19 | } 20 | } 21 | 22 | public static ArrayList subsetsM(String[] set, int m, int mPos, int setPos) { 23 | ArrayList setsOfM = new ArrayList(); 24 | while (mPos > 0 && setPos <= (set.length - mPos)) { 25 | ArrayList subs = subsetsM(set, m, mPos-1, setPos+1); 26 | for (String[] s : subs) { 27 | s[mPos-1] = set[setPos]; 28 | setsOfM.add(s); 29 | } 30 | setPos++; 31 | } 32 | if (setsOfM.size() == 0) { 33 | String[] emptySet = new String[m]; 34 | setsOfM.add(emptySet); 35 | } 36 | return setsOfM; 37 | } 38 | 39 | public static ArrayList getPowerset(String[] set) { 40 | ArrayList pset = new ArrayList(); 41 | int m = 1; 42 | while (m <= set.length){ 43 | ArrayList subsetsLengthM = subsetsM(set, m, m, 0); 44 | for (String[] s : subsetsLengthM) { 45 | pset.add(s); 46 | } 47 | m++; 48 | } 49 | String[] emptySet = {}; 50 | pset.add(emptySet); 51 | return pset; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /powerset/PowersetRecursive.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | 4 | public class PowersetIterative { 5 | public static String[] set1; 6 | 7 | public static void main(String[] m) { 8 | set1 = new String[6]; 9 | set1[0] = "a"; 10 | set1[1] = "b"; 11 | set1[2] = "c"; 12 | set1[3] = "d"; 13 | set1[4] = "e"; 14 | set1[5] = "f"; 15 | ArrayList pset = getPowerset(set1); 16 | System.out.println(pset.size()); 17 | for (String[] arr : pset) { 18 | System.out.print(Arrays.toString(arr) + " "); 19 | } 20 | } 21 | 22 | public static ArrayList subsetsM(String[] set, int m, int mPos, int setPos) { 23 | ArrayList setsOfM = new ArrayList(); 24 | while (mPos > 0 && setPos <= (set.length - mPos)) { 25 | ArrayList subs = subsetsM(set, m, mPos-1, setPos+1); 26 | for (String[] s : subs) { 27 | s[mPos-1] = set[setPos]; 28 | setsOfM.add(s); 29 | } 30 | setPos++; 31 | } 32 | if (setsOfM.size() == 0) { 33 | String[] emptySet = new String[m]; 34 | setsOfM.add(emptySet); 35 | } 36 | return setsOfM; 37 | } 38 | 39 | public static ArrayList getPowerset(String[] set) { 40 | ArrayList pset = new ArrayList(); 41 | int m = 1; 42 | while (m <= set.length){ 43 | ArrayList subsetsLengthM = subsetsM(set, m, m, 0); 44 | for (String[] s : subsetsLengthM) { 45 | pset.add(s); 46 | } 47 | m++; 48 | } 49 | String[] emptySet = {}; 50 | pset.add(emptySet); 51 | return pset; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /powerset/iterative_mike_1.py: -------------------------------------------------------------------------------- 1 | def all_chars_in(list1, val): 2 | for e in str(val): 3 | if int(e) not in list1: 4 | return False 5 | return True 6 | 7 | def num_in_order(num): 8 | prior = str(num)[0] 9 | for i in range(1,len(str(num))): 10 | cur = str(num)[i] 11 | if int(cur) < int(prior): 12 | return False 13 | prior = cur 14 | return True 15 | 16 | def all_num_unique(num): 17 | list1 = [] 18 | for n in str(num): 19 | if n in list1: 20 | return False 21 | else: 22 | list1.append(n) 23 | return True 24 | 25 | def pset_m(l1, m): 26 | num = int(str(9)*m) 27 | startlist = [x for x in range(num) if len(str(x)) == m] 28 | pset = [] 29 | for k in startlist: 30 | if all_chars_in(l1,k) and num_in_order(k) and all_num_unique(k): 31 | pset.append([k]) 32 | return pset 33 | 34 | def powerset(l1): 35 | pset = [] 36 | i = 1 37 | while i <= len(l1): 38 | pset = pset + pset_m(l1,i) 39 | i += 1 40 | return pset 41 | 42 | 43 | 44 | print powerset([1,2,3,4,5]) 45 | 46 | 47 | -------------------------------------------------------------------------------- /powerset/powerset_iterative.py: -------------------------------------------------------------------------------- 1 | 2 | #Iterative Powerset 3 | 4 | def reset_subset(subset, i): 5 | subset[i] += 1 6 | i += 1 7 | while i < len(subset): 8 | subset[i] = subset[i-1] + 1 9 | i+=1 10 | return subset 11 | 12 | def subsets_m(n, m): 13 | pset = [] 14 | subset = [x for x in range(0,m)] # [0,3,4], 5 15 | skip = False 16 | mPos = m-1 # last pos in subset 17 | while mPos >= 0: 18 | while subset[mPos] <= (n-(m-mPos)) and not skip: 19 | pset.append(subset[:]) 20 | subset[mPos] += 1 21 | mPos -= 1 22 | if subset[mPos] < (n-(m-mPos)): 23 | skip = False 24 | subset = reset_subset(subset,mPos) 25 | mPos = m-1 26 | else: 27 | skip = True 28 | return pset 29 | 30 | def powerset(n): 31 | pset = [] 32 | m = 1 33 | while m <= n: 34 | pset = pset + subsets_m(n,m) 35 | m+=1 36 | pset += [[]] 37 | return pset 38 | 39 | print powerset(5) 40 | print len(powerset(5)) == 32 41 | -------------------------------------------------------------------------------- /powerset/powerset_recursive.py: -------------------------------------------------------------------------------- 1 | '''powerset for any symbol''' 2 | 3 | def subsets_m(set, m, pos): 4 | p = [] 5 | while m > 0 and pos <= len(set)-m: 6 | subs = subsets_m(set, m-1, pos+1) 7 | for s in subs: 8 | p.append([set[pos]] + s) 9 | pos += 1 10 | if p == []: 11 | return [[]] 12 | return p 13 | 14 | def pset(set): 15 | p = [[]] 16 | m = 1 17 | while m <= len(set): 18 | p = p + subsets_m(set,m,0) 19 | m += 1 20 | return p 21 | 22 | # Test cases 23 | print len(pset(['a'])) 24 | print len(pset(['a','b'])) 25 | print len(pset(['a','b','c'])) 26 | print len(pset(['a','b','c','d'])) 27 | print len(pset(['a','b','c','d','e'])) 28 | print len(pset(['a','b','c','d','e','f'])) 29 | print len(pset(['a','b','c','d','e','f','g'])) 30 | print len(pset(['a','b','c','d','e','f','g','h'])) 31 | -------------------------------------------------------------------------------- /queues/Node.java: -------------------------------------------------------------------------------- 1 | package queues; 2 | 3 | public class Node { 4 | Node next; 5 | Node prior; 6 | String value; 7 | 8 | public Node(String value) { 9 | this.value = value; 10 | } 11 | 12 | public void setNext(Node next) { 13 | this.next = next; 14 | } 15 | public void setPrior(Node prior) { 16 | this.prior = prior; 17 | } 18 | public void setValue(String value) { 19 | this.value = value; 20 | } 21 | public String getValue() { 22 | return this.value; 23 | } 24 | public Node getNext() { 25 | return this.next; 26 | } 27 | public Node getPrior() { 28 | return this.prior; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /queues/Queue.java: -------------------------------------------------------------------------------- 1 | package queues; 2 | 3 | public class Queue { 4 | 5 | public static void main(String[] args) { 6 | Queue s1 = new Queue(); 7 | s1.enqueue("hello"); 8 | s1.enqueue("hi"); 9 | System.out.println(s1.dequeue().equals("hello")); 10 | } 11 | 12 | Node first; 13 | Node last; 14 | 15 | public void enqueue(String val) { 16 | Node n = new Node(val); 17 | if (first == null) { 18 | first = n; 19 | first.setNext(last); 20 | } else if (last == null) { 21 | last = n; 22 | } else { 23 | last.setNext(n); 24 | } 25 | } 26 | 27 | public String dequeue() { 28 | if (first == null) { 29 | return null; 30 | } else { 31 | String val = first.getValue(); 32 | first = first.getNext(); 33 | return val; 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /queues/QueueWithLinkedList.java: -------------------------------------------------------------------------------- 1 | package queues; 2 | 3 | import lists.Node; 4 | 5 | public class QueueWithLinkedList { 6 | 7 | public static void main(String[] args) { 8 | QueueWithLinkedList queue = new QueueWithLinkedList(); 9 | queue.enqueue("A"); 10 | queue.enqueue("B"); 11 | queue.enqueue("C"); 12 | //System.out.println(queue.dequeue()); 13 | //System.out.println(queue.dequeue()); 14 | //System.out.println(queue.dequeue()); 15 | 16 | Node t1 = new Node("A"); 17 | Node t2 = new Node("B"); 18 | Node t3 = new Node("C"); 19 | queue.testAssignment(t1,t2); 20 | System.out.println((t1.value == t2.value) == true); 21 | 22 | t1.next = t2; 23 | t2.next = t3; 24 | t2 = t3; 25 | System.out.println(t1.next.value); 26 | 27 | /* 28 | Node new1 = queue.testObjectAssignment(t1,t2); 29 | System.out.println(new1.value); 30 | System.out.println(new1.next.value); 31 | */ 32 | 33 | } 34 | 35 | Node last; 36 | 37 | public void enqueue(T val) { 38 | Node n = new Node(val); 39 | if (last == null) { 40 | last = n; 41 | } else if (last.next == null) { 42 | n.next = last; 43 | last.next = n; 44 | last = n; 45 | } else { 46 | n.next = last.next; 47 | last.next = n; 48 | last = n; 49 | } 50 | } 51 | 52 | public T dequeue() { 53 | if (last == null) { 54 | return null; 55 | } 56 | if (last.next == null) { 57 | Node first = last; 58 | last = null; 59 | return first.value; 60 | } 61 | Node first = last.next; 62 | last.next = first.next; 63 | return first.value; 64 | } 65 | 66 | public void testAssignment(Node t1, Node t2) { 67 | t1.value = t2.value; 68 | } 69 | 70 | public Node testObjectAssignment(Node t1, Node t2) { 71 | Node t3 = new Node("C"); 72 | t1.next = t2; 73 | t2.next = t3; 74 | t2 = t3; 75 | return t1; 76 | } 77 | 78 | } 79 | 80 | -------------------------------------------------------------------------------- /queues/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/queues/__init__.py -------------------------------------------------------------------------------- /queues/python/Node.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Node(object): 4 | """ 5 | Python 2 need to inherit from object 6 | Python 3 inherit from object is implicit 7 | """ 8 | def __init__(self, value=None, next=None): 9 | self.value = value 10 | self.next = next 11 | -------------------------------------------------------------------------------- /queues/python/Queue.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | 3 | """ 4 | Implement Queue w Linked List 5 | 6 | Enqueue, Dequeue, Size methods 7 | """ 8 | 9 | class Queue(object): 10 | def __init__(self, head=None): 11 | self.head = head 12 | self.size = 0 13 | 14 | def enqueue(self, value): 15 | self.size += 1 16 | if self.head is None: 17 | self.head = Node(value) 18 | return 19 | cur_node = self.head 20 | while cur_node.next is not None: 21 | cur_node = cur_node.next 22 | cur_node.next = Node(value) 23 | 24 | def dequeue(self): 25 | if self.head is not None: 26 | value = self.head.value 27 | self.head = self.head.next 28 | self.size -= 1 29 | return value 30 | else: 31 | return None 32 | 33 | def get_size(self): 34 | return self.size 35 | 36 | 37 | 38 | #Tests 39 | 40 | def test_basic_ops(): 41 | queue = Queue() 42 | assert queue.get_size() == 0 43 | assert queue.dequeue() == None 44 | queue.enqueue(5) 45 | assert queue.get_size() == 1 46 | assert queue.dequeue() == 5 47 | assert queue.get_size() == 0 48 | assert queue.dequeue() == None 49 | 50 | queue.enqueue(5) 51 | queue.enqueue(5) 52 | queue.enqueue(5) 53 | assert queue.get_size() == 3 54 | 55 | 56 | if __name__ == "__main__": 57 | test_basic_ops() -------------------------------------------------------------------------------- /queues/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/queues/python/__init__.py -------------------------------------------------------------------------------- /recursion/CentsCombosN.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class CentsCombosN { 4 | 5 | public static void main(String[] args) { 6 | int[] cents = {25,10,5,1}; 7 | int n = 25; 8 | int res = getPossibleNCombos(0, cents, 0, n); 9 | System.out.println(res); 10 | } 11 | 12 | public static int getPossibleNCombos(int sum, int[] cents, int index, int n) { 13 | if (sum == n) { 14 | return 1; 15 | } else if (index > cents.length-1) { 16 | return 0; 17 | } else if (sum + cents[index] > n) { 18 | return getPossibleNCombos(sum, cents, index+1, n); 19 | } else { 20 | return getPossibleNCombos(sum+cents[index], cents, index, n) + 21 | getPossibleNCombos(sum, cents, index+1, n); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /recursion/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | 4 | public class Fibonacci { 5 | 6 | public static void main(String[] args) { 7 | int fib = fibonacci(10); 8 | System.out.println(fib == 55); 9 | System.out.println(fibonacci(3)); 10 | } 11 | 12 | /* 13 | * Fn = F(n-1) + F(n-2) 14 | * F(1) == 1, F(0) == 0 15 | */ 16 | public static int fibonacci(int n) { 17 | if (n == 0) { 18 | return 0; 19 | } else if (n == 1) { 20 | return 1; 21 | } else { 22 | return fibonacci(n-1) + fibonacci(n-2); 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /recursion/PaintFill.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.Arrays; 4 | 5 | public class PaintFill { 6 | 7 | public static int[][] in1 = new int[3][3]; 8 | public static int[][] in2 = { 9 | { 0, 1, 1 }, 10 | { 1, 0, 0 }, 11 | { 1, 0, 0 } 12 | }; 13 | 14 | public static void main(String[] args) { 15 | //boolean[][] in1 = new boolean[3][3]; 16 | int[][] out1 = { 17 | { 1, 1, 1 }, 18 | { 1, 1, 1 }, 19 | { 1, 1, 1 } 20 | }; 21 | fillPaint(in1, 1,1); 22 | for (int i=0; i= 0 && matrix[row][col-1] != 1) { 45 | fillPaint(matrix, row, col-1); 46 | } 47 | //right 48 | if (col+1 < matrix[0].length && matrix[row][col+1] != 1) { 49 | fillPaint(matrix, row, col+1); 50 | } 51 | //down 52 | if (row+1 < matrix.length && matrix[row+1][col] != 1) { 53 | fillPaint(matrix, row+1, col); 54 | } 55 | //up 56 | if (row-1 >= 0 && matrix[row-1][col] != 1) { 57 | fillPaint(matrix, row-1, col); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /recursion/PowersetBinary.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | public class PowersetBinary { 7 | public static String[] set1; 8 | 9 | public static void main(String[] m) { 10 | set1 = new String[6]; 11 | set1[0] = "a"; 12 | set1[1] = "b"; 13 | set1[2] = "c"; 14 | set1[3] = "d"; 15 | set1[4] = "e"; 16 | set1[5] = "f"; 17 | String set2 = "abc"; 18 | String set3 = "abcde"; 19 | ArrayList pset = getPowerset(set2); 20 | printArrayList(pset, set2); 21 | pset = getPowerset(set3); 22 | printArrayList(pset, set3); 23 | } 24 | 25 | public static ArrayList getPowerset(String set) { 26 | int i = 0; 27 | ArrayList subsets = new ArrayList(); 28 | while (i < Math.pow(2,set.length())) { 29 | subsets.add(i); 30 | i++; 31 | } 32 | return subsets; 33 | } 34 | 35 | public static void printArrayList(ArrayList list, String set) { 36 | System.out.println("================"); 37 | System.out.println("Set: " + set); 38 | System.out.println("Length: " + set.length()); 39 | System.out.println("Pset: " + list.size() + " subsets"); 40 | for (Integer i : list) { 41 | String s = intToNBitBinaryStr(i, set.length()); 42 | System.out.println(s); 43 | } 44 | System.out.println("\n================"); 45 | } 46 | 47 | /* 48 | * Convert integer, i, to binary string of min digits, pad 49 | */ 50 | public static String intToNBitBinaryStr(int i, int n) { 51 | String binStr = Integer.toBinaryString(i); // get x-digit binary string from int 52 | binStr = String.format("%" + Integer.toString(n) + "s", binStr).replace(' ', '0'); //add minimum zero-padding to always return n-bit string 53 | binStr = binStr.substring(binStr.length()-n, binStr.length()); //grab last n digits b/c java represents binary in 64 digits 54 | 55 | return binStr; 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /recursion/PowersetIterative.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | public class PowersetIterative { 7 | public static String[] set1; 8 | 9 | public static void main(String[] m) { 10 | set1 = new String[6]; 11 | set1[0] = "a"; 12 | set1[1] = "b"; 13 | set1[2] = "c"; 14 | set1[3] = "d"; 15 | set1[4] = "e"; 16 | set1[5] = "f"; 17 | String set2 = "abc"; 18 | set2 = "abcde"; 19 | ArrayList pset = getPowerset(set2, ""); 20 | printArrayList(pset, set2); 21 | } 22 | 23 | public static ArrayList getPowerset(String set, String subset) { 24 | ArrayList list = new ArrayList(); 25 | if (set.length() == 0) { 26 | list.add(subset); 27 | return list; 28 | } else { 29 | ArrayList with = getPowerset(set.substring(1,set.length()), subset + set.substring(0,1)); 30 | ArrayList withOut = getPowerset(set.substring(1,set.length()), subset); 31 | list.addAll(with); 32 | list.addAll(withOut); 33 | return list; 34 | } 35 | } 36 | 37 | public static void printArrayList(ArrayList list, String set) { 38 | System.out.println("================"); 39 | System.out.println("Set: " + set); 40 | System.out.println("Length: " + set.length()); 41 | System.out.println("Pset: " + list.size() + " subsets"); 42 | for (String s : list) { 43 | System.out.print(s + " "); 44 | } 45 | System.out.println("\n================"); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /recursion/QueensChess.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.Arrays; 4 | 5 | public class QueensChess { 6 | 7 | public static void main(String[] args) { 8 | int[][] in1 = new int[3][3]; //default to 0s 9 | placeQueens(in1, 2, 0, 0); 10 | } 11 | 12 | public static void placeQueens(int[][] board, int queens, int row, int col) { 13 | if (queens == 0) { 14 | printArray(board); 15 | } else if (!spotOnBoard(board, row, col)) { 16 | //do nothing 17 | } else if (spotEligible(board, row, col) ) { 18 | System.out.println("spot is not eligible"); 19 | board[row][col] = 1; 20 | placeQueens(board, queens-1, row+1, col); 21 | board[row][col] = 0; 22 | placeQueens(board, queens, row, col+1); 23 | //do nothing 24 | } else { 25 | placeQueens(board, queens, row, col+1); 26 | placeQueens(board, queens, row+1, col); 27 | //placeQueens(board, queens-1, row-1, col-1); 28 | } 29 | } 30 | 31 | private static boolean spotOnBoard(int[][] board, int row, int col) { 32 | if (row < 0 || row >= board.length) { 33 | return false; 34 | } else if (col < 0 || col >= board[0].length) { 35 | return false; 36 | } else { 37 | return true; 38 | } 39 | } 40 | 41 | private static boolean spotEligible(int[][] board, int row, int col) { 42 | for (int i=0; i offLimitsArr = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | int paths = getPossiblePaths(3,0,0); 12 | System.out.println(paths); 13 | Integer[] a1 = new Integer[2]; 14 | a1[0] = 2; 15 | a1[1] = 2; 16 | offLimitsArr.add(a1); 17 | 18 | 19 | System.out.println(getPossiblePathsOffLimits(3,0,0)); 20 | } 21 | 22 | /* 23 | * 24 | * 25 | */ 26 | public static int getPossiblePaths(int n, int row, int col) { 27 | if (row >= n || col >= n) { 28 | return 0; 29 | } 30 | return 1 + getPossiblePaths(n,row+1,col) + getPossiblePaths(n,row,col+1); 31 | } 32 | 33 | public static int getPossiblePathsOffLimits(int n, int row, int col) { 34 | if (row >= n || col >= n) { 35 | return 0; 36 | } else if (offLimitsArr.get(0)[0] == row && offLimitsArr.get(0)[1] == col) { 37 | return 0; 38 | } else { 39 | return 1 + getPossiblePathsOffLimits(n,row+1,col) + getPossiblePathsOffLimits(n,row,col+1); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /recursion/StringPermutations.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class StringPermutations { 6 | 7 | public static List perms = new ArrayList(); 8 | 9 | public static void main(String[] args) { 10 | getPermutations("ABC",""); 11 | printArrayList(perms); 12 | System.out.println(perms.size()==6); 13 | 14 | perms.clear(); 15 | getPermutations("ABCD",""); 16 | //printArrayList(perms); 17 | System.out.println(perms.size()==24); 18 | 19 | perms.clear(); 20 | getPermutations("ABCDE",""); 21 | //printArrayList(perms); 22 | System.out.println(perms.size()==120); 23 | } 24 | 25 | /* 26 | * 27 | */ 28 | public static void getPermutations(String str, String cur) { 29 | if (str.length() == 0) { 30 | perms.add(cur); 31 | } else { 32 | for (int i=0; i arr) { 40 | for (String s : arr) { 41 | System.out.println(s); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /recursion/ValidPairsParentheses.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class ValidPairsParentheses { 4 | 5 | public static void main(String[] args) { 6 | getValidPairs3(3,3,""); 7 | getValidPairs4(3,3,""); 8 | } 9 | 10 | public static void getValidPairs3(int left, int right, String cur) { 11 | if (right == 0) { 12 | System.out.println(cur); 13 | } else if (left == 0) { 14 | getValidPairs3(left, right-1, cur+")"); 15 | } else if (left == right) { 16 | getValidPairs3(left-1, right, cur+"("); 17 | } else { 18 | getValidPairs3(left-1, right, cur+"("); 19 | getValidPairs3(left, right-1, cur+")"); 20 | } 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /recursion/python/binary_strings.py: -------------------------------------------------------------------------------- 1 | #3 2 | 3 | def generate_binary_str(n, curstr): 4 | if len(curstr) > n: 5 | return [] 6 | if len(curstr) > 1 and curstr[0] == "0": 7 | return [] 8 | strings = [] 9 | if curstr != "": 10 | strings.append(curstr) 11 | return strings + generate_binary_str(n, curstr + "1") + \ 12 | generate_binary_str(n, curstr + "0") 13 | 14 | def generate_binary_str2(n): 15 | if n == 0: 16 | return [] 17 | if n == 1: 18 | return ["1","0"] 19 | longer = [] 20 | smaller = generate_binary_str2(n-1) 21 | for s in smaller: 22 | if len(s) == n-1 and s[0] != "0": 23 | longer.append(s + "1") 24 | longer.append(s + "0") 25 | return longer + smaller 26 | 27 | def appendAtFront(x, arr): 28 | return [x + element for element in arr] 29 | 30 | def bitString(n): 31 | if n == 0: 32 | return [] 33 | if n == 1: 34 | return ["0","1"] 35 | return appendAtFront("0",bitString(n-1)) + \ 36 | appendAtFront("1",bitString(n-1)) 37 | 38 | print generate_binary_str(3,"") 39 | print generate_binary_str(4,"") 40 | 41 | print "generating binary str 2--------" 42 | print generate_binary_str2(1) 43 | print generate_binary_str2(2) 44 | print generate_binary_str2(3) 45 | print generate_binary_str2(4) 46 | 47 | print "generating binary str 3--------" 48 | print bitString(1) 49 | print bitString(2) 50 | print bitString(3) 51 | print bitString(4) 52 | -------------------------------------------------------------------------------- /recursion/python/kary_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generate all the strings of length n with k character options 3 | e.g. How many unique codes can I generate with of length N with K letters? 4 | examples: Amazon vendor codes. KEHAE or ASINs, B00AEB3FE 5 | k^n 6 | input: (2, ["ABC"]) 7 | output = ["AA","AB","AC","BA","BB","BC","CA","CB,"CC"] 8 | """ 9 | 10 | def appendChar(c, arr): 11 | return [elem + c for elem in arr] 12 | 13 | def kary_str(n, chars): 14 | if n == 0: 15 | return [] 16 | if n == 1: 17 | return chars 18 | strs = [] 19 | for c in chars: 20 | strs += appendChar(c, kary_str(n-1,chars)) 21 | return strs 22 | 23 | 24 | print kary_str(2,["A","B","C"]) 25 | 26 | -------------------------------------------------------------------------------- /recursion/python/permutate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Return all purmutations of str1 3 | 4 | ABC = ['ABC', 'BAC', 'BCA', 'ACB', 'CAB', 'CBA'] 5 | Permutations = N! 6 | Combinations = N^2 7 | Combinations size M = N!/M!(N-M)! 8 | 9 | """ 10 | def permutate(str1, curstr): 11 | if len(str1) <= 1: 12 | return [curstr + str1] 13 | permutations = [] 14 | for i in range(1,len(str1)): 15 | permutations += permutate(str1[1:i]+str1[i+1:], curstr+str1[0]+str1[i]) 16 | permutations += permutate(str1[:i]+str1[i+1:], curstr+str1[i]) 17 | return permutations 18 | 19 | 20 | print permutate("ABC","") 21 | print len(permutate("ABCD","")) -------------------------------------------------------------------------------- /searching/python/binary_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Binary Search 3 | 4 | Write method to return True if integer is in array 5 | """ 6 | 7 | 8 | def binary_search(arr, val): 9 | low = 0 10 | high = len(arr)-1 11 | while low <= high: 12 | mid = low + (high-low)/2 #alternatively (high+low)/2 13 | if arr[mid] == val: 14 | return True 15 | elif arr[mid] < val: 16 | low = mid+1 17 | else: 18 | high = mid-1 19 | return False 20 | 21 | 22 | def binary_search_recur(arr, val): 23 | if arr is None or len(arr) == 0: 24 | return False 25 | mid = len(arr)/2 26 | if arr[mid] == val: 27 | return True 28 | elif arr[mid] > val: 29 | return binary_search_recur(arr[:mid], val) 30 | else: 31 | return binary_search_recur(arr[mid+1:], val) 32 | 33 | 34 | 35 | 36 | # Tests 37 | a1 = [1,2,3,4,5] 38 | a2 = [1,2] 39 | a3 = [1] 40 | 41 | def test_binary_search(): 42 | assert binary_search(a1, 2) == True 43 | assert binary_search(a1, 9) == False 44 | assert binary_search(a1, 1) == True 45 | assert binary_search(a1, 0) == False 46 | 47 | assert binary_search(a2, 5) == False 48 | assert binary_search(a2, 1) == True 49 | assert binary_search(a2, 2) == True 50 | assert binary_search(a2, -3) == False 51 | 52 | assert binary_search(a3, 1) == True 53 | assert binary_search(a3, 0) == False 54 | assert binary_search(a3, 3) == False 55 | 56 | def test_binary_search_recur(): 57 | assert binary_search_recur(a1, 2) == True 58 | assert binary_search_recur(a1, 9) == False 59 | assert binary_search_recur(a1, 1) == True 60 | assert binary_search_recur(a1, 0) == False 61 | 62 | assert binary_search_recur(a2, 5) == False 63 | assert binary_search_recur(a2, 1) == True 64 | assert binary_search_recur(a2, 2) == True 65 | assert binary_search_recur(a2, -3) == False 66 | 67 | assert binary_search_recur(a3, 1) == True 68 | assert binary_search_recur(a3, 0) == False 69 | assert binary_search_recur(a3, 3) == False 70 | 71 | if __name__ == "__main__": 72 | test_binary_search() 73 | test_binary_search_recur() 74 | 75 | -------------------------------------------------------------------------------- /searching/python/count_element_occurence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Return the # of occurances of B 3 | in the sorted Array A in log(n) time 4 | """ 5 | 6 | class Solution: 7 | # @param A : tuple of integers 8 | # @param B : integer 9 | # @return an integer 10 | def getFirstOccur(self, A, B): 11 | low = 0 12 | high = len(A)-1 13 | 14 | while low <= high: 15 | mid = low + (high-low)/2 16 | if A[mid] >= B: 17 | high = mid-1 18 | else: 19 | low = mid+1 20 | if low >= len(A): 21 | return None 22 | return low 23 | 24 | def getLastOccur(self, A, B, low): 25 | high = len(A)-1 26 | 27 | while low <= high: 28 | mid = low + (high-low)/2 29 | if A[mid] > B: 30 | high = mid-1 31 | else: 32 | low = mid+1 33 | return high 34 | 35 | def findCount(self, A, B): 36 | lowerBound = self.getFirstOccur(A,B) 37 | if lowerBound is None: 38 | return None 39 | higherBound = self.getLastOccur(A,B,lowerBound) 40 | 41 | return higherBound-lowerBound+1 42 | 43 | 44 | sol = Solution() 45 | 46 | print sol.findCount([1,2,3,3,3,4,5,5,6,7,8], 3) == 3 47 | print sol.findCount([1],3) == None 48 | print sol.findCount([1],1) == 1 49 | print sol.findCount([1,1],1) == 2 50 | print sol.findCount([1,2],1) == 1 51 | -------------------------------------------------------------------------------- /searching/python/get_sqrt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find sqrt of number in log(n) time 3 | """ 4 | 5 | class Solution: 6 | # @param A : integer 7 | # @return an integer 8 | def sqrt(self, A): 9 | L = 0 10 | H = A 11 | while L<=H: 12 | M = L + (H-L)/2 13 | sqrt = self.get_sqrt_candidate(M,A) 14 | if sqrt is not None: 15 | return sqrt 16 | elif M*M < A: 17 | L = M+1 18 | else: 19 | H = M-1 20 | return -1 21 | 22 | def get_sqrt_candidate(self, num, A): 23 | if num*num == A: 24 | return num 25 | elif (num+1)*(num+1) == A: 26 | return num+1 27 | elif num*num < A and (num+1)*(num+1)>A: 28 | return num 29 | return None 30 | 31 | sol = Solution() 32 | 33 | print sol.sqrt(11) == 3 34 | print sol.sqrt(1) == 1 35 | print sol.sqrt(0) == 0 36 | print sol.sqrt(9) == 3 37 | print sol.sqrt(4) == 2 -------------------------------------------------------------------------------- /searching/python/search_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write an efficient algorithm that searches for a value in an m x n matrix. 3 | 4 | This matrix has the following properties: 5 | 6 | Integers in each row are sorted from left to right. 7 | The first integer of each row is greater than or equal to the last integer of the previous row. 8 | Example: 9 | 10 | Consider the following matrix: 11 | 12 | [ 13 | [1, 3, 5, 7], 14 | [10, 11, 16, 20], 15 | [23, 30, 34, 50] 16 | ] 17 | Given target = 3, return 1 ( 1 corresponds to true ) 18 | 19 | Return 0 / 1 ( 0 if the element is not present, 1 if the element is present ) for this problem 20 | 21 | """ 22 | 23 | class Solution: 24 | # @param A : list of list of integers 25 | # @param B : integer 26 | # @return an integer 27 | def searchMatrix(self, A, B): 28 | if len(A) < 1: 29 | return 0 30 | rows = len(A) 31 | cols = len(A[0]) 32 | L = 0 33 | H = rows * cols 34 | while L <= H: 35 | M = L + (H-L)/2 36 | row = (M-1) / cols 37 | col = (M-1) % cols 38 | val = A[row][col] 39 | if val == B: 40 | return 1 41 | elif val < B: 42 | L = M+1 43 | else: 44 | H = M-1 45 | return 0 46 | 47 | 48 | sol = Solution() 49 | 50 | matrix = [ 51 | [1, 3, 5, 7], 52 | [10,11,16,20], 53 | [23,30,54,60]] 54 | 55 | print sol.searchMatrix(matrix,10) == 1 56 | print sol.searchMatrix(matrix,13) == 0 57 | print sol.searchMatrix(matrix,-1) == 0 -------------------------------------------------------------------------------- /sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class BubbleSort { 4 | 5 | public static void main(String[] args) { 6 | int[] a1 = {2,1,4,5,3}; 7 | sort(a1); 8 | for (int i : a1) { 9 | System.out.print(i + ""); 10 | } 11 | 12 | } 13 | 14 | public static void sort(int[] arr) { 15 | boolean sorted = false; 16 | while (!sorted) { 17 | sorted = true; 18 | for (int i=0; i arr[i+1]) { 20 | int tmp = arr[i]; 21 | arr[i] = arr[i+1]; 22 | arr[i+1] = tmp; 23 | sorted = false; 24 | } 25 | } 26 | } 27 | }; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /sorting/BucketSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.*; 4 | import lists.Node; 5 | 6 | public class BucketSort { 7 | 8 | public static void main(String[] args) { 9 | int[] a1 = {1,2,13,9,5,6,10,5}; 10 | sort(a1); 11 | for (int i : a1) { 12 | System.out.print(i + ""); 13 | } 14 | 15 | } 16 | 17 | public static void sort(int[] arr) { 18 | Node[] buckets = new Node[10]; 19 | double max = getMax(arr); 20 | double bucketSize = max / buckets.length; 21 | for (int i=0; i[] buckets, double bucketSize) { 35 | int index = (int) (val / bucketSize); 36 | index = Math.max(0,index-1); 37 | Node n = new Node(val); 38 | Node cur = buckets[index]; 39 | if (cur == null) { 40 | buckets[index] = n; 41 | } else if (val <= cur.getValue()) { 42 | n.setNext(cur); 43 | buckets[index] = n; 44 | } else { 45 | while (cur.getNext() != null && val > (Integer) cur.getNext().getValue()) { 46 | cur = cur.getNext(); 47 | } 48 | n.setNext(cur.getNext()); 49 | cur.setNext(n); 50 | } 51 | } 52 | 53 | private static int getMax(int[] arr) { 54 | int max = arr[0]; 55 | for (int i=0; i= 0 && tmp < arr[j]) { 20 | arr[j+1] = arr[j]; 21 | j--; 22 | } 23 | arr[j+1] = tmp; 24 | i++; 25 | } 26 | }; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /sorting/MergeSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.*; 4 | 5 | public class MergeSort { 6 | 7 | public static void main(String[] args) { 8 | int[] a1 = {1,2,13,9,5,6,10,5}; 9 | a1 = sort(a1); 10 | for (int i : a1) { 11 | System.out.print(i + ""); 12 | } 13 | 14 | int[] a2 = {1,2,-13,9,50,6,10,5}; 15 | a2 = sort(a2); 16 | for (int i : a2) { 17 | System.out.print(i + ""); 18 | } 19 | } 20 | 21 | public static int[] sort(int[] arr) { 22 | if (arr.length <= 1) { 23 | return arr; 24 | } else { 25 | int[] left = Arrays.copyOfRange(arr, 0, arr.length/2); 26 | int[] right = Arrays.copyOfRange(arr, arr.length/2, arr.length); 27 | left = sort(left); 28 | right = sort(right); 29 | return merge(left, right); 30 | } 31 | }; 32 | 33 | public static int[] merge(int[] arr1, int[] arr2) { 34 | int[] sorted = new int[arr1.length + arr2.length]; 35 | int a = 0; 36 | int b = 0; 37 | for (int i=0; i= arr1.length) { 39 | sorted[i] = arr2[b]; 40 | b++; 41 | } else if (b >= arr2.length) { 42 | sorted[i] = arr1[a]; 43 | a++; 44 | } else if (arr1[a] < arr2[b]) { 45 | sorted[i] = arr1[a]; 46 | a++; 47 | } else { 48 | sorted[i] = arr2[b]; 49 | b++; 50 | } 51 | } 52 | return sorted; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.*; 4 | 5 | public class QuickSort { 6 | 7 | public static void main(String[] args) { 8 | int[] a1 = {1,2,13,9,5,6,10,5}; 9 | sort(a1,0,a1.length-1); 10 | for (int i : a1) { 11 | System.out.print(i + " "); 12 | } 13 | System.out.println(); 14 | int[] a2 = {1,2,-13,9,50,6,10,5}; 15 | sort(a2,0,a2.length-1); 16 | for (int i : a2) { 17 | System.out.print(i + " "); 18 | } 19 | } 20 | 21 | public static void sort(int[] arr, int low, int high) { 22 | if (high - low < 1) { 23 | //skip 24 | } else { 25 | int split = partition(arr, low, high); 26 | sort(arr,low,split-1); 27 | sort(arr,split,high); 28 | } 29 | }; 30 | 31 | public static int partition(int[] arr, int low, int high) { 32 | int pivot = arr[low + ((high - low) / 2)]; 33 | int i = low; 34 | int j = high; 35 | while (i <= j) { 36 | if (arr[i] >= pivot && arr[j] <= pivot) { 37 | int tmp = arr[i]; 38 | arr[i] = arr[j]; 39 | arr[j] = tmp; 40 | i++; 41 | j--; 42 | } else if (arr[i] < pivot) { 43 | i++; 44 | } else { 45 | j--; 46 | } 47 | } 48 | return i; 49 | } 50 | 51 | public static void print(int[] arr) { 52 | System.out.println(); 53 | for (int i : arr) { 54 | System.out.print(i + " "); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /sorting/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class SelectionSort { 4 | 5 | public static void main(String[] args) { 6 | int[] a1 = {2,1,4,5,3}; 7 | sort(a1); 8 | for (int i : a1) { 9 | System.out.print(i + ""); 10 | } 11 | 12 | } 13 | 14 | public static void sort(int[] arr) { 15 | int i = 0; 16 | while (i < arr.length-1) { 17 | int min = i; 18 | int j = i+1; 19 | while (j < arr.length) { 20 | if (arr[j] < arr[min]) { 21 | min = j; 22 | } 23 | j++; 24 | } 25 | int tmp = arr[i]; 26 | arr[i] = arr[min]; 27 | arr[min] = tmp; 28 | i++; 29 | } 30 | }; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /sorting/SelectionSortString.java: -------------------------------------------------------------------------------- 1 | public class SelectionSortString { 2 | 3 | public static void main(String[] args) { 4 | 5 | String str1 = "abdaacdefa"; //4 6 | String out = sortStr(str1); 7 | System.out.println(out); 8 | 9 | } 10 | 11 | public static String sortStr(String str) { 12 | int small; 13 | String tmp; 14 | boolean found; 15 | for (int i=0; i 0) { 23 | int start = 0; 24 | while (start < gap) { 25 | insertionSort(arr, start, gap); 26 | start++; 27 | } 28 | gap--; 29 | } 30 | } 31 | 32 | public static void insertionSort(int[] arr, int start, int gap) { 33 | int i = start + gap; 34 | while (i < arr.length) { 35 | int j = i; 36 | while (j > start && arr[j] < arr[j-gap]) { 37 | int tmp = arr[j]; 38 | arr[j] = arr[j-gap]; 39 | arr[j-gap] = tmp; 40 | j = j - gap; 41 | } 42 | i = i + gap; 43 | } 44 | }; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /sorting/SortArray012.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.*; 4 | 5 | public class SortArray012 { 6 | 7 | public static void main(String[] args) { 8 | SortArray012 arr = new SortArray012(); 9 | List l1 = new ArrayList(); 10 | l1.add(2); 11 | l1.add(0); 12 | l1.add(2); 13 | l1.add(0); 14 | l1.add(1); 15 | 16 | arr.sortList(l1); 17 | for (int i : l1) { 18 | System.out.print(i + " "); 19 | } 20 | System.out.println(); 21 | int[] a1 = {1,0,2,1,0,2,1}; 22 | arr.sortArray(a1); 23 | for (int i : a1) { 24 | System.out.print(i + " "); 25 | } 26 | System.out.println(); 27 | } 28 | 29 | public void sortList(List list) { 30 | int elemCount = list.size(); 31 | int listPos = 0; 32 | while (elemCount > 0) { 33 | int elem = list.get(listPos); 34 | if (elem == 0) { 35 | list.remove(listPos); 36 | list.add(0,0); 37 | listPos++; 38 | } else if (elem == 2) { 39 | list.remove(listPos); 40 | list.add(2); 41 | } else { 42 | listPos++; 43 | } 44 | elemCount--; 45 | } 46 | }; 47 | 48 | public void sortArray(int[] arr) { 49 | int[] buckets = new int[3]; //0,0,0 50 | for (int i=0; i 0) { 56 | arr[pos] = i; 57 | pos++; 58 | buckets[i]--; 59 | } 60 | } 61 | }; 62 | 63 | } 64 | -------------------------------------------------------------------------------- /sorting/python/bubble.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Bubble Sort 4 | 5 | Loops Through Swapping Each out-of-order 6 | value with its neighbor until all values 7 | are in order 8 | 9 | Worst Case: O(n^2) 10 | Best Case: O(n) 11 | """ 12 | 13 | def sort(arr): 14 | is_sorted = False 15 | while not is_sorted: 16 | is_sorted = True 17 | i = 0 18 | while i < len(arr): 19 | cur = arr[i] 20 | #we have found something out of order 21 | if i+1 < len(arr) and cur > arr[i+1]: 22 | is_sorted = False 23 | arr[i] = arr[i+1] 24 | arr[i+1] = cur 25 | i+=1 26 | return arr 27 | 28 | 29 | 30 | if __name__ == "__main__": 31 | assert sort([3,2,5,5]) == [2,3,5,5] 32 | assert sort([3,2,5]) == [2,3,5] 33 | assert sort([2,1]) == [1,2] 34 | assert sort([1,2]) == [1,2] 35 | assert sort([1]) == [1] 36 | assert sort([]) == [] 37 | assert sort([1,2,3,4]) == [1,2,3,4] 38 | assert sort(["A","C","B"]) == ["A","B","C"] 39 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 40 | assert sort([2,3,5,-2,5,5]) == [-2,2,3,5,5,5] 41 | -------------------------------------------------------------------------------- /sorting/python/counting.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Counting Sort 4 | 5 | Creates a bucket array from 0 to M (max value), 6 | and then increments the count for each element it finds. 7 | It loops through the bucket array adding to it the sum of the 8 | previous bin, this results in a mapping of the position of 9 | each element in the new sorted array. 10 | 11 | http://www.geeksforgeeks.org/counting-sort/ 12 | http://en.wikipedia.org/wiki/Counting_sort 13 | https://www.cs.usfca.edu/~galles/visualization/CountingSort.html 14 | 15 | Average Case - O(n) 16 | Worst Case - O(n) 17 | """ 18 | 19 | def sort(arr): 20 | max_num = max(arr) 21 | count_arr = [0 for x in range(max_num+1)] 22 | sorted_arr = [0 for x in range(len(arr))] 23 | for num in arr: 24 | count_arr[num] += 1 25 | for i in range(len(count_arr)): 26 | if i > 0: 27 | count_arr[i] += count_arr[i-1] 28 | for num in arr: 29 | count_arr[num] -= 1 30 | pos_in_sorted = count_arr[num] 31 | sorted_arr[pos_in_sorted] = num 32 | return sorted_arr 33 | 34 | if __name__ == "__main__": 35 | assert sort([3,2,5,5]) == [2,3,5,5] 36 | assert sort([3,2,5]) == [2,3,5] 37 | assert sort([2,1]) == [1,2] 38 | assert sort([1,2]) == [1,2] 39 | assert sort([1]) == [1] 40 | assert sort([1,2,3,4]) == [1,2,3,4] 41 | assert sort([1,3,1,0,3,2]) == [0,1,1,2,3,3] 42 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 43 | assert sort([2,3,5,0,5,5]) == [0,2,3,5,5,5] 44 | assert sort([6,1,3,5,7,2]) == [1,2,3,5,6,7] 45 | -------------------------------------------------------------------------------- /sorting/python/heap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Heapsort 3 | O(nlogn) time 4 | O(1) space - constant space 5 | 6 | Steps: 7 | 1) Build Heap (in-place) - O(n) 8 | 2) Swap Max Element To End, then Heapify Array - O(logn) 9 | 3) Repeat O(n) 10 | 11 | Heap sort algorithm has limited uses because 12 | Quicksort and Mergesort are better in practice. 13 | 14 | https://en.wikipedia.org/wiki/Heapsort#Comparison_with_other_sorts 15 | 16 | However, heapsort is nice b/c it guarantees O(nlogn) 17 | and uses O(1) constant space 18 | """ 19 | 20 | 21 | def sort(arr): 22 | """Sort in ASC order using MAX Heap""" 23 | size = len(arr) 24 | 25 | ##Step 1 - Heapify Array in-place 26 | arr = build_heap(arr) 27 | 28 | ##Step 2 - Swap Max Element To End, then Heapify 29 | while size > 0: 30 | swap(arr,1,size) 31 | size-=1 32 | perc_down(arr,1,size) 33 | return arr[1:] 34 | 35 | def build_heap(arr): 36 | """ 37 | Heapify Array In-Place 38 | Starting From Middle b/c leaf nodes 39 | always satisfy the heap propery 40 | """ 41 | i = len(arr)//2 42 | size = len(arr) 43 | arr = [0] + arr 44 | while i > 0: 45 | perc_down(arr,i,size) 46 | i-=1 47 | return arr 48 | 49 | def perc_down(arr, i, size): 50 | while 2*i <= size: #left child 51 | mc = get_max_child(arr,i,size) 52 | if arr[mc] > arr[i]: 53 | swap(arr,mc,i) 54 | else: #If elements are sorted, stop 55 | break 56 | i = mc 57 | 58 | def get_max_child(arr, i, size): 59 | if 2*i+1 > size: 60 | return 2*i 61 | elif arr[2*i] > arr[2*i+1]: 62 | return 2*i 63 | return 2*i+1 64 | 65 | def swap(arr, a, b): 66 | tmp = arr[a] 67 | arr[a] = arr[b] 68 | arr[b] = tmp 69 | 70 | 71 | a1 = [17,2,6,1,4,5,2] 72 | assert sort(a1) == [1,2,2,4,5,6,17] 73 | 74 | a2 = [12,11,13,5,6,7] 75 | assert sort(a2) == [5, 6, 7, 11, 12, 13] 76 | -------------------------------------------------------------------------------- /sorting/python/insertion.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Insertion Sort 4 | 5 | Loop Through Elements in Array "Shifting" or 6 | Swapping that element with its element on the left 7 | until that element is sorted. This creates a 8 | sorted left sub array. Continue until end of 9 | array 10 | 11 | Worst Case: O(n^2) 12 | Best Case: O(n^2) 13 | """ 14 | 15 | 16 | def sort(arr): 17 | for i in range(len(arr)): 18 | j = i 19 | while j > 0: 20 | cur_val = arr[j] 21 | if cur_val < arr[j-1]: 22 | arr[j] = arr[j-1] 23 | arr[j-1] = cur_val 24 | else: 25 | break 26 | j-=1 27 | return arr 28 | 29 | 30 | if __name__ == "__main__": 31 | assert sort([3,2,5,5]) == [2,3,5,5] 32 | assert sort([3,2,5]) == [2,3,5] 33 | assert sort([2,1]) == [1,2] 34 | assert sort([1,2]) == [1,2] 35 | assert sort([1]) == [1] 36 | assert sort([]) == [] 37 | assert sort([1,2,3,4]) == [1,2,3,4] 38 | assert sort(["A","C","B"]) == ["A","B","C"] 39 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 40 | assert sort([2,3,5,-2,5,5]) == [-2,2,3,5,5,5] -------------------------------------------------------------------------------- /sorting/python/merge.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Merge Sort 4 | 5 | 1. Divide the unsorted list into n sublists, 6 | each containing 1 element (a list of 1 element is considered sorted). 7 | 8 | 2. Repeatedly merge sublists to produce new sorted sublists until 9 | there is only 1 sublist remaining. This will be the sorted list. 10 | 11 | Worst Case - O(n Log n) 12 | Best Case - O(n Log n) 13 | """ 14 | 15 | def sort(arr): 16 | if len(arr) == 0: 17 | return [] 18 | elif len(arr) == 1: 19 | return arr 20 | else: 21 | midpoint = len(arr)/2 22 | return merge(sort(arr[:midpoint]), 23 | sort(arr[midpoint:])) 24 | 25 | def merge(left, right): 26 | result = [] 27 | l = 0 28 | r = 0 29 | while l < len(left): 30 | if r < len(right) and right[r] < left[l]: 31 | result.append(right[r]) 32 | r+=1 33 | else: 34 | result.append(left[l]) 35 | l+=1 36 | while r < len(right): 37 | result.append(right[r]) 38 | r+=1 39 | return result 40 | 41 | if __name__ == "__main__": 42 | assert sort([3,2,5,5]) == [2,3,5,5] 43 | assert sort([3,2,5]) == [2,3,5] 44 | assert sort([2,1]) == [1,2] 45 | assert sort([1,2]) == [1,2] 46 | assert sort([1]) == [1] 47 | assert sort([]) == [] 48 | assert sort([1,2,3,4]) == [1,2,3,4] 49 | assert sort(["A","C","B"]) == ["A","B","C"] 50 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 51 | assert sort([2,3,5,-2,5,5]) == [-2,2,3,5,5,5] 52 | assert sort([6,1,3,5,7,2]) == [1,2,3,5,6,7] -------------------------------------------------------------------------------- /sorting/python/quicksort.py: -------------------------------------------------------------------------------- 1 | def sort(arr, start, end): 2 | if start >= end: 3 | return 4 | pivot = (start+end)/2 5 | i = start 6 | j = end 7 | while i < j: 8 | if arr[i] >= arr[pivot] and arr[j] <= arr[pivot]: 9 | tmp = arr[i] 10 | arr[i] = arr[j] 11 | arr[j] = tmp 12 | i+=1 13 | j-=1 14 | else: 15 | if arr[i] < arr[pivot]: 16 | i+=1 17 | if arr[j] > arr[pivot]: 18 | j-=1 19 | sort(arr,start,pivot) 20 | sort(arr,pivot+1,end) 21 | 22 | 23 | 24 | 25 | a1 = [12,5,6,2,4,13] 26 | sort(a1,0,len(a1)-1) 27 | print a1 28 | 29 | a2 = [12,5,4,13] 30 | sort(a2,0,len(a2)-1) 31 | print a2 32 | 33 | a3 = [12,5] 34 | sort(a3,0,len(a3)-1) 35 | print a3 36 | 37 | a4 = [5] 38 | sort(a4,0,len(a4)-1) 39 | print a4 40 | 41 | a5 = [12,5,5,12] 42 | sort(a5,0,len(a5)-1) 43 | print a5 44 | 45 | 46 | -------------------------------------------------------------------------------- /sorting/python/selection.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Selection Sort 4 | 5 | Loop Through Array finding smallest 6 | element and swap with current element. 7 | Move to next element and continue. 8 | 9 | Worst Case: O(n^2) 10 | Best Case: O(n^2) 11 | """ 12 | 13 | def sort(arr): 14 | for i in range(len(arr)): 15 | cur_val = arr[i] 16 | smallest = None 17 | for j in range(i+1, len(arr)): 18 | if smallest is None or arr[j] < arr[smallest]: 19 | smallest = j 20 | if smallest is not None and arr[smallest] < cur_val: 21 | arr[i] = arr[smallest] 22 | arr[smallest] = cur_val 23 | return arr 24 | 25 | 26 | if __name__ == "__main__": 27 | assert sort([3,2,5,5]) == [2,3,5,5] 28 | assert sort([3,2,5]) == [2,3,5] 29 | assert sort([2,1]) == [1,2] 30 | assert sort([1,2]) == [1,2] 31 | assert sort([1]) == [1] 32 | assert sort([]) == [] 33 | assert sort([1,2,3,4]) == [1,2,3,4] 34 | assert sort(["A","C","B"]) == ["A","B","C"] 35 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 36 | assert sort([2,3,5,-2,5,5]) == [-2,2,3,5,5,5] -------------------------------------------------------------------------------- /sorting/python/shell.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Shell Sort 4 | 5 | Insertion Sort, but with a diminishing increment (i = 3), 6 | sometimes called the gap, used to create a sublist by choosing 7 | all items that are i items apart. Sorts those sublists using 8 | insertion sort, and then completes one final normal insertion 9 | (increment = 1) sort at the end 10 | 11 | Average Case - O(n^2) 12 | Worst Case - O(n^2) 13 | """ 14 | DEFAULT_HOP = 1 15 | 16 | def sort(arr, hop=DEFAULT_HOP): 17 | i = 0 18 | while i < hop: 19 | arr = insertion_sort_w_hop(arr, i, hop) 20 | i+=1 21 | arr = insertion_sort_w_hop(arr, 0, 1) 22 | return arr 23 | 24 | def insertion_sort_w_hop(arr, start, hop): 25 | i = start 26 | while i < len(arr): 27 | j = i 28 | while j-hop >= start and arr[j] < arr[j-hop]: 29 | cur = arr[j] 30 | arr[j] = arr[j-hop] 31 | arr[j-hop] = cur 32 | j -= hop 33 | i += hop 34 | return arr 35 | 36 | if __name__ == "__main__": 37 | assert sort([3,2,5,5]) == [2,3,5,5] 38 | assert sort([3,2,5]) == [2,3,5] 39 | assert sort([2,1]) == [1,2] 40 | assert sort([1,2]) == [1,2] 41 | assert sort([1]) == [1] 42 | assert sort([]) == [] 43 | assert sort([1,2,3,4]) == [1,2,3,4] 44 | assert sort(["A","C","B"]) == ["A","B","C"] 45 | assert sort([2,3,5,2,5,5]) == [2,2,3,5,5,5] 46 | assert sort([2,3,5,-2,5,5]) == [-2,2,3,5,5,5] 47 | assert sort([6,1,3,5,7,2]) == [1,2,3,5,6,7] -------------------------------------------------------------------------------- /sorting/python/silly_sort.py: -------------------------------------------------------------------------------- 1 | def sort(arr): 2 | for i in range(len(arr)): 3 | arr = silly(arr,arr[i]) 4 | return arr 5 | 6 | def silly(buckets, num): 7 | if buckets[num] == num: 8 | return buckets 9 | tmp = buckets[num] 10 | buckets[num] = num 11 | return silly(buckets, tmp) 12 | 13 | 14 | print sort([2,1,0]) 15 | print sort([3,1,4,2,5,0]) 16 | 17 | -------------------------------------------------------------------------------- /sorting/python/sort012.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Sort 012 4 | 5 | Sort an array that contains only the integers 6 | 0, 1, and 2 in linear time. 7 | 8 | (e.g. [1,0,2,2,1] == [0,1,1,2,2]) 9 | 10 | O(n) 11 | """ 12 | 13 | def sort(arr): 14 | count_arr = [0 for x in range(3)] 15 | for num in arr: 16 | count_arr[num] += 1 17 | count_index = 0 18 | for i in range(len(arr)): 19 | if count_arr[count_index] == 0: 20 | count_index += 1 21 | arr[i] = count_index 22 | count_arr[count_index] -= 1 23 | return arr 24 | 25 | if __name__ == "__main__": 26 | assert sort([1,2,1,0,1,2]) == [0,1,1,1,2,2] 27 | assert sort([2,1]) == [1,2] 28 | assert sort([1,2]) == [1,2] 29 | assert sort([1]) == [1] 30 | -------------------------------------------------------------------------------- /stacks/EvaluateExpression.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class EvaluateExpression { 6 | 7 | private final String SUPPORTED_OPS = "+-*/"; 8 | public static void main(String[] args) { 9 | EvaluateExpression eval = new EvaluateExpression(); 10 | String s1 = "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )"; 11 | System.out.println(eval.solveExp(s1) == 101); 12 | } 13 | 14 | public int solveExp(String exp) { 15 | Stack operands = new Stack(); 16 | Stack operators = new Stack(); 17 | String[] arr = exp.split(" "); 18 | for (String s : arr) { 19 | if (s.equals("(")) { 20 | //skip 21 | } else if (SUPPORTED_OPS.contains(s)) { 22 | operators.push(s); 23 | } else if (s.equals(")")) { 24 | int b = operands.pop(); 25 | int a = operands.pop(); 26 | String operator = operators.pop(); 27 | int val = calculate(operator, a, b); 28 | operands.push(val); 29 | } else { 30 | int val = Integer.parseInt(s); 31 | operands.push(val); 32 | } 33 | } 34 | return operands.pop(); 35 | } 36 | 37 | private int calculate(String operator, int a, int b) { 38 | if (operator.equals("+")) { 39 | return a + b; 40 | } 41 | if (operator.equals("-")) { 42 | return a - b; 43 | } 44 | if (operator.equals("*")) { 45 | return a * b; 46 | } 47 | if (operator.equals("/")) { 48 | return a / b; 49 | } 50 | return -1; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /stacks/Node.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class Node { 4 | Node next; 5 | Node prior; 6 | String value; 7 | 8 | public Node(String value) { 9 | this.value = value; 10 | } 11 | 12 | public void setNext(Node next) { 13 | this.next = next; 14 | } 15 | public void setPrior(Node prior) { 16 | this.prior = prior; 17 | } 18 | public void setValue(String value) { 19 | this.value = value; 20 | } 21 | public String getValue() { 22 | return this.value; 23 | } 24 | public Node getNext() { 25 | return this.next; 26 | } 27 | public Node getPrior() { 28 | return this.prior; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /stacks/QueueUsingStacks.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class QueueUsingStacks { 4 | 5 | public static void main(String[] args) { 6 | QueueUsingStacks queue = new QueueUsingStacks(); 7 | queue.enqueue("hello"); 8 | queue.enqueue("hi"); 9 | System.out.println(queue.dequeue().equals("hello")); 10 | } 11 | 12 | static Stack s1 = new Stack(); 13 | static Stack s2 = new Stack(); 14 | 15 | public static void enqueue(String val) { 16 | String s = s1.pop(); 17 | while (s != null) { 18 | s2.push(s); 19 | s = s1.pop(); 20 | } 21 | s1.push(val); 22 | s = s2.pop(); 23 | while (s != null) { 24 | s1.push(s); 25 | s = s2.pop(); 26 | } 27 | } 28 | 29 | public static String dequeue() { 30 | return s1.pop(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /stacks/SetOfStacks.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class SetOfStacks { 4 | 5 | public static void main(String[] args) { 6 | SetOfStacks s1 = new SetOfStacks(); 7 | s1.push("hello"); 8 | s1.push("hello1"); 9 | s1.push("hello2"); 10 | s1.push("hello3"); 11 | s1.push("hello4"); 12 | s1.push("hello5"); 13 | System.out.println(plates); 14 | System.out.println(curStack); 15 | 16 | System.out.println(s1.pop()); 17 | System.out.println(plates); 18 | System.out.println(curStack); 19 | } 20 | 21 | static Stack[] set = new Stack[8]; 22 | static int THRESHOLD = 5; 23 | static int curStack = 0; 24 | static int plates = 0; 25 | 26 | public static void push(String val) { 27 | if (set[curStack] == null) { 28 | set[curStack] = new Stack(); 29 | set[curStack].push(val); 30 | plates++; 31 | } else if (plates == THRESHOLD) { 32 | curStack++; 33 | plates = 0; 34 | push(val); 35 | } else { 36 | set[curStack].push(val); 37 | plates++; 38 | } 39 | } 40 | 41 | public static String pop() { 42 | if (plates == 0) { 43 | curStack--; 44 | plates = 5; 45 | return pop(); 46 | } else { 47 | plates--; 48 | return set[curStack].pop(); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /stacks/SortStack.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class SortStack { 4 | 5 | public static void main(String[] args) { 6 | Stack s1 = new Stack(); 7 | System.out.println(s1.isEmpty() == true); 8 | s1.push("b"); 9 | s1.push("c"); 10 | s1.push("d"); 11 | s1.push("a"); 12 | s1.push("a"); 13 | s1.push("e"); 14 | s1 = sortStack(s1); 15 | while (!s1.isEmpty()) { 16 | System.out.println(s1.pop()); 17 | } 18 | } 19 | 20 | public static Stack sortStack(Stack stack) { 21 | Stack tmp = new Stack(); 22 | Stack sorted = new Stack(); 23 | while (!stack.isEmpty()) { 24 | while ( !sorted.isEmpty() && greaterThan(stack.peek(), sorted.peek()) ) { 25 | tmp.push(sorted.pop()); 26 | } 27 | sorted.push(stack.pop()); 28 | while ( !tmp.isEmpty() ) { 29 | sorted.push(tmp.pop()); 30 | } 31 | } 32 | 33 | return sorted; 34 | } 35 | 36 | private static boolean greaterThan(String a, String b) { 37 | return a.compareTo(b) > 0; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /stacks/Stack.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class Stack { 4 | 5 | public static void main(String[] args) { 6 | Stack s1 = new Stack(); 7 | s1.push("hello"); 8 | s1.push("hi"); 9 | System.out.println(s1.isEmpty() == false); 10 | System.out.println(s1.peek().equals("hi")); 11 | System.out.println(s1.pop().equals("hi")); 12 | System.out.println(s1.pop().equals("hello")); 13 | System.out.println(s1.isEmpty() == true); 14 | } 15 | 16 | Node top; 17 | 18 | public void push(String val) { 19 | Node n = new Node(val); 20 | if (top == null) { 21 | top = n; 22 | } else { 23 | n.setNext(top); 24 | top = n; 25 | } 26 | } 27 | 28 | public String pop() { 29 | if (top == null) { 30 | return null; 31 | } else { 32 | String val = top.getValue(); 33 | top = top.getNext(); 34 | return val; 35 | } 36 | } 37 | 38 | public String peek() { 39 | if (top == null) { 40 | return null; 41 | } else { 42 | return top.getValue(); 43 | } 44 | } 45 | 46 | public boolean isEmpty() { 47 | return top == null; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /stacks/StackWithMin.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | import lists.NodeInteger; 4 | 5 | public class StackWithMin { 6 | 7 | public static void main(String[] args) { 8 | StackWithMin s1 = new StackWithMin(); 9 | s1.push(3); 10 | s1.push(6); 11 | System.out.println(s1.getMin() == 3); 12 | System.out.println(s1.pop() == 6); 13 | System.out.println(s1.getMin() == 3); 14 | System.out.println(s1.pop() == 3); 15 | System.out.println(s1.pop() == -1); 16 | } 17 | 18 | private NodeInteger top; 19 | 20 | public void push(int val) { 21 | NodeInteger n = new NodeInteger(val); 22 | if (top == null) { 23 | n.setMin(val); 24 | } else if (val < top.getMin()) { 25 | n.setMin(val); 26 | } else { 27 | n.setMin(top.getMin()); 28 | } 29 | n.setNext(top); 30 | top = n; 31 | } 32 | 33 | public int pop() { 34 | if (top == null) { 35 | return -1; 36 | } else { 37 | int val = top.getValue(); 38 | top = top.getNext(); 39 | return val; 40 | } 41 | } 42 | 43 | public int getMin() { 44 | if (top == null) { 45 | return -1; 46 | } else { 47 | return top.getMin(); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /stacks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/stacks/__init__.py -------------------------------------------------------------------------------- /stacks/python/Node.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Node(object): 4 | """ 5 | Python 2 need to inherit from object 6 | Python 3 inherit from object is implicit 7 | """ 8 | def __init__(self, value=None, next=None): 9 | self.value = value 10 | self.next = next 11 | -------------------------------------------------------------------------------- /stacks/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfortuner/problems/a436cb15646e42baa9b6898902ac8ac082a4a0f4/stacks/python/__init__.py -------------------------------------------------------------------------------- /stacks/python/stacks_w_array.py: -------------------------------------------------------------------------------- 1 | from Stack import Stack 2 | from Node import Node 3 | """ 4 | Stacks with Array 5 | 6 | Implement 3 stacks using a single array 7 | 8 | Approaches 9 | 1) Index 0, 3, 6.. first stack. 1, 4, 7.. second stack. 2, 5, 8.. third stack. 10 | 11 | """ 12 | 13 | class StacksWithArray(object): 14 | def __init__(self): 15 | self.array = [None for x in range(99)] 16 | # Represent next available open position 17 | self.stack_positions = { 18 | 0 : 0, 19 | 1 : 1, 20 | 2 : 2 21 | } 22 | self.INCREMENT = 3 23 | 24 | def push(self, stackno, value): 25 | """ 26 | Find the current open position in array 27 | of the stack (0-2) requested by client 28 | Add value, then increment to next open position 29 | """ 30 | index = self.stack_positions[stackno] 31 | self.array[index] = value 32 | self.stack_positions[stackno] += self.INCREMENT 33 | print "stack positions = " + str(self.stack_positions) 34 | print "array values = " + str(self.array) 35 | 36 | def pop(self, stackno): 37 | index = self.stack_positions[stackno] 38 | if index > stackno: 39 | self.stack_positions[stackno] -= self.INCREMENT 40 | index = self.stack_positions[stackno] 41 | value = self.array[index] 42 | self.array[index] = None 43 | print "stack positions = " + str(self.stack_positions) 44 | print "array values = " + str(self.array) 45 | return value 46 | 47 | 48 | 49 | #Tests 50 | 51 | def test_basic_ops(): 52 | stack = StacksWithArray() 53 | stack.push(0,"A") 54 | stack.push(1,"B") 55 | stack.push(2,"C") 56 | 57 | stack.push(0,"A") 58 | stack.push(0,"A") 59 | stack.push(0,"A") 60 | 61 | stack.pop(0) 62 | stack.pop(0) 63 | stack.pop(0) 64 | 65 | stack.push(0,"A") 66 | stack.pop(1) 67 | stack.pop(1) 68 | stack.pop(1) 69 | stack.pop(2) 70 | stack.pop(2) 71 | stack.pop(0) 72 | stack.pop(0) 73 | stack.pop(0) 74 | 75 | 76 | if __name__ == "__main__": 77 | test_basic_ops() 78 | -------------------------------------------------------------------------------- /strings/LongestSubstringNoDupes.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.*; 4 | 5 | public class LongestSubstringNoDupes { 6 | 7 | public static void main(String[] args) { 8 | LongestSubstringNoDupes sub = new LongestSubstringNoDupes(); 9 | String s1 = "ababc"; 10 | String s2 = "ab"; 11 | String s3 = "a"; 12 | String s4 = ""; 13 | System.out.println(sub.getMaxSubstringLength(s1) == 3); 14 | System.out.println(sub.getMaxSubstringLength(s2) == 2); 15 | System.out.println(sub.getMaxSubstringLength(s3) == 1); 16 | System.out.println(sub.getMaxSubstringLength(s4) == 0); 17 | } 18 | 19 | /* 20 | * Complexity - O(n^2) ? But average case looks much better 21 | */ 22 | public int getMaxSubstringLength(String str) { 23 | Map map = new HashMap(); 24 | int maxLength = 0; 25 | int curLength = 0; 26 | for (int i=0; i maxLength) { 34 | maxLength = curLength; 35 | } 36 | curLength = 0; 37 | map.clear(); 38 | } 39 | return maxLength; 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /strings/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class RemoveDuplicates { 5 | 6 | public static void main(String[] args) { 7 | String in = "aaabddaeg"; 8 | String out = removeDuplicates(in); 9 | System.out.println(out); 10 | } 11 | 12 | public static String removeDuplicates(String str) { 13 | Map map = new HashMap(); 14 | String newStr = ""; 15 | for (int i=0; i=0; i--) { 14 | newStr = newStr + str.substring(i,i+1); 15 | } 16 | return newStr; 17 | }; 18 | 19 | public static String reverse2(String str) { 20 | int start = 0; 21 | int end = str.length()-1; 22 | String tmp; 23 | while (start < end) { 24 | tmp = str.substring(start,start+1); 25 | str = str.substring(0,start) + str.substring(end,end+1) + 26 | str.substring(start+1,end) + tmp + str.substring(end+1,str.length()); 27 | start++; 28 | end--; 29 | } 30 | return str; 31 | }; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /strings/ReverseWords.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.*; 4 | 5 | public class ReverseWords { 6 | 7 | public static void main(String[] args) { 8 | String in = "I am a student"; 9 | String out = "student a am I"; 10 | System.out.println(out.equals(reverseSentence(in))); 11 | System.out.println(out.equals(reverseSentenceArray(in))); 12 | } 13 | 14 | public static String reverseSentence(String str) { 15 | String reverse = ""; 16 | int i = 0; 17 | while(i < str.length()) { 18 | int j=i; 19 | while (j= 0) { 33 | reverse = reverse + arr[i] + " "; 34 | i--; 35 | } 36 | return reverse.substring(0,reverse.length()-1); 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /strings/RotateString.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class RotateString { 4 | 5 | public static void main(String[] args) { 6 | RotateString rot = new RotateString(); 7 | String s1 = "abcd"; 8 | System.out.println("cdab".equals(rot.rotate(s1,2))); 9 | System.out.println("dabc".equals(rot.rotate(s1,5))); 10 | } 11 | 12 | //Rotate String to the right 13 | public String rotate(String str, int n) { 14 | while (n > 0) { 15 | str = str.substring(str.length()-1,str.length()) + str.substring(0,str.length()-1); 16 | n--; 17 | } 18 | return str; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /strings/python/first_unique_char.py: -------------------------------------------------------------------------------- 1 | """ 2 | [FindFirstUniqueChar] 3 | Return the first non-repeated character in a string. 4 | If not found, return null. Assume the string is NOT sorted. 5 | """ 6 | 7 | #Cases 8 | """ 9 | 1) Empty or None 10 | 2) No repeats 11 | 3) Single repeat 12 | 4) Multiple repeats (return first found?) 13 | 5) 1,2,3 length strings 14 | """ 15 | 16 | #Approaches 17 | """ 18 | 1) Sort string O(n log n), then loop O(n) and check if str1[i] == str1[i+1] (Won't work for first unique) 19 | 2) HashMap to store unique chars. Loop O(n) check if in HashMap, if not, store. 20 | 3) Naive Double Loop O(n^2), For each, for each, see if another exists. Return first found. 21 | 4) Can we do linear time? 22 | """ 23 | 24 | def get_first_unique_char_loops(str1): 25 | i = 0 26 | while i < len(str1): 27 | j = i+1 28 | while j < len(str1): 29 | if str1[i] == str1[j]: 30 | return str1[i] 31 | j+=1 32 | i+=1 33 | return None 34 | 35 | def get_first_unique_char_dict(str1): 36 | chars = {} 37 | for s in str1: 38 | if chars.get(s) != None: 39 | return s 40 | chars[s] = s 41 | return None 42 | 43 | 44 | #Tests 45 | 46 | def test_get_first_unique_char_loops(): 47 | assert get_first_unique_char_loops("ABCBD") == "B" 48 | assert get_first_unique_char_loops("") == None 49 | assert get_first_unique_char_loops("A") == None 50 | assert get_first_unique_char_loops("AB") == None 51 | assert get_first_unique_char_loops("ABCC") == "C" 52 | 53 | def test_get_first_unique_char_dict(): 54 | assert get_first_unique_char_dict("ABCBD") == "B" 55 | assert get_first_unique_char_dict("") == None 56 | assert get_first_unique_char_dict("A") == None 57 | assert get_first_unique_char_dict("AB") == None 58 | assert get_first_unique_char_dict("ABCC") == "C" 59 | 60 | if __name__ == "__main__": 61 | test_get_first_unique_char_loops() 62 | test_get_first_unique_char_dict() 63 | 64 | 65 | -------------------------------------------------------------------------------- /strings/python/interpret_symbols.py: -------------------------------------------------------------------------------- 1 | letters = { 2 | "1":"a", 3 | "2":"b", 4 | "3":"c", 5 | "11":"d", 6 | "12":"e", 7 | "23":"f", 8 | "1123":"g" 9 | } 10 | 11 | """ 12 | input: "1123" 13 | output: ["aabc","aaf","aec","dbc","df","g"] 14 | """ 15 | 16 | def interpret(symbols, curstr, start, end): 17 | if end > len(symbols): 18 | return [] 19 | seq = symbols[start:end] 20 | if seq in letters: 21 | newstr = curstr + letters[seq] 22 | if end == len(symbols): 23 | return [newstr] 24 | return interpret(symbols, newstr, end, end+1) + \ 25 | interpret(symbols, curstr, start, end+1) 26 | else: 27 | return interpret(symbols, curstr, start, end+1) 28 | 29 | print interpret("1123","",0,1) 30 | print interpret("1","",0,1) 31 | print interpret("23","",0,1) 32 | 33 | -------------------------------------------------------------------------------- /strings/python/longest_substring_no_dupes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Longest Substring No Dupes 3 | Given a string, please get the length of the longest substring 4 | which does not have duplicated characters. 5 | Supposing all characters in the string are in the range from 'a' to 'z'. 6 | Input: "ababc", Output: 3. 7 | """ 8 | 9 | #Cases 10 | """ 11 | 1) Empty or None 12 | 2) Single char 13 | 3) Normal string (whole is unique) 14 | 4) Normal string (part is unique - beginning/end) 15 | """ 16 | 17 | #Approaches 18 | """ 19 | 1) Store cur_length, max_length, cur_index, setofchars. Loop through O(n^2) use set to 20 | know dupes. Keep track of longest substring without dupes. Reset if dupe found. 21 | """ 22 | 23 | def get_len_longest_substr(str1): 24 | #hashmap which stores unique chars in string 25 | #Once dupe is found, we clear hashmap and start again 26 | cur_substr_chars = set() 27 | max_length = 0 28 | start_index = 0 29 | i = 0 30 | while i < len(str1): 31 | if str1[i] not in cur_substr_chars: 32 | cur_substr_chars.add(str1[i]) 33 | if i-start_index+1 > max_length: 34 | max_length = i-start_index+1 35 | i += 1 36 | else: 37 | cur_substr_chars = set() 38 | start_index += 1 39 | i = start_index 40 | return max_length 41 | 42 | 43 | #Tests 44 | 45 | def test_get_len_longest_substr(): 46 | assert get_len_longest_substr("abcadd") == 4 47 | assert get_len_longest_substr("abcabc") == 3 48 | assert get_len_longest_substr("aaa") == 1 49 | assert get_len_longest_substr("abcad") == 4 50 | assert get_len_longest_substr("a") == 1 51 | assert get_len_longest_substr("") == 0 52 | assert get_len_longest_substr("abc") == 3 53 | 54 | if __name__ == "__main__": 55 | test_get_len_longest_substr() 56 | 57 | -------------------------------------------------------------------------------- /strings/python/remove_dupes.py: -------------------------------------------------------------------------------- 1 | 2 | ## CASES 3 | """ 4 | None 5 | "" 6 | "A" 7 | "ABC" 8 | "ABBCA" 9 | """ 10 | 11 | ## APPROACHES 12 | """ 13 | 1) Sort string. Loop once. Remove next if char is same. (in place) 14 | 2) New string. HashMap. Loop once. If map contains val, don't add. (Could also use set). 15 | 3) Same string. Remove in place 16 | """ 17 | 18 | def remove_dupes_sort(str1): 19 | newstr = "" 20 | str1 = "".join(sorted(str1)) 21 | i = 0 22 | while i < len(str1): 23 | newstr += str1[i] 24 | if i == len(str1)-1: 25 | return newstr 26 | elif str1[i] == str1[i+1]: 27 | while i < len(str1)-1 and str1[i] == str1[i+1]: 28 | i += 1 29 | i += 1 30 | return newstr 31 | 32 | def remove_dupes_map(str1): 33 | charmap = {} 34 | newstr = "" 35 | for s in str1: 36 | if charmap.get(s) is None: 37 | newstr += s 38 | charmap[s] = 1 39 | return newstr 40 | 41 | def remove_dupes_in_place(str1): 42 | if len(str1) < 2: 43 | return str1 44 | i = 0 45 | while i < len(str1)-1: 46 | print len(str1) #python keeps updating length of string 47 | k = i+1 48 | while k < len(str1): 49 | if str1[i] == str1[k]: 50 | if k == len(str1)-1: 51 | str1 = str1[:k] 52 | else: 53 | str1 = str1[:k] + str1[k+1:] 54 | else: 55 | k+=1 56 | i+=1 57 | return str1 58 | 59 | #5(4) 60 | #ABACB 61 | #ABCB 62 | #ABC 63 | 64 | 65 | 66 | ## Tests 67 | 68 | def test_remove_dupes_sort(): 69 | assert remove_dupes_sort("CABABABDCC") == "ABCD" 70 | assert remove_dupes_sort("ABC") == "ABC" 71 | assert remove_dupes_sort("") == "" 72 | 73 | def test_remove_dupes_map(): 74 | assert remove_dupes_map("CABABABDCC") == "CABD" 75 | assert remove_dupes_map("ABC") == "ABC" 76 | assert remove_dupes_map("") == "" 77 | 78 | def test_remove_dupes_in_place(): 79 | assert remove_dupes_in_place("CABABABDCC") == "CABD" 80 | assert remove_dupes_in_place("ABC") == "ABC" 81 | assert remove_dupes_in_place("") == "" 82 | 83 | if __name__ == "__main__": 84 | test_remove_dupes_sort() 85 | test_remove_dupes_map() 86 | test_remove_dupes_in_place() 87 | 88 | -------------------------------------------------------------------------------- /strings/python/replace_spaces.py: -------------------------------------------------------------------------------- 1 | #Cases 2 | """ 3 | 1) Empty string 4 | 2) No spaces 5 | 3) Normal some spaces 6 | 4) Multiples contiguous spaces 7 | """ 8 | 9 | def replace_spaces(str1): 10 | html_space = "%20" 11 | newstr = "" 12 | for s in str1: 13 | if s == " ": 14 | newstr += html_space 15 | else: 16 | newstr += s 17 | return newstr 18 | 19 | def replace_spaces_pythonic(str1): 20 | #returns new copy of str 21 | return str1.replace(" ", "%20") 22 | 23 | #Tests 24 | 25 | def test_replace_spaces(): 26 | assert replace_spaces("") == "" 27 | assert replace_spaces("ABC") == "ABC" 28 | assert replace_spaces("A AB B") == "A%20AB%20B" 29 | assert replace_spaces("A A A AAA") == "A%20%20A%20A%20%20%20AAA" 30 | 31 | def test_replace_spaces_pythonic(): 32 | assert replace_spaces_pythonic("") == "" 33 | assert replace_spaces_pythonic("ABC") == "ABC" 34 | assert replace_spaces_pythonic("A AB B") == "A%20AB%20B" 35 | assert replace_spaces_pythonic("A A A AAA") == "A%20%20A%20A%20%20%20AAA" 36 | 37 | if __name__ == "__main__": 38 | test_replace_spaces() 39 | test_replace_spaces_pythonic() -------------------------------------------------------------------------------- /strings/python/reverse_string.py: -------------------------------------------------------------------------------- 1 | #Cases 2 | """ 3 | 1) Empty string 4 | 2) Normal all-distinct 5 | 3) Normal some dupes 6 | 4) even/odd number?? 7 | 5) 1,2,3+ length 8 | 9 | """ 10 | 11 | def reverse_string(str1): 12 | newstr = "" 13 | i = len(str1)-1 14 | while i >= 0: 15 | newstr += str1[i] 16 | i-=1 17 | return newstr 18 | 19 | def reverse_string_in_place(str1): 20 | #ABC / 3,0 21 | #CAB / 3,1 22 | #CBA / 3,2 23 | #CBA / 3,3 24 | i = 0 25 | while i < len(str1): 26 | str1 = str1[0:i] + str1[-1] + str1[i:-1] 27 | i+=1 28 | return str1 29 | 30 | 31 | #Tests 32 | 33 | def test_reverse_string(): 34 | assert reverse_string("ABC") == "CBA" 35 | assert reverse_string("") == "" 36 | assert reverse_string("AABB") == "BBAA" 37 | assert reverse_string("A") == "A" 38 | 39 | def test_reverse_string_in_place(): 40 | assert reverse_string_in_place("ABC") == "CBA" 41 | assert reverse_string_in_place("") == "" 42 | assert reverse_string_in_place("AABB") == "BBAA" 43 | assert reverse_string_in_place("A") == "A" 44 | 45 | if __name__ == "__main__": 46 | test_reverse_string() 47 | test_reverse_string_in_place() 48 | -------------------------------------------------------------------------------- /strings/reverse_string_inplace.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | //inplace reverse a sentence 7 | using namespace std; 8 | 9 | void inplace_reverse(string & arr, int size){ 10 | int s = 0; 11 | while (size > s){ 12 | char *start = &arr[s]; 13 | char *tmp = &arr[size]; 14 | char tmp2 = *tmp; 15 | 16 | *tmp = *start; 17 | *start = tmp2; 18 | s++; 19 | size--; 20 | } 21 | 22 | } 23 | 24 | int main() { 25 | string tmp = "this is my word"; 26 | inplace_reverse(tmp,14); 27 | cout << tmp << endl; 28 | return 0; 29 | } -------------------------------------------------------------------------------- /strings/string_replace_space.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // replaces each space in the string with '%20' 7 | // Linear time solution 8 | string replace_Space(string &word){ 9 | if (word.size() == 0) 10 | return "nothing to return"; 11 | string word2=""; 12 | for (int x=0;x { 5 | BinaryTree parent; 6 | BinaryTree leftChild; 7 | BinaryTree rightChild; 8 | T value; 9 | int subtreeWeight; 10 | 11 | public BinaryTree(T value) { 12 | this.value = value; 13 | } 14 | public BinaryTree getParent() { 15 | return this.parent; 16 | } 17 | public void setParent(BinaryTree tree) { 18 | this.parent = tree; 19 | } 20 | public T getValue() { 21 | return this.value; 22 | } 23 | public void setValue(T val) { 24 | this.value = val; 25 | } 26 | public void setLeftChild(BinaryTree child) { 27 | child.setParent(this); 28 | this.leftChild = child; 29 | } 30 | public void setRightChild(BinaryTree child) { 31 | child.setParent(this); 32 | this.rightChild = child; 33 | } 34 | public BinaryTree getLeftChild() { 35 | return this.leftChild; 36 | } 37 | public BinaryTree getRightChild() { 38 | return this.rightChild; 39 | } 40 | 41 | public int getSubtreeWeight() { 42 | return this.subtreeWeight; 43 | } 44 | 45 | public void setSubtreeWeight(int weight) { 46 | this.subtreeWeight = weight; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /trees/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | 4 | public class BinaryTreeNode { 5 | BinaryTreeNode parent; 6 | BinaryTreeNode leftChild; 7 | BinaryTreeNode rightChild; 8 | String key; 9 | String value; 10 | 11 | public BinaryTreeNode(String key, String value, BinaryTreeNode parent) { 12 | this.key = key; 13 | this.value = value; 14 | this.parent = parent; 15 | } 16 | public BinaryTreeNode getParent() { 17 | return this.parent; 18 | } 19 | public void setParent(BinaryTreeNode tree) { 20 | this.parent = tree; 21 | } 22 | public String getKey() { 23 | return this.key; 24 | } 25 | public void setKey(String key) { 26 | this.key = key; 27 | } 28 | public String getValue() { 29 | return this.value; 30 | } 31 | public void setValue(String val) { 32 | this.value = val; 33 | } 34 | public void setLeftChild(BinaryTreeNode child) { 35 | child.setParent(this); 36 | this.leftChild = child; 37 | } 38 | public void setRightChild(BinaryTreeNode child) { 39 | child.setParent(this); 40 | this.rightChild = child; 41 | } 42 | public BinaryTreeNode getLeftChild() { 43 | return this.leftChild; 44 | } 45 | public BinaryTreeNode getRightChild() { 46 | return this.rightChild; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /trees/BuildBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class BuildBinarySearchTree { 4 | 5 | public static void main(String[] args) { 6 | String[] a1 = {"A","C","D","F","S"}; 7 | BinaryTree t1 = buildBinaryTree(a1); 8 | printTree(t1); 9 | System.out.println("==========="); 10 | String[] a2 = {"C","E","D","A","B"}; 11 | BinaryTree t2 = buildBinaryTree(a2); 12 | printTree(t2); 13 | } 14 | 15 | 16 | //Create binary search tree from array of Strings 17 | //[3,6,2,5,7] 18 | public static BinaryTree buildBinaryTree(String[] arr) { 19 | BinaryTree tree = new BinaryTree(null); 20 | for (int i=0; i { 6 | 7 | private final String OPERATORS = "+-/*"; 8 | private static class Node { 9 | T val; 10 | Node left; 11 | Node right; 12 | public Node (T value) { 13 | this.val = value; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | ExpressionTree exp = new ExpressionTree(); 19 | String i1 = "7 3 + 2 *"; 20 | Node t1 = exp.buildTreeFromPostfix(i1); 21 | String postfix1 = exp.getPostfixFromTree(t1); 22 | System.out.println(postfix1.equals("73+2*")); 23 | String infix1 = exp.getInfixFromTree(t1); 24 | System.out.println("7+3*2".equals(infix1)); 25 | } 26 | 27 | public Node buildTreeFromPostfix(String postfix) { 28 | Stack> stack = new Stack(); 29 | String[] arr = postfix.split(" "); 30 | for (String s : arr) { 31 | Node cur = new Node(s); 32 | if (OPERATORS.contains(s)) { 33 | cur.right = stack.pop(); 34 | cur.left = stack.pop(); 35 | } 36 | stack.push(cur); 37 | } 38 | return stack.pop(); 39 | } 40 | 41 | public String getPostfixFromTree(Node node) { 42 | if (OPERATORS.contains(node.val)) { 43 | return getPostfixFromTree(node.left) + getPostfixFromTree(node.right) + node.val; 44 | } 45 | return node.val; 46 | } 47 | 48 | public String getInfixFromTree(Node node) { 49 | if (OPERATORS.contains(node.val)) { 50 | return getInfixFromTree(node.left) + node.val + getInfixFromTree(node.right); 51 | } 52 | return node.val; 53 | } 54 | 55 | public void printTree(Node tree) { 56 | if (tree != null) { 57 | printTree(tree.left); 58 | printTree(tree.right); 59 | System.out.print(tree.val); 60 | } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /trees/IsBalanced.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.lang.Math; 4 | 5 | public class IsBalanced { 6 | 7 | 8 | public static void main(String[] str) { 9 | BinaryTree tree = new BinaryTree("A"); 10 | BinaryTree t2 = new BinaryTree("B"); 11 | BinaryTree t3 = new BinaryTree("C"); 12 | tree.setLeftChild(t2); 13 | tree.setRightChild(t3); 14 | 15 | BinaryTree t4 = new BinaryTree("D"); 16 | BinaryTree t5 = new BinaryTree("E"); 17 | t2.setLeftChild(t4); 18 | t2.setRightChild(t5); 19 | 20 | BinaryTree t6 = new BinaryTree("F"); 21 | BinaryTree t7 = new BinaryTree("G"); 22 | t3.setLeftChild(t6); 23 | t3.setRightChild(t7); 24 | 25 | /* 26 | A 27 | B C 28 | D E F G 29 | 30 | */ 31 | BinaryTree t8 = new BinaryTree("K"); 32 | t4.setRightChild(new BinaryTree("J")); 33 | t6.setRightChild(t8); 34 | t8.setRightChild(new BinaryTree("I")); 35 | System.out.println(getHeight(tree) == 5); 36 | System.out.println(isBalanced(tree) == true); 37 | } 38 | 39 | public static boolean isBalanced(BinaryTree tree) { 40 | if (tree == null) { 41 | return true; 42 | } else { 43 | int left = getHeight(tree.getLeftChild()); 44 | int right = getHeight(tree.getRightChild()); 45 | if (Math.abs(left - right) > 1) { 46 | return false; 47 | } else { 48 | return true; 49 | } 50 | } 51 | } 52 | 53 | public static int getHeight(BinaryTree tree) { 54 | if (tree == null) { 55 | return 0; 56 | } else { 57 | int left = getHeight(tree.getLeftChild()); 58 | int right = getHeight(tree.getRightChild()); 59 | if (left > right) { 60 | return left + 1; 61 | } else { 62 | return right + 1; 63 | } 64 | } 65 | } 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /trees/MinHeightTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.lang.Math; 4 | import java.util.List; 5 | import java.util.ArrayList; 6 | 7 | public class MinHeightTree { 8 | 9 | 10 | public static void main(String[] str) { 11 | BinaryTree tree = new BinaryTree(""); 12 | List list = new ArrayList(); 13 | String[] arr = {"A","B","C","D","E"}; 14 | for (String s : arr) { 15 | list.add(s); 16 | } 17 | BinaryTree newTree = buildTree(tree,list); 18 | printTree(newTree); 19 | 20 | } 21 | 22 | public static BinaryTree buildTree(BinaryTree tree, List list) { 23 | if (list.size() == 0) { 24 | return null; 25 | } else if (list.size() == 1) { 26 | return new BinaryTree(list.get(0)); 27 | } else { 28 | int mid = list.size() / 2; 29 | BinaryTree newTree = new BinaryTree(list.get(mid)); 30 | newTree.setLeftChild(buildTree(newTree, list.subList(0,mid))); 31 | if (mid+1 < list.size()) { 32 | newTree.setRightChild(buildTree(newTree, list.subList(mid+1,list.size()))); 33 | } 34 | return newTree; 35 | } 36 | } 37 | 38 | public static void printTree(BinaryTree tree) { 39 | if (tree == null) { 40 | //do nothing 41 | } else { 42 | System.out.println(tree.getValue()); 43 | printTree(tree.getLeftChild()); 44 | printTree(tree.getRightChild()); 45 | } 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /trees/MirrorBinaryTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class MirrorBinaryTree { 4 | 5 | public static void main(String[] args) { 6 | String[] a1 = {"1","2","3","4","5","6","7"}; 7 | BinaryTree t1 = BuildBinarySearchTree.buildBinaryTree(a1); 8 | BuildBinarySearchTree.printTree(t1); 9 | System.out.println("============"); 10 | BinaryTree m1 = mirrorTree(t1); 11 | BuildBinarySearchTree.printTree(m1); 12 | } 13 | 14 | 15 | public static BinaryTree mirrorTree(BinaryTree tree) { 16 | if (tree == null) { 17 | return tree; 18 | } 19 | BinaryTree tmp = tree.getLeftChild(); 20 | tree.leftChild = mirrorTree(tree.rightChild); 21 | tree.rightChild = mirrorTree(tmp); 22 | return tree; 23 | 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /trees/PrintPathToKey.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class PrintPathToKey { 4 | 5 | public static void main(String[] args) { 6 | String[] a1 = {"D","A","B","F","S","C","E"}; 7 | BinaryTree t1 = BuildBinarySearchTree.buildBinaryTree(a1); 8 | System.out.println(getPathArray(t1,"A").equals("1")); 9 | System.out.println(getPathArray(t1,"C").equals("100")); 10 | System.out.println(getPathArray(t1,"E").equals("01")); 11 | System.out.println(getPathArray(t1,"K").equals("-1")); 12 | } 13 | 14 | 15 | public static String getPathArray(BinaryTree tree, String key) { 16 | String path = ""; 17 | BinaryTree curNode = tree; 18 | while(curNode != null) { 19 | if (curNode.getValue().equals(key)) { 20 | return path; 21 | } else if ( key.compareTo(curNode.getValue()) <= 0 ) { 22 | path = path + "1"; 23 | curNode = curNode.getLeftChild(); 24 | } else { 25 | path = path + "0"; 26 | curNode = curNode.getRightChild(); 27 | } 28 | } 29 | return "-1"; 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /trees/Tree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | 6 | public class Tree { 7 | TreeNode root; 8 | 9 | public void setRoot(TreeNode node) { 10 | root = node; 11 | } 12 | public TreeNode getRoot() { 13 | return root; 14 | } 15 | public void addChild(TreeNode parent, TreeNode newChild) { 16 | newChild.setParent(parent); 17 | parent.getChildren().add(newChild); 18 | } 19 | public void addChild(TreeNode parent, TreeNode newChild, int index) { 20 | newChild.setParent(parent); 21 | List children = parent.getChildren(); 22 | TreeNode curChild = children.get(index); 23 | curChild.setParent(newChild); 24 | newChild.getChildren().add(curChild); 25 | children.set(index, newChild); 26 | } 27 | /* 28 | * Removes element at index 3, returns element, 29 | * shifts remaining elements to the left, resizing the list 30 | */ 31 | public void removeChild(TreeNode parent, int index) { 32 | parent.getChildren().remove(index); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /trees/TreeNode.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | 6 | public class TreeNode { 7 | TreeNode parent; 8 | Integer value; 9 | List children = new ArrayList(); 10 | 11 | public TreeNode(int value) { 12 | this.value = value; 13 | } 14 | public void setParent(TreeNode node) { 15 | parent = node; 16 | } 17 | public TreeNode getParent() { 18 | return parent; 19 | } 20 | public void setValue(int val) { 21 | this.value = val; 22 | } 23 | public int getValue() { 24 | return value; 25 | } 26 | public TreeNode getChild(int index) { 27 | return children.get(index); 28 | } 29 | public List getChildren() { 30 | return children; 31 | } 32 | public void setChildren(List subTree) { 33 | children = subTree; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /trees/TreeTest.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | 6 | public class TreeTest { 7 | 8 | public static void main(String[] str) { 9 | Tree tree = new Tree(); 10 | TreeNode n1 = new TreeNode(3); 11 | tree.setRoot(n1); 12 | TreeNode n2 = new TreeNode(4); 13 | TreeNode n3 = new TreeNode(5); 14 | tree.addChild(n1, n2); 15 | tree.addChild(n1, n3); 16 | 17 | System.out.println(n2.getParent() == n1); 18 | 19 | System.out.println(n1.getValue() == 3); 20 | System.out.println(n2.getParent() == n1); 21 | 22 | System.out.println(n1.getChildren().size() == 2); 23 | System.out.println(n1.getChild(0).getValue() == 4); 24 | 25 | tree.removeChild(n1, 0); 26 | 27 | System.out.println(n1.getChildren().size() == 1); 28 | System.out.println(n1.getChild(0).getValue() == 5); 29 | 30 | tree.addChild(n1, n2, 0); 31 | 32 | System.out.println(n1.getChildren().size() == 1); 33 | System.out.println(n1.getChild(0).getValue() == 4); 34 | System.out.println(n2.getParent() == n1); 35 | 36 | System.out.println(n2.getChildren().size() == 1); 37 | System.out.println(n2.getChild(0).getValue() == 5); 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /trees/bst_sum_to_k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | //http://www.careercup.com/question?id=5767892626833408 7 | 8 | // Program to find two nodes in a BST that sum to input k 9 | 10 | // assumes that nodes have parent pointers 11 | // assumes no duplicates in the bst 12 | 13 | // Structure of tree node 14 | struct Node 15 | { 16 | int value; 17 | struct Node *left, *right; 18 | }; 19 | 20 | // A utility function to create a new BT node 21 | Node *newNode(char item) 22 | { 23 | Node *temp = new Node; 24 | temp->value = item; 25 | temp->left = temp->right = NULL; 26 | return temp; 27 | } 28 | 29 | 30 | void sum_2_nodes(Node* r1, Node* r2, int k){ 31 | if (r1 == NULL || r2 == NULL) 32 | return; 33 | else { 34 | int i = r1->value + r2->value; 35 | if (i == k){ 36 | cout << r1->value << "+" << r2->value << endl; 37 | exit(1); 38 | } 39 | else if (i > k) 40 | sum_2_nodes(r1->left,r2,k); 41 | else if (i < k) 42 | sum_2_nodes(r1,r2->right,k); 43 | } 44 | } 45 | 46 | 47 | void treeSum(Node *root,int k){ 48 | if ((root == NULL) || (root->left == NULL && root->right == NULL)) 49 | return; 50 | else if (root->left != NULL) 51 | sum_2_nodes(root->left,root,k); 52 | else if (root->right != NULL) 53 | sum_2_nodes(root,root->right,k); 54 | } 55 | 56 | 57 | int main() { 58 | int k = 0; 59 | cout << "Enter a number" << endl; 60 | cin >> k; 61 | 62 | Node *T = newNode(5); 63 | T->left = newNode(3); 64 | T->right = newNode(7); 65 | T->left->left = newNode(2); 66 | T->left->right = newNode(4); 67 | T->right->right = newNode(9); 68 | T->right->left = newNode(6); 69 | 70 | treeSum(T,k); 71 | 72 | return 0; 73 | } -------------------------------------------------------------------------------- /trees/in_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | // Structure of tree node 8 | struct Node 9 | { 10 | char key; 11 | struct Node *left, *right; 12 | }; 13 | 14 | // A utility function to create a new BT node 15 | Node *newNode(char item) 16 | { 17 | Node *temp = new Node; 18 | temp->key = item; 19 | temp->left = temp->right = NULL; 20 | return temp; 21 | } 22 | 23 | 24 | // function for in-order traversal of a tree 25 | // prints out the contents (Assume each node has 1 piece of content which is an integer). 26 | // recursive 27 | void print_inorder(Node *root){ 28 | if (root == NULL) 29 | return; 30 | print_inorder(root->left); 31 | cout << root->key << endl; 32 | print_inorder(root->right); 33 | } 34 | 35 | // // iterative using stacks 36 | // void print_inorder_iter(Node *root){ 37 | // if (root == NULL) 38 | // return; 39 | 40 | // stack *tmp = new stack; 41 | // while (tmp->size() > 0 || root != NULL){ 42 | // if (root == NULL){ 43 | // Node parent = tmp->Pop(); 44 | // cout << parent->key << endl; 45 | // root = parent->right; 46 | // } 47 | // else 48 | // { 49 | // tmp.push(root); 50 | // root = root->left; 51 | // } 52 | // } 53 | 54 | // } 55 | 56 | int main(){ 57 | 58 | Node *T = newNode('a'); // a 59 | T->left = newNode('b'); // b d 60 | T->right = newNode('d'); // c e 61 | T->left->left = newNode('c'); 62 | T->right->right = newNode('e'); 63 | 64 | print_inorder(T); 65 | 66 | cout << "*****************\n"; 67 | cout << "and now iteratively\n"; 68 | cout << "*****************\n"; 69 | 70 | //print_inorder_iter(T); 71 | 72 | return 0; 73 | } -------------------------------------------------------------------------------- /trees/python/LCA.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | def LCA(root, a, b): 9 | if root == None: 10 | return None 11 | left = LCA(root.left, a, b) 12 | right = LCA(root.right, a, b) 13 | if left != None and right != None: 14 | return root 15 | if root is a or root is b: 16 | return root 17 | if left != None: 18 | return left 19 | if right != None: 20 | return right 21 | return None 22 | 23 | """ 24 | Binary Search Tree 25 | 26 | Cases: 27 | 1) Both left (both smaller than root) 28 | 2) Both right (both greater than root) 29 | 3) Root is LCA (one smaller, one greater) 30 | """ 31 | 32 | def LCA_BST(root, a, b): 33 | if root == None: 34 | return None 35 | if (root.data >= a.data and root.data <= b.data): 36 | return root 37 | if (root.data <= a.data and root.data >= b.data): 38 | return root 39 | if root.data > a.data and root.data > b.data: 40 | return LCA_BST(root.left, a, b) 41 | else: 42 | return LCA_BST(root.right, a, b) 43 | 44 | 45 | ## TESTS ------- 46 | 47 | ## Tree 1 48 | l5 = Node(5) 49 | l3 = Node(7) 50 | l4 = Node(6) 51 | r3 = Node(8) 52 | l2 = Node(4,None,l3) 53 | l1 = Node(2,l2,l5) 54 | r1 = Node(3,l4,r3) 55 | tree1 = Node(1,l1,r1) 56 | 57 | print "BINARY TREE" 58 | assert LCA(tree1, l4, r3).data == 3 59 | assert LCA(tree1, l1, r3).data == 1 60 | assert LCA(tree1, l1, l2).data == 2 61 | assert LCA(tree1, tree1, r1).data == 1 62 | 63 | ## BST 1 64 | l6 = Node(12) 65 | l5 = Node(6) 66 | l4 = Node(9) 67 | r3 = Node(15,l6) 68 | l2 = Node(3) 69 | l1 = Node(4,l2,l5) 70 | r1 = Node(11,l4,r3) 71 | bst1 = Node(7,l1,r1) 72 | 73 | print "BINARY SEARCH TREE" 74 | assert LCA_BST(bst1, l1, r3).data == 7 75 | assert LCA_BST(bst1, l4, r3).data == 11 76 | assert LCA_BST(bst1, l2, l5).data == 4 77 | assert LCA_BST(bst1, r1, r3).data == 11 78 | -------------------------------------------------------------------------------- /trees/python/Node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data, left=None, right=None): 3 | self.data = data 4 | self.left = left 5 | self.right = right 6 | -------------------------------------------------------------------------------- /trees/python/build_bst.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | """ 9 | Build BST from Sorted List 10 | """ 11 | 12 | def build_bst(A): 13 | if len(A) == 0: 14 | return None 15 | mid = len(A)/2 16 | root = Node(A[mid]) 17 | root.left = build_bst(A[:mid]) 18 | root.right = build_bst(A[mid+1:]) 19 | return root 20 | 21 | """ 22 | Return a sorted list from BST 23 | """ 24 | 25 | def sorted_list_from_bst(root): 26 | if root == None: 27 | return [] 28 | left = sorted_list_from_bst(root.left) 29 | result = [root.data] 30 | right = sorted_list_from_bst(root.right) 31 | return left + result + right 32 | 33 | ## TESTS ------- 34 | 35 | a1 = [3,4,6,7,9,11,12,15] 36 | output = build_bst(a1) 37 | print output.data 38 | #LEFT 39 | print output.left.data 40 | print output.left.left.data 41 | print output.left.left.left.data 42 | #RIGHT 43 | print output.right.data 44 | print output.right.left.data 45 | print output.right.right.data 46 | assert sorted_list_from_bst(output) == a1 47 | -------------------------------------------------------------------------------- /trees/python/build_tree.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | """ 9 | Given Pre-Order and In-Order 10 | Traversal Lists of Nodes, 11 | Reconstruct a Binary Tree 12 | 13 | Inorder: Node(D), Node(B), EAFC 14 | Preorder: Node(A), Node(B), DECF 15 | """ 16 | 17 | def build_tree(po, io): 18 | if len(po) < 1: 19 | return None 20 | if len(po) == 1: 21 | return po[0] 22 | root = po[0] 23 | i = 0 24 | while io[i] != root: 25 | i+=1 26 | root.left = build_tree(po[1:i+1], io[:i]) 27 | root.right = build_tree(po[i+1:], io[i+1:]) 28 | return root 29 | 30 | 31 | na = Node("A") 32 | nb = Node("B") 33 | nd = Node("D") 34 | ne = Node("E") 35 | nc = Node("C") 36 | nf = Node("F") 37 | 38 | po = [na,nb,nd,ne,nc,nf] 39 | io = [nd,nb,ne,na,nf,nc] 40 | tree = build_tree(po,io) 41 | assert tree.data == "A" 42 | assert tree.left.data == "B" 43 | assert tree.left.left.data == "D" 44 | assert tree.left.right.data == "E" 45 | assert tree.right.data == "C" 46 | assert tree.right.left.data == "F" 47 | assert tree.right.right == None 48 | 49 | -------------------------------------------------------------------------------- /trees/python/deepest_node.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | import test_data 3 | 4 | ## Time/Space Complexity 5 | ## O(n)/O(n) 6 | 7 | ## Deepest BFS 8 | """ 9 | Normal BFS 10 | Last node dequed is the deepest! 11 | """ 12 | 13 | def get_deepest_recursive(nodeobj): 14 | if nodeobj[0] == None: 15 | return [None,0] 16 | left = get_deepest_recursive([nodeobj[0].left,nodeobj[1]+1]) 17 | right = get_deepest_recursive([nodeobj[0].right,nodeobj[1]+1]) 18 | if left[0] == None and right[0] == None: 19 | return nodeobj 20 | if left[1] > right[1]: 21 | return left 22 | return right 23 | 24 | ## Tests 25 | print "RECURSIVE" 26 | print "Deepest= " + str(get_deepest_recursive([test_data.tree1,0])[0].data) 27 | print "Deepest= " + str(get_deepest_recursive([test_data.tree2,0])[0].data) 28 | print "Deepest= " + str(get_deepest_recursive([test_data.tree3,0])[0].data) 29 | print "Deepest= " + str(get_deepest_recursive([test_data.tree4,0])[0].data) 30 | -------------------------------------------------------------------------------- /trees/python/diameter.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | """ 9 | Approaches 10 | 1) Post Order w Hashmap 11 | O(n), O(n + ~height) 12 | 2) Level Order w Two Queues 13 | """ 14 | 15 | def diameter(tree): 16 | if tree == None: 17 | return 0 18 | diameter = level_map(tree, 0) 19 | return max(diameter.values()) 20 | 21 | def level_map(tree, level): 22 | if tree == None: 23 | return {} 24 | left = level_map(tree.left, level+1) 25 | right = level_map(tree.right, level+1) 26 | map = join(left, right) 27 | map[level] = 1 28 | return map 29 | 30 | def join(map1, map2): 31 | for key2 in map2: 32 | if key2 in map1: 33 | map1[key2] += map2[key2] 34 | else: 35 | map1[key2] = map2[key2] 36 | return map1 37 | 38 | print diameter(test_data.tree1) 39 | print diameter(test_data.tree2) 40 | print diameter(test_data.tree3) 41 | print diameter(test_data.tree4) 42 | -------------------------------------------------------------------------------- /trees/python/find_element.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | ## O(n)/O(n) 7 | 8 | ## In Order 9 | def find_element(tree, value): 10 | if tree == None: 11 | return False 12 | left = find_element(tree.left, value) 13 | if left == True: 14 | return True 15 | if tree.data == value: 16 | return True 17 | return find_element(tree.right, value) 18 | 19 | ## In Order 20 | def find_element_iterative(tree, value): 21 | if tree == None: 22 | return False 23 | stack = [] 24 | node = tree 25 | while len(stack) > 0 or node != None: 26 | if node != None: 27 | stack.append(node) 28 | node = node.left 29 | else: 30 | node = stack.pop() 31 | if node.data == value: 32 | return True 33 | node = node.right 34 | return False 35 | 36 | print find_element(test_data.tree1, 8) 37 | print find_element(test_data.tree2, 7) 38 | print find_element(test_data.tree3, 0) 39 | print find_element(test_data.tree4, 3) 40 | 41 | print "ITERATIVE" 42 | print find_element_iterative(test_data.tree1, 8) 43 | print find_element_iterative(test_data.tree2, 7) 44 | print find_element_iterative(test_data.tree3, 0) 45 | print find_element_iterative(test_data.tree4, 3) 46 | -------------------------------------------------------------------------------- /trees/python/in_order.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | import test_data 3 | 4 | def in_order_iterative(root): 5 | stack = [] 6 | node = root 7 | while len(stack) > 0 or node != None: 8 | if node != None: 9 | stack.append(node) 10 | node = node.left 11 | else: 12 | node = stack.pop() 13 | print node.data 14 | node = node.right 15 | print "complete!" 16 | 17 | def in_order_recursive(root): 18 | if root == None: 19 | return None 20 | in_order_recursive(root.left) 21 | print root.data, 22 | in_order_recursive(root.right) 23 | 24 | def in_order_search(root, target): 25 | if root == None: 26 | return None 27 | left = in_order_search(root.left, target) 28 | if left != None: 29 | return left 30 | if root.data == target: 31 | return root 32 | right = in_order_search(root.right, target) 33 | if right != None: 34 | return right 35 | return None 36 | 37 | 38 | 39 | ## Tests ## 40 | 41 | l3 = Node(7) 42 | l4 = Node(5) 43 | r3 = Node(6) 44 | 45 | l2 = Node(4,l3) 46 | 47 | l1 = Node(2,l2) 48 | r1 = Node(3,l4,r3) 49 | 50 | root = Node(1,l1,r1) 51 | 52 | def test_in_order_iterative(): 53 | in_order_iterative(test_data.tree1) 54 | in_order_iterative(test_data.tree2) 55 | in_order_iterative(test_data.tree3) 56 | in_order_iterative(test_data.tree4) 57 | 58 | def test_in_order_recursive(): 59 | in_order_recursive(test_data.tree1) 60 | in_order_recursive(test_data.tree2) 61 | in_order_recursive(test_data.tree3) 62 | in_order_recursive(test_data.tree4) 63 | 64 | def test_in_order_search(): 65 | assert in_order_search(root, 5) == l4 66 | assert in_order_search(root, 4) == l2 67 | assert in_order_search(root, 6) == r3 68 | 69 | test_in_order_iterative() 70 | test_in_order_recursive() 71 | test_in_order_search() 72 | -------------------------------------------------------------------------------- /trees/python/is_bst.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | def is_bst(root, min, max): 9 | if root == None: 10 | return True 11 | if root.data < min: 12 | return False 13 | if root.data > max: 14 | return False 15 | left = is_bst(root.left, min, root.data) 16 | right = is_bst(root.right, root.data, max) 17 | return left and right 18 | 19 | """ 20 | In Order Traversal of BST 21 | -This gives you a sorted list 22 | -So check if values Out of Order! 23 | """ 24 | 25 | def is_bst_in_order(root): 26 | global prev 27 | if root == None: 28 | return True 29 | left = is_bst_in_order(root.left) 30 | if not left: 31 | return False 32 | if root.data < prev: 33 | return False 34 | prev = root.data 35 | return is_bst_in_order(root.right) 36 | 37 | 38 | ## TESTS ------- 39 | 40 | print "BINARY SEARCH TREE" 41 | assert is_bst(test_data.bst1,-sys.maxint,sys.maxint) == True 42 | assert is_bst(test_data.tree3,-sys.maxint,sys.maxint) == True #Skew tree 43 | 44 | print "NOT BINARY SEARCH TREE" 45 | assert is_bst(test_data.tree1,-sys.maxint,sys.maxint) == False 46 | assert is_bst(test_data.tree2,-sys.maxint,sys.maxint) == False 47 | 48 | print "IN ORDER IMPL-------" 49 | 50 | print "BINARY SEARCH TREE" 51 | prev = -sys.maxint 52 | assert is_bst_in_order(test_data.bst1) == True 53 | prev = -sys.maxint 54 | assert is_bst_in_order(test_data.tree3) == True #Skew tree 55 | 56 | print "NOT BINARY SEARCH TREE" 57 | prev = -sys.maxint 58 | assert is_bst_in_order(test_data.tree1) == False 59 | prev = -sys.maxint 60 | assert is_bst_in_order(test_data.tree2) == False 61 | 62 | 63 | -------------------------------------------------------------------------------- /trees/python/kth_smallest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | def kth_smallest(root, k): 9 | stack = [] 10 | node = root 11 | while len(stack) > 0 or node != None: 12 | if node != None: 13 | stack.append(node) 14 | node = node.left 15 | else: 16 | node = stack.pop() 17 | if k == 1: 18 | return node.data 19 | k-=1 20 | node = node.right 21 | return None 22 | 23 | 24 | ##Tests 25 | print kth_smallest(test_data.bst1,1) 26 | print kth_smallest(test_data.bst1,2) 27 | print kth_smallest(test_data.bst1,3) 28 | print kth_smallest(test_data.bst1,4) 29 | print kth_smallest(test_data.bst1,5) 30 | print kth_smallest(test_data.bst1,6) 31 | print kth_smallest(test_data.bst1,7) 32 | print kth_smallest(test_data.bst1,8) 33 | 34 | -------------------------------------------------------------------------------- /trees/python/level_order.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | 3 | def level_order(root): 4 | if root == None: 5 | return 6 | queue = [] 7 | queue.append(root) 8 | while len(queue) > 0: 9 | node = queue.pop(0) 10 | print node.data, 11 | if node.left != None: 12 | queue.append(node.left) 13 | if node.right != None: 14 | queue.append(node.right) 15 | 16 | 17 | ## Tests ## 18 | 19 | ## Tree 1 20 | l5 = Node(5) 21 | l3 = Node(8) 22 | l4 = Node(6) 23 | r3 = Node(7) 24 | 25 | l2 = Node(4,None,l3) 26 | 27 | l1 = Node(2,l2,l5) 28 | r1 = Node(3,l4,r3) 29 | root = Node(1,l1,r1) 30 | 31 | 32 | ## Tree 2 33 | right3b = Node(7) 34 | right3a = Node(6) 35 | right2 = Node(3, right3a, right3b) 36 | left3b = Node(5) 37 | left3a = Node(4) 38 | left2 = Node(2,left3a,left3b) 39 | root2 = Node(1,left2,right2) 40 | 41 | def test_level_order(): 42 | print "Iterative---" 43 | print "Tree 1" 44 | level_order(root) 45 | print "\nTree 2" 46 | level_order(root2) 47 | 48 | 49 | test_level_order() 50 | -------------------------------------------------------------------------------- /trees/python/max_element.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | O(n), O(n) 7 | 8 | ## Post Order 9 | def max_element(tree): 10 | if tree == None: 11 | return -sys.maxint 12 | left_max = max_element(tree.left) 13 | right_max = max_element(tree.right) 14 | return max(left_max, right_max, tree.data) 15 | 16 | ## Pre Order 17 | def max_element_iterative(tree): 18 | max_element = -sys.maxint 19 | if tree == None: 20 | return 21 | stack = [] 22 | stack.append(tree) 23 | while len(stack) > 0: 24 | node = stack.pop() 25 | if node.data > max_element: 26 | max_element = node.data 27 | if node.right != None: 28 | stack.append(node.right) 29 | if node.left != None: 30 | stack.append(node.left) 31 | return max_element 32 | 33 | print max_element(test_data.tree1) 34 | print max_element(test_data.tree2) 35 | print max_element(test_data.tree3) 36 | 37 | print "ITERATIVE" 38 | print max_element_iterative(test_data.tree1) 39 | print max_element_iterative(test_data.tree2) 40 | print max_element_iterative(test_data.tree3) 41 | -------------------------------------------------------------------------------- /trees/python/max_path_sum.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from Node import Node 3 | import test_data 4 | 5 | ## Time/Space Complexity 6 | #O(n), O(n) 7 | 8 | """ 9 | Approaches 10 | """ 11 | 12 | def max_path_sum(tree): 13 | if tree == None: 14 | return 0 15 | return get_max(tree)[1] 16 | 17 | def get_max(root): 18 | if root == None: 19 | return [0,-sys.maxint] 20 | left = get_max(root.left) 21 | right = get_max(root.right) 22 | cur_max = max(root.data,left[1],right[1], 23 | root.data+left[0],root.data+right[0]) 24 | cur_sum = root.data 25 | if left[0] > 0 and left[0] > right[0]: 26 | cur_sum += left[0] 27 | elif right[0] > 0: 28 | cur_sum += right[0] 29 | return [cur_sum,cur_max] 30 | 31 | 32 | print max_path_sum(test_data.tree1) 33 | print max_path_sum(test_data.tree2) 34 | print max_path_sum(test_data.tree3) 35 | print max_path_sum(test_data.tree4) 36 | print max_path_sum(test_data.negatives) 37 | -------------------------------------------------------------------------------- /trees/python/post_order.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | import test_data 3 | 4 | def post_order_iterative(root): 5 | if root == None: 6 | return 7 | stack = [] 8 | prev = None 9 | node = root 10 | while len(stack) > 0 or prev == None or node.left == prev: 11 | if node.left != None and is_child(node, prev): 12 | stack.append(node) 13 | prev = node 14 | node = node.left 15 | elif node.right != None and (is_child(node, prev) \ 16 | or prev == node.left): 17 | stack.append(node) 18 | prev = node 19 | node = node.right 20 | else: 21 | print node.data, 22 | prev = node 23 | node = stack.pop() 24 | print node.data, 25 | 26 | def is_child(node, prev): 27 | if prev is None: 28 | return True 29 | return node in [prev.left, prev.right] 30 | 31 | def post_order_recursive(root): 32 | if root == None: 33 | return None 34 | post_order_recursive(root.left) 35 | post_order_recursive(root.right) 36 | print root.data, 37 | 38 | 39 | 40 | ## Tests ## 41 | 42 | def test_post_order_iterative(): 43 | print "Iterative---" 44 | print "Tree 1" 45 | post_order_iterative(test_data.tree1) 46 | print "\nTree 2" 47 | post_order_iterative(test_data.tree2) 48 | print "\nTree 3" 49 | post_order_iterative(test_data.tree3) 50 | 51 | def test_post_order_recursive(): 52 | print "\nRecursive---" 53 | print "Tree 1" 54 | post_order_recursive(test_data.tree1) 55 | print "\nTree 2" 56 | post_order_recursive(test_data.tree2) 57 | print "\nTree 3" 58 | post_order_recursive(test_data.tree3) 59 | 60 | test_post_order_iterative() 61 | test_post_order_recursive() 62 | -------------------------------------------------------------------------------- /trees/python/pre_order.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | 3 | def pre_order(root): 4 | if root == None: 5 | return 6 | stack = [] 7 | stack.append(root) 8 | while len(stack) > 0: 9 | node = stack.pop() 10 | print node.data, 11 | if node.right != None: 12 | stack.append(node.right) 13 | if node.left != None: 14 | stack.append(node.left) 15 | 16 | def pre_order_recursive(root): 17 | if root == None: 18 | return 19 | print root.data 20 | pre_order_recursive(root.left) 21 | pre_order_recursive(root.right) 22 | 23 | 24 | ## Tests ## 25 | 26 | ## Tree 1 27 | l5 = Node(5) 28 | l3 = Node(7) 29 | l4 = Node(6) 30 | r3 = Node(8) 31 | 32 | l2 = Node(4,None,l3) 33 | 34 | l1 = Node(2,l2,l5) 35 | r1 = Node(3,l4,r3) 36 | root = Node(1,l1,r1) 37 | 38 | 39 | ## Tree 2 40 | right3b = Node(7) 41 | right3a = Node(6) 42 | right2 = Node(3, right3a, right3b) 43 | left3b = Node(5) 44 | left3a = Node(4) 45 | left2 = Node(2,left3a,left3b) 46 | root2 = Node(1,left2,right2) 47 | 48 | def test_pre_order(): 49 | print "Iterative---" 50 | print "Tree 1" 51 | pre_order(root) 52 | print "\nTree 2" 53 | pre_order(root2) 54 | 55 | 56 | test_pre_order() 57 | -------------------------------------------------------------------------------- /trees/python/print_upside_down.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | import test_data 3 | 4 | def print_upside_down(root): 5 | if root == None: 6 | return 7 | queue = [] 8 | stack = [] 9 | queue.append(root) 10 | while len(queue) > 0: 11 | node = queue.pop(0) 12 | stack.append(node) 13 | if node.right != None: 14 | queue.append(node.right) 15 | if node.left != None: 16 | queue.append(node.left) 17 | while len(stack) > 0: 18 | print(stack.pop().data), 19 | print "\n" 20 | 21 | ## Tests ## 22 | print_upside_down(test_data.tree1) 23 | print_upside_down(test_data.tree2) 24 | print_upside_down(test_data.tree3) 25 | print_upside_down(test_data.tree4) 26 | -------------------------------------------------------------------------------- /trees/python/test_data.py: -------------------------------------------------------------------------------- 1 | from Node import Node 2 | 3 | ## Tree 1 4 | l5 = Node(5) 5 | l3 = Node(7) 6 | l4 = Node(6) 7 | r3 = Node(8) 8 | l2 = Node(4,None,l3) 9 | l1 = Node(2,l2,l5) 10 | r1 = Node(3,l4,r3) 11 | root = Node(1,l1,r1) 12 | 13 | ## Tree 2 14 | right3b = Node(7) 15 | right3a = Node(6) 16 | right2 = Node(3, right3a, right3b) 17 | left3b = Node(5) 18 | left3a = Node(4) 19 | left2 = Node(2,left3a,left3b) 20 | root2 = Node(1,left2,right2) 21 | 22 | ##Right Skewed Tree 23 | ra4 = Node(5,None,None) 24 | ra3 = Node(4,None,ra4) 25 | ra2 = Node(3,None,ra3) 26 | ra1 = Node(2,None,ra2) 27 | root3 = Node(1,None,ra1) 28 | 29 | ##Left Skewed Tree 30 | la4 = Node(5) 31 | la3 = Node(4,la4) 32 | la2 = Node(3,la3) 33 | la1 = Node(2,la2) 34 | root4 = Node(1,la1) 35 | 36 | ## Tree w Negatives 37 | l5 = Node(5) 38 | l3 = Node(9) 39 | l4 = Node(6) 40 | r3 = Node(-8,l3) 41 | l2 = Node(4,) 42 | l1 = Node(-2,l2,l5) 43 | r1 = Node(3,l4,r3) 44 | root5 = Node(1,l1,r1) 45 | 46 | ## Mirrors 47 | mirror = Node(1) 48 | 49 | ## BST 50 | l6 = Node(12) 51 | l5 = Node(6) 52 | l4 = Node(9) 53 | r3 = Node(15,l6) 54 | l2 = Node(3) 55 | l1 = Node(4,l2,l5) 56 | r1 = Node(11,l4,r3) 57 | bst1 = Node(7,l1,r1) 58 | 59 | ##Trees 60 | tree1 = root 61 | tree2 = root2 62 | tree3 = root3 63 | tree4 = root4 64 | negatives = root5 65 | bst1 = bst1 66 | --------------------------------------------------------------------------------