├── oop ├── __init__.py ├── employee.py └── restaurant.py ├── bitwise ├── __init__.py └── UpdateBits.py ├── Craking the Coding Interview ├── __init__.py ├── 9.1_countWays.py ├── 9.5_permutation.py ├── 1.4_encode_space.py ├── 1.3_anagram.py ├── 9.4_find_subsets_from_set.py ├── 1.2_reverseString.py ├── 5.1_updateBits.py ├── 1.1_isUniqChars.py ├── 3.2_push_pop_min_stack.py ├── 1.5_compress_word.py ├── 3.5_queue_using_two_stack ├── 2.3_remove_node_linkedlist.py ├── 2.1_del_dup_linkedlist.py ├── 5.0_bit_operator.py ├── 2.5_add_lists.py ├── 2.7_palindrome_linkedlist.py ├── 2.4_split_and_merge_linkedlist.py ├── 2.2_k_th_from_last_linkedlist.py ├── 3.3_set_of_stacks.py ├── 4.1_is_balanced_binary_tree.py └── 3.1_three_stacks_in_one_array.py ├── sort ├── __init__.py ├── BubbleSort.py ├── InsertionSort.py ├── SelectionSort.py ├── MergeSort.py ├── QuickSort.py └── HeapSort.py ├── data_structure ├── __init__.py ├── matrix.py ├── Queue.py ├── Stack.py ├── LinkedList.py └── BinaryTree.py ├── README.md ├── coding_interview_2018 ├── .idea │ ├── misc.xml │ ├── modules.xml │ ├── coding_interview_2017.iml │ └── workspace.xml ├── dynamic_programming │ ├── all_pairs_shortest_path.py │ ├── largest_sum_subarray.py │ └── longest_palindrome_subsequence.py ├── sort │ ├── quick_sort.py │ ├── heap_sort.py │ ├── merge_sort.py │ └── topological_sort.py ├── graph │ ├── dfs.py │ ├── bfs.py │ ├── island_count.py │ ├── bt_diameter.py │ ├── check_balanced_bt.py │ └── find_path_two_nodes_in_tree.py ├── etc │ ├── longest_substring_k_uniq_ch.py │ ├── longest_palindrome_substring.py │ └── lru_cache.py ├── binary_search │ ├── first_failed_build_ver.py │ └── find_k_rotated_sorted_array.py └── data_structure │ └── trie.py ├── dynamic_programming └── permutation.py ├── leetcode ├── test │ ├── lengthOfLongestSubstringTest.java │ ├── twoSumTest.java │ └── addTwoNumbersTest.java ├── algorithms │ └── 01.TwoSum.py └── src │ ├── twoSum.java │ ├── lengthOfLongestSubstring.java │ └── addTwoNumbers.java ├── javaSolution └── src │ ├── Collections │ └── MyCollectionsTest.java │ ├── data_structure │ ├── MyQueue.java │ ├── MyStack.java │ ├── MyLinkedList.java │ └── myBST.java │ ├── Sorts │ ├── MyHeapSort.java │ ├── MyMergeSort.java │ └── MyQuickSort.java │ ├── Strings │ └── MyStringTest.java │ ├── Graphs │ ├── MyDFS.java │ ├── MyBFS.java │ ├── FindShortestPathNoWeight.java │ └── Dijkstra.java │ └── Arrays │ └── MyArrayTest.java ├── graph ├── bfs.py ├── dfs.py └── dijkstra.py └── .gitignore /oop/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bitwise/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Craking the Coding Interview/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /sort/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | -------------------------------------------------------------------------------- /data_structure/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Problem Solving with Python 2 | 3 | Python implementation and unit tests for Algorithm, data struction and various interview questions. 4 | 5 | ## Authors 6 | 7 | * **Minsuk Heo** - [Homepage](http://minsuk-heo.github.io/) 8 | -------------------------------------------------------------------------------- /coding_interview_2018/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /data_structure/matrix.py: -------------------------------------------------------------------------------- 1 | def matrix(w,h): 2 | return [ [0 for x in range(w)] for y in range(h) ] 3 | 4 | m1 = matrix(3,4) 5 | print(m1) 6 | m1[0][0] = 1 7 | m1[0][1] = 2 8 | m1[0][2] = 3 9 | m1[1][0] = 4 10 | m1[1][1] = 5 11 | m1[1][2] = 6 12 | print(m1) 13 | -------------------------------------------------------------------------------- /Craking the Coding Interview/9.1_countWays.py: -------------------------------------------------------------------------------- 1 | def countWays(n): 2 | if(n < 0): 3 | return 0 4 | elif n == 0: 5 | return 1 6 | else: 7 | return countWays(n-1) + countWays(n-2) + countWays(n-3) 8 | 9 | 10 | print(countWays(3)) 11 | -------------------------------------------------------------------------------- /dynamic_programming/permutation.py: -------------------------------------------------------------------------------- 1 | def perm(n, i): 2 | if i == len(n) - 1: 3 | print(n) 4 | else: 5 | for j in range(i, len(n)): 6 | n[i], n[j] = n[j], n[i] 7 | perm(n, i + 1) 8 | n[i], n[j] = n[j], n[i] # swap back, for the next loop 9 | 10 | 11 | perm([1, 2, 3], 0) -------------------------------------------------------------------------------- /coding_interview_2018/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Craking the Coding Interview/9.5_permutation.py: -------------------------------------------------------------------------------- 1 | def perm(input, i): 2 | if i == len(input) - 1: 3 | print(input) 4 | else: 5 | for j in range(i, len(input)): 6 | input[i], input[j] = input[j], input[i] 7 | perm(input, i + 1) 8 | input[i], input[j] = input[j], input[i] # swap back, for the next loop 9 | 10 | 11 | perm([1, 2, 3], 0) -------------------------------------------------------------------------------- /oop/employee.py: -------------------------------------------------------------------------------- 1 | class person: 2 | def __init__(self, name): 3 | self.name = name 4 | def hello(self): 5 | print("hello my name is " + self.name) 6 | 7 | class employee(person): 8 | def __init__(self, name, title): 9 | self.name = name 10 | self.title = title 11 | 12 | john = person("john") 13 | john.hello() 14 | 15 | jane = employee("jane", "manager") 16 | jane.hello() -------------------------------------------------------------------------------- /leetcode/test/lengthOfLongestSubstringTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Assert; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | /** 6 | * Created by Minsuk_Heo on 12/18/2016. 7 | */ 8 | public class lengthOfLongestSubstringTest { 9 | @org.junit.Test 10 | public void lengthOfLongestSubstringTest() throws Exception { 11 | Assert.assertEquals(3, lengthOfLongestSubstring.solution("abcabcbb")); 12 | } 13 | } -------------------------------------------------------------------------------- /Craking the Coding Interview/1.4_encode_space.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | """ 3 | replace space with %20 4 | ex)"hey how are you " 5 | return hey%20how%20are%20you 6 | """ 7 | 8 | def encode_space(str,length): 9 | return str.strip().replace(" ", "%20") 10 | 11 | class encode_space_test(unittest.TestCase): 12 | def test(self): 13 | self.assertEqual("hey%20how%20are%20you",encode_space("hey how are you ",18)) -------------------------------------------------------------------------------- /leetcode/test/twoSumTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Minsuk_Heo on 12/17/2016. 3 | */ 4 | 5 | import org.junit.Assert; 6 | 7 | public class twoSumTest { 8 | @org.junit.Test 9 | public void twoSumTest() throws Exception { 10 | int [] testSet = {2,7,11,15}; 11 | int [] expected = {0,1}; 12 | Assert.assertEquals(0, twoSum.twoSum(testSet, 9)[0]); 13 | Assert.assertEquals(1, twoSum.twoSum(testSet, 9)[1]); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /coding_interview_2018/dynamic_programming/all_pairs_shortest_path.py: -------------------------------------------------------------------------------- 1 | """ 2 | Floyd Warshall Algorithm 3 | 4 | 3 5 | +-------+ 6 | | | 7 | | 2 v 8 | (0)<----(3)-------+ 9 | | ^ | 10 | 2 | | 6 | 2 11 | v | | 12 | (1)---->(2)<------+ 13 | 4 14 | 15 | """ 16 | # I is infinity 17 | I = 99999 18 | matrix = [[0,2,I,3], 19 | [I,0,4,I], 20 | [I,I,0,6], 21 | [2,I,2,0]] -------------------------------------------------------------------------------- /coding_interview_2018/.idea/coding_interview_2017.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /sort/BubbleSort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def bubblesort(alist): 4 | for i in range(len(alist)-1): 5 | for j in range(len(alist)-1): 6 | if alist[j] > alist[j+1]: 7 | alist[j], alist[j+1] = alist[j+1], alist[j] 8 | return alist 9 | 10 | 11 | class unit_test(unittest.TestCase): 12 | def test(self): 13 | self.assertEqual([1, 2, 3, 4, 5, 6], bubblesort([4, 6, 1, 3, 5, 2])) 14 | self.assertEqual([1, 2, 3, 4, 5, 6], bubblesort([6, 4, 3, 1, 2, 5])) 15 | self.assertEqual([1, 2, 3, 4, 5, 6], bubblesort([6, 5, 4, 3, 2, 1])) 16 | -------------------------------------------------------------------------------- /Craking the Coding Interview/1.3_anagram.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | anagram: true if listen and silent 5 | better ask if space is considered as string 6 | uppercase is different from lowercase 7 | """ 8 | 9 | def anagram(str1, str2): 10 | if ''.join(sorted(str1.lower())).strip() == ''.join(sorted(str2.lower())).strip(): 11 | return True 12 | else: 13 | return False 14 | 15 | class anagramTest(unittest.TestCase): 16 | def test(self): 17 | self.assertTrue(anagram("listen", "silent")) 18 | self.assertFalse(anagram("abc", "def")) 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Craking the Coding Interview/9.4_find_subsets_from_set.py: -------------------------------------------------------------------------------- 1 | class find_subsets_from_set: 2 | 3 | def sub_sets(self, set): 4 | # start by adding an empty set to all possible subsets 5 | return self.findSubset([], set) 6 | 7 | def findSubset(self, prev, subset): 8 | if subset: 9 | cur = subset[0] 10 | # findSubset(prev, next items) + findSubset(prev + current, next items) 11 | return self.findSubset(prev, subset[1:]) + self.findSubset(prev + [cur], subset[1:]) 12 | return [prev] 13 | 14 | 15 | print(find_subsets_from_set().sub_sets([2,1,3])) -------------------------------------------------------------------------------- /coding_interview_2018/sort/quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(input, start, end): 2 | if start >= end: 3 | return 4 | 5 | pivot = end 6 | window = start 7 | i = start 8 | while i < pivot: 9 | if input[i] < input[pivot]: 10 | input[window], input[i] = input[i], input[window] 11 | window += 1 12 | i += 1 13 | input[window], input[pivot] = input[pivot], input[window] 14 | pivot = window 15 | quick_sort(input, start, pivot-1) 16 | quick_sort(input, pivot+1, end) 17 | 18 | input = [4,9,1,2,8,3] 19 | quick_sort(input, 0 ,len(input)-1) 20 | print(input) -------------------------------------------------------------------------------- /coding_interview_2018/dynamic_programming/largest_sum_subarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | f([-2,-1,4,1]) = 5 3 | f([-2,-1,4,1,-3,1]) = 5 4 | """ 5 | 6 | def largest_sum_subarray(arr): 7 | l_sum = arr[0] 8 | cur = arr[0] 9 | for i in range(1, len(arr)): 10 | if cur > 0: 11 | cur = cur + arr[i] 12 | else: 13 | cur = arr[i] 14 | 15 | l_sum = max(l_sum, cur) 16 | 17 | return l_sum 18 | 19 | 20 | print( largest_sum_subarray( [-2,-1] ) ) 21 | print( largest_sum_subarray( [-2,-1,4,1] ) ) 22 | print( largest_sum_subarray( [-2,-1,4,1,-3,1] ) ) 23 | print( largest_sum_subarray( [-2,-1,4,1,-1,3] ) ) -------------------------------------------------------------------------------- /Craking the Coding Interview/1.2_reverseString.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # pythonic way 4 | def reverseString(str): 5 | return str[::-1] 6 | 7 | # use stack to solve problem 8 | def reverseString2(str): 9 | stack = [] 10 | for ch in str: 11 | stack.append(ch) 12 | 13 | result = "" 14 | while len(stack) > 0: 15 | result += stack.pop() 16 | 17 | return result 18 | 19 | class reverseStringTest(unittest.TestCase): 20 | def test(self): 21 | input = "abcde" 22 | self.assertEquals("edcba", reverseString(input)) 23 | 24 | input = "qwert" 25 | self.assertEquals("trewq", reverseString2(input)) -------------------------------------------------------------------------------- /bitwise/UpdateBits.py: -------------------------------------------------------------------------------- 1 | """ 2 | N = 10000000000 3 | M = 10011 4 | i = 2 5 | j = 6 6 | output : 10001001100 7 | """ 8 | 9 | def printBinary(num): 10 | b_num = bin(num) #b_num: 0bXXX 11 | print(b_num[2:]) #don't display b0 12 | 13 | def getMask(i,j,max_int): 14 | left = max_int << (j+1) 15 | right = (1 << i) - 1 16 | return left | right 17 | 18 | def UpdateBits(m,n,i,j): 19 | max_int = 2 ** 31 - 1 20 | mask = getMask(i,j,max_int) 21 | n_cleared = n & mask 22 | m_shifted = m << i 23 | return n_cleared | m_shifted 24 | 25 | m = 19 26 | n = 2048 27 | i = 2 28 | j = 6 29 | 30 | result = UpdateBits(m,n,i,j) 31 | printBinary(result) 32 | -------------------------------------------------------------------------------- /coding_interview_2018/graph/dfs.py: -------------------------------------------------------------------------------- 1 | """ 2 | 4 3 | / \ 4 | 1 5 5 | / \ \ 6 | 2 3 9 7 | 8 | """ 9 | 10 | vertice = [4,1,5,2,3,9] 11 | adj_list = {} 12 | adj_list[4] = [1,5] 13 | adj_list[1] = [2,3] 14 | adj_list[5] = [9] 15 | adj_list[2] = [] 16 | adj_list[3] = [] 17 | adj_list[9] = [] 18 | 19 | stack = [] 20 | visited = [] 21 | 22 | 23 | def dfs(start): 24 | stack.append(start) 25 | 26 | while len(stack) > 0: 27 | cur = stack.pop() 28 | for neighbor in adj_list[cur]: 29 | if not neighbor in visited: 30 | stack.append(neighbor) 31 | visited.append(cur) 32 | 33 | dfs(4) 34 | 35 | print(visited) -------------------------------------------------------------------------------- /coding_interview_2018/graph/bfs.py: -------------------------------------------------------------------------------- 1 | """ 2 | 4 3 | / \ 4 | 1 5 5 | / \ \ 6 | 2 3 9 7 | 8 | """ 9 | 10 | vertice = [4,1,5,2,3,9] 11 | adj_list = {} 12 | adj_list[4] = [1,5] 13 | adj_list[1] = [2,3] 14 | adj_list[5] = [9] 15 | adj_list[2] = [] 16 | adj_list[3] = [] 17 | adj_list[9] = [] 18 | 19 | stack = [] 20 | visited = [] 21 | 22 | 23 | def bfs(start): 24 | stack.append(start) 25 | 26 | while len(stack) > 0: 27 | cur = stack.pop() 28 | for neighbor in adj_list[cur]: 29 | if not neighbor in visited: 30 | stack.insert(0, neighbor) 31 | visited.append(cur) 32 | 33 | bfs(4) 34 | 35 | print(visited) -------------------------------------------------------------------------------- /javaSolution/src/Collections/MyCollectionsTest.java: -------------------------------------------------------------------------------- 1 | package Collections; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | 7 | /** 8 | * Created by Minsuk_Heo on 1/1/2017. 9 | */ 10 | public class MyCollectionsTest { 11 | public static void main(String[] args) { 12 | HashMap hMap = new HashMap(); 13 | hMap.put("1","first"); 14 | hMap.put("2","second"); 15 | 16 | Collection cl = hMap.values(); 17 | Iterator itr = cl.iterator(); 18 | 19 | while(itr.hasNext()){ 20 | System.out.println(itr.next()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /coding_interview_2018/etc/longest_substring_k_uniq_ch.py: -------------------------------------------------------------------------------- 1 | """ 2 | abaydae = 5 3 | abcade = 6 4 | """ 5 | 6 | 7 | def longest_substring(str, k): 8 | log = {} 9 | cur = "" 10 | largest = 0 11 | 12 | for i in range(len(str)): 13 | if not str[i] in log: 14 | log[str[i]] = 1 15 | cur += str[i] 16 | else: 17 | if log[str[i]] == k: 18 | largest = max(largest, len(cur)) 19 | start = cur.find(str[i]) 20 | cur = cur[start+1:] + str[i] 21 | else: 22 | log[str[i]] += 1 23 | cur += str[i] 24 | return max(largest, len(cur)) 25 | 26 | str ="aaaaaaa" 27 | print( longest_substring(str,2) ) 28 | 29 | str ="abaa" 30 | print( longest_substring(str,1) ) -------------------------------------------------------------------------------- /graph/bfs.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | 3 | vertexList = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] 4 | edgeList = [(0,1), (1,2), (1,3), (3,4), (4,5), (1,6)] 5 | graphs = (vertexList, edgeList) 6 | 7 | def bfs(graph, start): 8 | vertexList, edgeList = graph 9 | visitedList = [] 10 | queue = [start] 11 | adjacencyList = [[] for vertex in vertexList] 12 | 13 | # fill adjacencyList from graph 14 | for edge in edgeList: 15 | adjacencyList[edge[0]].append(edge[1]) 16 | 17 | # bfs 18 | while queue: 19 | current = queue.pop() 20 | for neighbor in adjacencyList[current]: 21 | if not neighbor in visitedList: 22 | queue.insert(0,neighbor) 23 | visitedList.append(current) 24 | return visitedList 25 | 26 | print(bfs(graphs, 0)) 27 | 28 | -------------------------------------------------------------------------------- /graph/dfs.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | 3 | vertexList = ['0', '1', '2', '3', '4', '5', '6'] 4 | edgeList = [(0,1), (0,2), (1,0) , (1,3) , (2,0) , (2,4) , (2,5) , (3,1), (4,2) , (4,6), (5,2), (6,4)] 5 | graphs = (vertexList, edgeList) 6 | 7 | def dfs(graph, start): 8 | vertexList, edgeList = graph 9 | visitedVertex = [] 10 | stack = [start] 11 | adjacencyList = [[] for vertex in vertexList] 12 | 13 | for edge in edgeList: 14 | adjacencyList[edge[0]].append(edge[1]) 15 | 16 | while stack: 17 | current = stack.pop() 18 | for neighbor in adjacencyList[current]: 19 | if not neighbor in visitedVertex: 20 | stack.append(neighbor) 21 | visitedVertex.append(current) 22 | return visitedVertex 23 | 24 | print(dfs(graphs, 0)) 25 | 26 | -------------------------------------------------------------------------------- /coding_interview_2018/sort/heap_sort.py: -------------------------------------------------------------------------------- 1 | def heap_sort(input): 2 | p = (len(input) // 2) - 1 3 | #heapify 4 | while p >= 0: 5 | siftdown(input, p, len(input)-1) 6 | p -= 1 7 | 8 | out = len(input) - 1 9 | while out > 0: 10 | input[0], input[out] = input[out], input[0] 11 | out -= 1 12 | siftdown(input, 0, out) 13 | 14 | def siftdown(arr, p, last): 15 | left = 2*p+1 16 | right = 2*p+2 17 | if left > last: 18 | return 19 | if right > last or arr[left] > arr[right]: 20 | max_node = left 21 | else: 22 | max_node = right 23 | 24 | if arr[max_node] > arr[p]: 25 | arr[max_node], arr[p] = arr[p], arr[max_node] 26 | siftdown(arr, max_node, last) 27 | 28 | 29 | input = [4,3,1,5,7,9] 30 | heap_sort(input) 31 | print(input) -------------------------------------------------------------------------------- /coding_interview_2018/sort/merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(input, start, end): 2 | if start == end: 3 | return 4 | 5 | mid = (start + end) // 2 6 | merge_sort(input, start, mid) 7 | merge_sort(input, mid+1, end) 8 | left = input[start: mid+1] 9 | right = input[mid+1: end+1] 10 | 11 | i,j,k = 0,0,start 12 | 13 | while i < len(left) and j < len(right): 14 | if left[i] < right[j]: 15 | input[k] = left[i] 16 | i += 1 17 | else: 18 | input[k] = right[j] 19 | j += 1 20 | k += 1 21 | 22 | while i < len(left): 23 | input[k] = left[i] 24 | i += 1 25 | k += 1 26 | 27 | while j < len(right): 28 | input[k] = right[j] 29 | j += 1 30 | k += 1 31 | 32 | 33 | input = [4,9,1,2,8,3] 34 | merge_sort(input, 0 ,len(input)-1) 35 | print(input) -------------------------------------------------------------------------------- /sort/InsertionSort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def insertion_sort(input): 4 | 5 | for idx, valueToInsert in enumerate(input): 6 | # select the hole position where number is to be inserted 7 | holePosition = idx 8 | 9 | # check if previous no. is larger than value to be inserted 10 | while holePosition > 0 and input[holePosition-1] > valueToInsert: 11 | input[holePosition - 1], input[holePosition] = input[holePosition], input[holePosition-1] 12 | holePosition = holePosition - 1 13 | 14 | return input 15 | 16 | class unit_test(unittest.TestCase): 17 | def test(self): 18 | self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([4, 6, 1, 3, 5, 2])) 19 | self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([6, 4, 3, 1, 2, 5])) 20 | self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([6, 5, 4, 3, 2, 1])) -------------------------------------------------------------------------------- /coding_interview_2018/binary_search/first_failed_build_ver.py: -------------------------------------------------------------------------------- 1 | """ 2 | S,S,S,F,F,F,F,F,F,F 3 | """ 4 | 5 | 6 | def binary_search(input, l, r): 7 | if len(input) < 1: 8 | return -1 9 | 10 | while l < r: 11 | mid = (l + r) // 2 12 | if input[mid] == "F": 13 | r = mid 14 | else: 15 | l = mid + 1 16 | 17 | return l if input[l] == "F" else -1 18 | 19 | 20 | input = ["S", "S", "S", "F", "F", "F", "F", "F", "F", "F"] 21 | idx = binary_search(input, 0 , len(input)-1) 22 | print(idx) 23 | 24 | input = ["F", "F", "F"] 25 | idx = binary_search(input, 0 , len(input)-1) 26 | print(idx) 27 | 28 | input = ["S", "S", "S"] 29 | idx = binary_search(input, 0 , len(input)-1) 30 | print(idx) 31 | 32 | input = ["S"] 33 | idx = binary_search(input, 0 , len(input)-1) 34 | print(idx) 35 | 36 | input = [] 37 | idx = binary_search(input, 0 , len(input)-1) 38 | print(idx) -------------------------------------------------------------------------------- /Craking the Coding Interview/5.1_updateBits.py: -------------------------------------------------------------------------------- 1 | """ 2 | N = 10000000000 3 | M = 10011 4 | i = 2 5 | j = 6 6 | output : 10001001100 7 | """ 8 | 9 | def printBinary(num): 10 | b_num = bin(num) #b_num: 0bXXX 11 | print(b_num[2:]) #don't display b0 12 | 13 | def getMask(i,j,max_int): 14 | # 11100000000 15 | left = max_int << (j+1) 16 | # 00000000011 17 | right = (1 << i) - 1 18 | # 11100000011 19 | return left | right 20 | 21 | def UpdateBits(m,n,i,j): 22 | max_int = 2 ** 32 - 1 23 | # mask = 11100000011 24 | mask = getMask(i,j,max_int) 25 | # n_cleared = 10000000000 26 | n_cleared = n & mask 27 | # m_shifted = 1001100 28 | m_shifted = m << i 29 | # return 10001001100 30 | return n_cleared | m_shifted 31 | 32 | # 19 = 10011 33 | m = 19 34 | # 1024 = 10000000000 35 | n = 1024 36 | i = 2 37 | j = 6 38 | 39 | result = UpdateBits(m,n,i,j) 40 | printBinary(result) 41 | -------------------------------------------------------------------------------- /sort/SelectionSort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def selectionSort(input): 4 | for i in range(len(input) - 1): 5 | # assume the min is the first element 6 | idx_min = i 7 | j = i + 1 8 | 9 | # test against elements after i to find the smallest 10 | while j < len(input): 11 | if(input[j] < input[idx_min]): 12 | # found new minimum; remember its index 13 | idx_min = j 14 | j = j + 1 15 | 16 | if idx_min is not i: 17 | # swap 18 | input[idx_min], input[i] = input[i], input[idx_min] 19 | 20 | return input 21 | 22 | class unit_test(unittest.TestCase): 23 | def test(self): 24 | self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([4, 6, 1, 3, 5, 2])) 25 | self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([6, 4, 3, 1, 2, 5])) 26 | self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([6, 5, 4, 3, 2, 1])) 27 | -------------------------------------------------------------------------------- /javaSolution/src/data_structure/MyQueue.java: -------------------------------------------------------------------------------- 1 | package data_structure; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * Created by Minsuk_Heo on 1/1/2017. 7 | */ 8 | public class MyQueue { 9 | ArrayList queue = new ArrayList(); 10 | 11 | public void enqueue(Integer n) { 12 | queue.add(n); 13 | } 14 | 15 | public Integer dequeue() { 16 | if(queue.isEmpty()) { 17 | System.out.println("queue is empty"); 18 | throw new java.util.NoSuchElementException(); 19 | } 20 | return queue.remove(0); 21 | } 22 | 23 | public static void main(String[] args) { 24 | MyQueue mq = new MyQueue(); 25 | mq.enqueue(1); 26 | mq.enqueue(2); 27 | mq.enqueue(3); 28 | mq.enqueue(4); 29 | System.out.println(mq.dequeue()); 30 | System.out.println(mq.dequeue()); 31 | System.out.println(mq.dequeue()); 32 | System.out.println(mq.dequeue()); 33 | } 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /sort/MergeSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | 3 | def mergeSort(alist): 4 | print("Splitting ",alist) 5 | if len(alist)>1: 6 | mid = len(alist)//2 7 | lefthalf = alist[:mid] 8 | righthalf = alist[mid:] 9 | 10 | mergeSort(lefthalf) 11 | mergeSort(righthalf) 12 | 13 | i=0 14 | j=0 15 | k=0 16 | while i < len(lefthalf) and j < len(righthalf): 17 | if lefthalf[i] < righthalf[j]: 18 | alist[k]=lefthalf[i] 19 | i=i+1 20 | else: 21 | alist[k]=righthalf[j] 22 | j=j+1 23 | k=k+1 24 | 25 | while i < len(lefthalf): 26 | alist[k]=lefthalf[i] 27 | i=i+1 28 | k=k+1 29 | 30 | while j < len(righthalf): 31 | alist[k]=righthalf[j] 32 | j=j+1 33 | k=k+1 34 | print("Merging ",alist) 35 | 36 | alist = [6,2,4,1,3,7,5,8] 37 | mergeSort(alist) 38 | print(alist) 39 | -------------------------------------------------------------------------------- /data_structure/Queue.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | __author__ = 'Minsuk Heo' 4 | 5 | """ 6 | Queue 7 | """ 8 | 9 | 10 | class Queue: 11 | 12 | def __init__(self): 13 | self.items = [] 14 | 15 | def enqueue(self, item): 16 | self.items.insert(0, item) 17 | 18 | def dequeue(self): 19 | self.items.pop() 20 | 21 | def print_queue(self): 22 | print(self.items) 23 | 24 | def is_empty(self): 25 | return self.items == [] 26 | 27 | def size(self): 28 | return len(self.items) 29 | 30 | class QueueTest(unittest.TestCase): 31 | def test(self): 32 | queue = Queue() 33 | self.assertTrue(queue.is_empty()) 34 | queue.enqueue(1) 35 | self.assertEqual(queue.size(),1) 36 | queue.enqueue(2) 37 | self.assertEqual(queue.size(),2) 38 | queue.print_queue() 39 | queue.dequeue() 40 | self.assertEqual(queue.size(),1) 41 | queue.print_queue() 42 | self.assertFalse(queue.is_empty()) 43 | -------------------------------------------------------------------------------- /leetcode/algorithms/01.TwoSum.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | You may assume that each input would have exactly one solution. 5 | 6 | Example, 7 | Given nums = [2, 7, 11, 15], target = 9, 8 | Because nums[0] + nums[1] = 2 + 7 = 9, 9 | return [0, 1]. 10 | """ 11 | import unittest 12 | 13 | class TwoSum(): 14 | def twoSum(self, nums, target): 15 | """ 16 | :type nums: List[int] 17 | :type target: int 18 | :rtype: List[int] 19 | """ 20 | n = len(nums) 21 | dict = {} 22 | for i in xrange(n): 23 | if(nums[i] in dict): 24 | return [dict[nums[i]], i] 25 | else: 26 | dict[target - nums[i]] = i 27 | 28 | class MyTest(unittest.TestCase): 29 | def test(self): 30 | ts = TwoSum() 31 | self.assertEqual(ts.twoSum([2,7,11,15], 9), [0,1]) 32 | self.assertEqual(ts.twoSum([2,7,11,15], 18), [1,2]) -------------------------------------------------------------------------------- /coding_interview_2018/etc/longest_palindrome_substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | f("a") = "a" 3 | f("aa") = "aa" 4 | f("aba") = "aba" 5 | f("abba") = "abba" 6 | f("abcdc") = "cdc" 7 | """ 8 | 9 | 10 | def find_pal(left, right, input): 11 | if right >= len(input): 12 | return "" 13 | if input[left] != input[right]: 14 | return "" 15 | while left >= 0 and right < len(input) and input[left] == input[right]: 16 | left -= 1 17 | right += 1 18 | 19 | return input[left+1:right] 20 | 21 | 22 | def longest_palindrome(input): 23 | if len(input) <= 1: 24 | return input 25 | max_odd = "" 26 | max_even = "" 27 | for idx in range(len(input)): 28 | max_odd = max(max_odd, find_pal(idx, idx, input)) 29 | max_even = max(max_even, find_pal(idx, idx+1, input)) 30 | return max(max_odd, max_even) 31 | 32 | print( longest_palindrome("") ) 33 | print( longest_palindrome("a") ) 34 | print( longest_palindrome("aa") ) 35 | print( longest_palindrome("aba") ) 36 | print( longest_palindrome("abcdc") ) 37 | -------------------------------------------------------------------------------- /Craking the Coding Interview/1.1_isUniqChars.py: -------------------------------------------------------------------------------- 1 | """ 2 | return true if the string doesn't have duplicate characters 3 | return false if the string has duplicate character by myself. 4 | """ 5 | import unittest 6 | 7 | def isUniqChars(str): 8 | # assume characters are ASCII, total 256 characters 9 | # if the string is greater than 256, there is duplicate 10 | if len(str) > 256: 11 | return False 12 | # initialize boolean array 13 | hash = [False] * 256 14 | 15 | for ch in str: 16 | # if boolean array is true, then there is duplicate 17 | if hash[ord(ch)] is True: 18 | return False 19 | # if the value in hash is False, the value is not duplicate yet 20 | else: 21 | hash[ord(ch)] = True 22 | return True 23 | 24 | 25 | class isUniqCharsTest(unittest.TestCase): 26 | def test(self): 27 | input_unique = "abcde" 28 | input_not_unique = "abcdea" 29 | self.assertTrue(isUniqChars(input_unique)) 30 | self.assertFalse(isUniqChars(input_not_unique)) 31 | -------------------------------------------------------------------------------- /Craking the Coding Interview/3.2_push_pop_min_stack.py: -------------------------------------------------------------------------------- 1 | """ 2 | stack has min function O(1) 3 | """ 4 | import unittest 5 | 6 | class stack(): 7 | def __init__(self): 8 | self.items = [] 9 | self.mins = [] 10 | self.min = None 11 | 12 | def push(self, item): 13 | self.items.append(item) 14 | if self.min is not None: 15 | self.mins.append(self.min) 16 | if self.min is None or self.min > item: 17 | self.min = item 18 | 19 | def pop(self): 20 | self.items.pop() 21 | self.min = self.mins.pop() 22 | 23 | def getminimum(self): 24 | return self.min 25 | 26 | def peak(self): 27 | return self.items[-1] 28 | 29 | class test(unittest.TestCase): 30 | def test(self): 31 | st = stack() 32 | st.push(5) 33 | self.assertEqual(5, st.getminimum()) 34 | st.push(3) 35 | self.assertEqual(3, st.getminimum()) 36 | self.assertEqual(3, st.peak()) 37 | st.pop() 38 | self.assertEqual(5, st.getminimum()) 39 | 40 | 41 | -------------------------------------------------------------------------------- /coding_interview_2018/data_structure/trie.py: -------------------------------------------------------------------------------- 1 | """ 2 | store word in dictionary 3 | search word in dictionary return True if exist 4 | """ 5 | 6 | class Trie: 7 | head = {} 8 | 9 | def add(self, word): 10 | cur = self.head 11 | for ch in word: 12 | if ch not in cur: 13 | cur[ch] = {} 14 | cur = cur[ch] 15 | # item denotes the Trie has this word as item 16 | # if item key doesn't exist Trie doesn't have this word but as path to longer word 17 | cur['*'] = True 18 | 19 | def search(self, word): 20 | cur = self.head 21 | for ch in word: 22 | if ch not in cur: 23 | return False 24 | cur = cur[ch] 25 | 26 | if '*' in cur: 27 | return True 28 | else: 29 | return False 30 | 31 | 32 | dictionary = Trie() 33 | 34 | dictionary.add("hi") 35 | dictionary.add("hello") 36 | print(dictionary.search("hi")) 37 | print(dictionary.search("hello")) 38 | print(dictionary.search("hel")) 39 | print(dictionary.search("hey")) -------------------------------------------------------------------------------- /Craking the Coding Interview/1.5_compress_word.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | """ 3 | abbcccccccd -> a1b2c7d1 4 | abc -> abc if the compression (a1b1c1) is longer than original, return original 5 | """ 6 | 7 | def compressword(input): 8 | buffer = None 9 | output = "" 10 | cnt = 1 11 | for ch in input: 12 | if buffer is None: 13 | output += ch 14 | buffer = ch 15 | else: 16 | if buffer == ch: 17 | cnt += 1 18 | else: 19 | output += str(cnt) 20 | cnt = 1 21 | output += ch 22 | buffer = ch 23 | output += str(cnt) 24 | 25 | if len(output) > len(input): 26 | return input 27 | else: 28 | return output 29 | 30 | class compress_test(unittest.TestCase): 31 | def test(self): 32 | self.assertEqual("a1b2c7d1",compressword("abbcccccccd")) 33 | self.assertEqual("a1b7c2d2", compressword("abbbbbbbccdd")) 34 | self.assertEqual("abc", compressword("abc")) 35 | self.assertEqual("aabcc", compressword("aabcc")) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | ### PyCharm ### 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 5 | 6 | # User-specific stuff: 7 | .idea/workspace.xml 8 | .idea/tasks.xml 9 | .idea/dictionaries 10 | .idea/vcs.xml 11 | .idea/jsLibraryMappings.xml 12 | 13 | # Sensitive or high-churn files: 14 | .idea/dataSources.ids 15 | .idea/dataSources.xml 16 | .idea/dataSources.local.xml 17 | .idea/sqlDataSources.xml 18 | .idea/dynamic.xml 19 | .idea/uiDesigner.xml 20 | 21 | # Gradle: 22 | .idea/gradle.xml 23 | .idea/libraries 24 | 25 | # Mongo Explorer plugin: 26 | .idea/mongoSettings.xml 27 | 28 | ## File-based project format: 29 | *.iws 30 | 31 | ## pycharm compile file 32 | *.pyc 33 | 34 | ## Plugin-specific files: 35 | 36 | # IntelliJ 37 | /out/ 38 | 39 | # mpeltonen/sbt-idea plugin 40 | .idea_modules/ 41 | 42 | # JIRA plugin 43 | atlassian-ide-plugin.xml 44 | 45 | # Crashlytics plugin (for Android Studio and IntelliJ) 46 | com_crashlytics_export_strings.xml 47 | crashlytics.properties 48 | crashlytics-build.properties 49 | fabric.properties -------------------------------------------------------------------------------- /coding_interview_2018/graph/island_count.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 0 0 0 0 1 4 | 1 1 0 0 1 5 | 1 1 0 1 0 6 | 0 0 1 1 0 7 | 0 0 0 0 1 8 | 9 | total 4 islands 10 | 11 | 1 0 0 12 | 0 1 0 13 | 0 1 1 14 | 15 | total 2 islands 16 | 17 | """ 18 | 19 | def adjacency_land(i,j, map): 20 | if i >= 0 and i < len(map) and j >= 0 and j < len(map[0]): 21 | if map[i][j] == 1: 22 | map[i][j] = 0 23 | adjacency_land(i - 1, j, map) 24 | adjacency_land(i + 1, j, map) 25 | adjacency_land(i, j - 1, map) 26 | adjacency_land(i, j + 1, map) 27 | 28 | def island_count(map): 29 | cnt = 0 30 | for i in range(len(map)): 31 | for j in range(len(map[0])): 32 | if map[i][j] == 1: 33 | cnt += 1 34 | map[i][j] = 0 35 | adjacency_land(i-1, j, map) 36 | adjacency_land(i+1, j, map) 37 | adjacency_land(i, j-1, map) 38 | adjacency_land(i, j+1, map) 39 | return cnt 40 | 41 | 42 | map = [ [0,0,0,0,1],[1,1,0,0,1], [1,1,0,1,0], [0,0,1,1,0], [0,0,0,0,1]] 43 | print(island_count(map)) 44 | 45 | map = [ [1,0,0],[0,1,0], [0,1,1]] 46 | print(island_count(map)) -------------------------------------------------------------------------------- /coding_interview_2018/dynamic_programming/longest_palindrome_subsequence.py: -------------------------------------------------------------------------------- 1 | # Returns the length of the longest palindromic subsequence 2 | 3 | def longest_palindrome_subsequence(str): 4 | n = len(str) 5 | 6 | # Create a table to store results of subproblems 7 | matrix = [] 8 | for i in range(n): 9 | matrix.append([0]*n) 10 | 11 | # Strings of length 1 are palindrome of length 1 12 | for i in range(n): 13 | matrix[i][i] = 1 14 | 15 | # window is length of substring 16 | for window in range(2, n + 1): 17 | for i in range(n - window + 1): 18 | j = i + window - 1 19 | if str[i] == str[j] and window == 2: 20 | matrix[i][j] = 2 21 | elif str[i] == str[j]: 22 | matrix[i][j] = matrix[i + 1][j - 1] + 2 23 | else: 24 | matrix[i][j] = max(matrix[i][j - 1], matrix[i + 1][j]); 25 | 26 | return matrix[0][n - 1] 27 | 28 | print(longest_palindrome_subsequence("a")) 29 | print(longest_palindrome_subsequence("abba")) 30 | print(longest_palindrome_subsequence("efet")) 31 | print(longest_palindrome_subsequence("abcdcba")) 32 | print(longest_palindrome_subsequence("abcddcba")) 33 | print(longest_palindrome_subsequence("awbcdedcba")) -------------------------------------------------------------------------------- /leetcode/src/twoSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Minsuk_Heo on 12/17/2016. 3 | * https://leetcode.com/problems/two-sum/ 4 | * Given nums = [2, 7, 11, 15], target = 9, 5 | * Because nums[0] + nums[1] = 2 + 7 = 9, 6 | * return [0, 1]. 7 | * 8 | * Time complexity: O(n) 9 | */ 10 | import java.util.*; 11 | 12 | public class twoSum { 13 | 14 | public static int[] twoSum(int[] nums, int target) { 15 | Hashtable hash = new Hashtable(); 16 | int[] answer = new int[2]; 17 | 18 | // iterate given array 19 | for(int i=0; i 4 -> 3) + (5 -> 6 -> 4) 11 | * Output: 7 -> 0 -> 8 12 | */ 13 | 14 | import static org.junit.Assert.*; 15 | 16 | /** 17 | * Created by Minsuk_Heo on 12/17/2016. 18 | */ 19 | public class addTwoNumbersTest { 20 | @Test 21 | public void addTwoNumbers() throws Exception { 22 | ListNode l1 = new ListNode(2); 23 | l1.next = new ListNode(4); 24 | l1.next.next = new ListNode(3); 25 | 26 | ListNode l2 = new ListNode(5); 27 | l2.next = new ListNode(6); 28 | l2.next.next = new ListNode(4); 29 | 30 | ListNode expected = addTwoNumbers.addTwoNumbers(l1, l2); 31 | 32 | Assert.assertEquals(7, expected.val); 33 | expected = expected.next; 34 | Assert.assertEquals(0, expected.val); 35 | expected = expected.next; 36 | Assert.assertEquals(8, expected.val); 37 | 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /coding_interview_2018/graph/bt_diameter.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 3 | /\ 4 | 2 5 5 | / \ 6 | 9 10 7 | 8 | diameter = 5 9 | 10 | 3 11 | /\ 12 | 2 5 13 | / \ \ 14 | 9 8 10 15 | \ 16 | 4 17 | 18 | diameter = 6 19 | 20 | """ 21 | 22 | 23 | class Node: 24 | def __init__(self, item): 25 | self.val = item 26 | self.left = None 27 | self.right = None 28 | 29 | 30 | def diameter(node): 31 | if not node: 32 | return 0 33 | left_diameter = longest_path(node.left) 34 | right_diameter = longest_path(node.right) 35 | return left_diameter + right_diameter + 1 36 | 37 | 38 | def longest_path(node): 39 | if not node: 40 | return 0 41 | 42 | left = longest_path(node.left) 43 | right = longest_path(node.right) 44 | 45 | return max(left, right) + 1 46 | 47 | 48 | head = Node(3) 49 | head.left = Node(2) 50 | head.right = Node(5) 51 | head.left.left = Node(9) 52 | head.right.right = Node(10) 53 | 54 | print(diameter(head)) 55 | 56 | head = Node(3) 57 | head.left = Node(2) 58 | head.right = Node(5) 59 | head.left.left = Node(9) 60 | head.left.right = Node(8) 61 | head.right.right = Node(10) 62 | head.left.right.right = Node(4) 63 | 64 | print(diameter(head)) 65 | 66 | print(diameter(None)) 67 | print(diameter(Node(10))) -------------------------------------------------------------------------------- /Craking the Coding Interview/2.3_remove_node_linkedlist.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo & Chris Jones' 2 | """ 3 | Linked List 4 | """ 5 | class Node: 6 | def __init__(self, item): 7 | self.val = item 8 | self.next = None 9 | 10 | # Class to handle the linked list options 11 | class LinkedList: 12 | def __init__(self, item): 13 | self.head = Node(item) 14 | 15 | # Adds a value to the linked list 16 | def add(self, item): 17 | cur = self.head 18 | while cur.next is not None: 19 | cur = cur.next 20 | cur.next = Node(item) 21 | 22 | # removes a value from teh linked list 23 | def remove_item(self, item): 24 | if self.head.val == item: 25 | self.head = self.head.next 26 | else: 27 | cur = self.head 28 | while cur.next is not None: 29 | if cur.next.val == item: 30 | next_node = cur.next.next 31 | cur.next = next_node 32 | break 33 | cur = cur.next 34 | 35 | def print_list(self): 36 | cur = self.head 37 | res = [] 38 | while cur is not None: 39 | res.append(cur.val) 40 | cur = cur.next 41 | return str(res) 42 | 43 | 44 | ll = LinkedList(9) 45 | ll.add(5) 46 | ll.add(8) 47 | ll.add(7) 48 | ll.add(6) 49 | ll.remove_item(6) 50 | print(ll.print_list()) 51 | -------------------------------------------------------------------------------- /coding_interview_2018/sort/topological_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | In Directed Acyclic Graph (DAG), when A->B, A must comes before B in the ordering. 3 | Implement topology sort to visit all vertice in the graph 4 | 5 | a ---> d ---> e <--- c 6 | ^ 7 | | 8 | b 9 | 10 | """ 11 | 12 | from collections import defaultdict 13 | 14 | # store edge information in adjacency list 15 | adjacency_list = defaultdict() 16 | adjacency_list['a'] = ['d'] 17 | adjacency_list['b'] = ['d'] 18 | adjacency_list['c'] = ['e'] 19 | adjacency_list['d'] = ['e'] 20 | adjacency_list['e'] = [] 21 | 22 | # store visited vertex information in visited_list 23 | visited_list = defaultdict() 24 | visited_list['a'] = False 25 | visited_list['b'] = False 26 | visited_list['c'] = False 27 | visited_list['d'] = False 28 | visited_list['e'] = False 29 | 30 | output_stack = [] 31 | 32 | ''' 33 | once visit vertex, change visited_list value to True so we don't revisit it again. 34 | recursively run topology sort to the neighbors in adjacency list. 35 | once all the neighbors are visited, put the current vertex in the output stack. 36 | ''' 37 | 38 | 39 | def topology_sort(vertex): 40 | if not visited_list[vertex]: 41 | visited_list[vertex] = True 42 | for neighbor in adjacency_list[vertex]: 43 | topology_sort(neighbor) 44 | output_stack.insert(0, vertex) 45 | 46 | for vertex in visited_list: 47 | topology_sort(vertex) 48 | 49 | print(output_stack) -------------------------------------------------------------------------------- /coding_interview_2018/graph/check_balanced_bt.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 3 | / \ 4 | 2 5 5 | 6 | balanced = True 7 | 8 | 3 9 | / \ 10 | 2 5 11 | / \ 12 | 9 8 13 | \ 14 | 4 15 | 16 | balanced = False 17 | 18 | 3 19 | /\ 20 | 2 5 21 | / \ \ 22 | 9 8 10 23 | \ 24 | 4 25 | 26 | balanced = True 27 | 28 | """ 29 | 30 | 31 | class Node: 32 | def __init__(self, item): 33 | self.val = item 34 | self.left = None 35 | self.right = None 36 | 37 | 38 | def get_depth(node): 39 | if not node: 40 | return 0 41 | 42 | left = get_depth(node.left) 43 | right = get_depth(node.right) 44 | 45 | if left == -1 or right == -1: 46 | return -1 47 | else: 48 | if abs(left - right) > 1: 49 | return -1 50 | else: 51 | return max(left, right)+1 52 | 53 | 54 | def check_balanced_bt(node): 55 | if not node: 56 | return True 57 | 58 | if get_depth(node) == -1: 59 | return False 60 | else: 61 | return True 62 | 63 | head = Node(3) 64 | head.left = Node(2) 65 | head.right = Node(5) 66 | head.right.right = Node(6) 67 | 68 | print(check_balanced_bt(head)) 69 | 70 | head = Node(3) 71 | head.left = Node(2) 72 | head.right = Node(5) 73 | head.right.right = Node(6) 74 | head.right.right.right = Node(6) 75 | 76 | print(check_balanced_bt(head)) -------------------------------------------------------------------------------- /Craking the Coding Interview/2.1_del_dup_linkedlist.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Linked List 4 | Delete Duplicate from linked list 5 | """ 6 | import unittest 7 | 8 | class Node: 9 | def __init__(self, item): 10 | self.val = item 11 | self.next = None 12 | 13 | class LinkedList: 14 | def __init__(self, item): 15 | self.head = Node(item) 16 | 17 | def add(self, item): 18 | cur = self.head 19 | while cur.next is not None: 20 | cur = cur.next 21 | cur.next = Node(item) 22 | 23 | def delete_duplicate(self): 24 | cur = self.head 25 | dict = {} 26 | prev = None 27 | while cur is not None: 28 | if cur.val in dict: 29 | prev.next = cur.next 30 | else: 31 | dict[cur.val]= True 32 | prev = cur 33 | cur = cur.next 34 | 35 | def printlist(self): 36 | cur = self.head 37 | res = [] 38 | while cur is not None: 39 | res.append(cur.val) 40 | cur = cur.next 41 | return str(res) 42 | 43 | class LinkedListTest(unittest.TestCase): 44 | def test(self): 45 | ll = LinkedList(3) 46 | ll.add(4) 47 | ll.add(5) 48 | ll.add(6) 49 | ll.add(4) 50 | ll.add(7) 51 | ll.add(4) 52 | ll.add(6) 53 | ll.add(6) 54 | ll.delete_duplicate() 55 | self.assertEqual("[3, 4, 5, 6, 7]", ll.printlist()) 56 | -------------------------------------------------------------------------------- /Craking the Coding Interview/5.0_bit_operator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | num = 10 (1010) 5 | """ 6 | def getBit(num, idx): 7 | if num & (1 << idx) != 0: 8 | return 1 9 | else: 10 | return 0 11 | 12 | def setBit(num, idx): 13 | return num | (1 << idx) 14 | 15 | def clearBit(num, idx): 16 | return num & ~(1 << idx) 17 | 18 | def clearBitsMSBThroughIdx(num, idx): 19 | mask = (1 << idx) - 1 20 | return num & mask 21 | 22 | class bittest(unittest.TestCase): 23 | def test(self): 24 | # 10 = 1010 in decimal expression 25 | 26 | #getBit test 27 | self.assertEqual(0, getBit(10, 0)) 28 | self.assertEqual(1, getBit(10, 1)) 29 | self.assertEqual(0, getBit(10, 2)) 30 | self.assertEqual(1, getBit(10, 3)) 31 | # setBit test 32 | self.assertEqual(11, setBit(10, 0)) 33 | self.assertEqual(10, setBit(10, 1)) 34 | self.assertEqual(14, setBit(10, 2)) 35 | # clearBit test 36 | self.assertEqual(10, clearBit(10, 0)) 37 | self.assertEqual(8, clearBit(10, 1)) 38 | self.assertEqual(10, clearBit(10, 2)) 39 | self.assertEqual(2, clearBit(10, 3)) 40 | # clearBitsMSBThroughIdx test 41 | self.assertEqual(0, clearBitsMSBThroughIdx(10, 0)) #0000 42 | self.assertEqual(0, clearBitsMSBThroughIdx(10, 1)) #0000 43 | self.assertEqual(2, clearBitsMSBThroughIdx(10, 2)) #0010 44 | self.assertEqual(2, clearBitsMSBThroughIdx(10, 3)) #0010 45 | 46 | -------------------------------------------------------------------------------- /leetcode/src/lengthOfLongestSubstring.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | 4 | /** 5 | * Created by Minsuk_Heo on 12/18/2016. 6 | * 7 | * Given a string, find the length of the longest substring without repeating characters. 8 | * Given "abcabcbb", the answer is "abc", which the length is 3. 9 | * Given "bbbbb", the answer is "b", with the length of 1. 10 | * Given "pwwkew", the answer is "wke", with the length of 3. 11 | * Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 12 | * 13 | */ 14 | public class lengthOfLongestSubstring { 15 | 16 | public static void main(String [] args) { 17 | String str = "abcabcbb"; 18 | int result = solution(str); 19 | System.out.println(result); 20 | } 21 | 22 | public static int solution(String s) { 23 | Map indexHash = new HashMap(); 24 | int lengthOfLongestSubstring = 0; 25 | int substring_ptr = -1; 26 | 27 | for(int runner_idx = 0; runner_idx < s.length(); runner_idx++) { 28 | char c = s.charAt(runner_idx); 29 | if(indexHash.containsKey(c)) { 30 | int duplicate_ptr = indexHash.get(c); 31 | substring_ptr = Math.max(substring_ptr, duplicate_ptr); 32 | } 33 | lengthOfLongestSubstring = Math.max(lengthOfLongestSubstring, runner_idx - substring_ptr); 34 | indexHash.put(c, runner_idx); 35 | } 36 | return lengthOfLongestSubstring; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /data_structure/Stack.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | __author__ = 'Minsuk Heo' 4 | 5 | """ 6 | Stack 7 | """ 8 | 9 | 10 | class Stack: 11 | def __init__(self): 12 | self.items = [] 13 | self.max = 5 14 | 15 | def push(self, item): 16 | if len(self.items) < 5: 17 | self.items.append(item) 18 | else: 19 | print("abort push in order to prevent stack overflow") 20 | 21 | def pop(self): 22 | if len(self.items) > 0: 23 | self.items.pop() 24 | else: 25 | print("stack is empty, abort pop to prevent stack underflow") 26 | 27 | def print_stack(self): 28 | print(self.items) 29 | 30 | def peek(self): 31 | return self.items[len(self.items)-1] 32 | 33 | def is_empty(self): 34 | return self.items == [] 35 | 36 | def size(self): 37 | return len(self.items) 38 | 39 | 40 | class StackTest(unittest.TestCase): 41 | def test(self): 42 | st = Stack() 43 | self.assertTrue(st.is_empty()) 44 | self.assertEqual(st.size(), 0) 45 | st.push(1) 46 | st.push(2) 47 | st.print_stack() 48 | st.pop() 49 | st.print_stack() 50 | st.push(3) 51 | self.assertEquals(st.peek(),3) 52 | self.assertFalse(st.is_empty()) 53 | self.assertEqual(st.size(), 2) 54 | st.pop() 55 | st.pop() 56 | st.pop() 57 | st.push(3) 58 | st.push(3) 59 | st.push(3) 60 | st.push(3) 61 | st.push(3) 62 | st.push(3) 63 | 64 | -------------------------------------------------------------------------------- /javaSolution/src/Sorts/MyHeapSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | /** 4 | * Created by Minsuk_Heo on 1/2/2017. 5 | */ 6 | public class MyHeapSort { 7 | 8 | public static void main(String[] args) { 9 | int [] arr = {4,2,8,1,3,5,7,9,6}; 10 | MyHeapSort mh = new MyHeapSort(); 11 | mh.heapsort(arr); 12 | } 13 | 14 | private void heapsort(int[] arr) { 15 | heapify(arr); 16 | int end = arr.length - 1; 17 | while(end > 0) { 18 | swap(arr, 0, end); 19 | siftdown(arr,0,end); 20 | end -= 1; 21 | } 22 | for(int i : arr){ 23 | System.out.println(i); 24 | } 25 | } 26 | 27 | private void heapify(int[] arr) { 28 | int p = arr.length / 2 - 1; 29 | while (p>=0) { 30 | siftdown(arr, p, arr.length); 31 | p -= 1; 32 | } 33 | 34 | } 35 | 36 | private void siftdown(int[] arr, int p, int size) { 37 | int l = 2*p + 1; 38 | int r = 2*p + 2; 39 | int largest = p; 40 | 41 | if (l <= size - 1 && arr[l] > arr[p]) { 42 | largest = l; 43 | } 44 | 45 | if (r <= size - 1 && arr[r] > arr[largest]) { 46 | largest = r; 47 | } 48 | 49 | if (largest != p) { 50 | swap(arr, p, largest); 51 | siftdown(arr, largest, size); 52 | } 53 | } 54 | 55 | private void swap(int[] arr, int i,int j){ 56 | int tmp = arr[i]; 57 | arr[i] = arr[j]; 58 | arr[j] = tmp; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /javaSolution/src/data_structure/MyStack.java: -------------------------------------------------------------------------------- 1 | package data_structure; 2 | 3 | 4 | /** 5 | * Created by Minsuk_Heo on 1/1/2017. 6 | */ 7 | public class MyStack { 8 | private T[] arr; 9 | private int top = 0; 10 | private static final int defaultStackSize = 3; 11 | 12 | public MyStack(){ 13 | this(defaultStackSize); 14 | } 15 | 16 | public MyStack(int stSize) { 17 | arr = (T[]) new Object[stSize]; 18 | } 19 | 20 | public void push(T element){ 21 | if(arr.length == top) { 22 | // prevent stack overflow 23 | System.out.println("stack is full, can't push"); 24 | } else { 25 | arr[top++] = element; 26 | } 27 | } 28 | 29 | public T pop() { 30 | if(top == 0) { 31 | System.out.println("no more item in the stack, can't pop"); 32 | throw new java.util.NoSuchElementException(); 33 | } else { 34 | T ele = arr[--top]; 35 | // prevent memory leak 36 | arr[top] = null; 37 | return ele; 38 | } 39 | } 40 | 41 | 42 | 43 | public static void main(String[] args) { 44 | MyStack intStack = new MyStack(5); 45 | intStack.push(2); 46 | intStack.push(3); 47 | System.out.println(intStack.pop()); 48 | System.out.println(intStack.pop()); 49 | MyStack stringStack = new MyStack(); 50 | stringStack.push("abc"); 51 | stringStack.push("def"); 52 | System.out.println(stringStack.pop()); 53 | System.out.println(stringStack.pop()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /javaSolution/src/Strings/MyStringTest.java: -------------------------------------------------------------------------------- 1 | package Strings; 2 | 3 | /** 4 | * Created by Minsuk_Heo on 12/30/2016. 5 | */ 6 | public class MyStringTest { 7 | 8 | public static void main(String [] args){ 9 | String str1 = "hello"; 10 | String str2 = "hello"; 11 | 12 | // How to Compare two string 13 | if(str1.equals(str2)) { 14 | System.out.println("same"); 15 | } 16 | // How to Remove character in string 17 | str1 = "this is java"; 18 | System.out.println(removeCharAt(str1,1)); 19 | // How to Replace character or substring by new one 20 | System.out.println(str1.replace("t", "T")); 21 | System.out.println(str1.replaceAll("is", "ARE")); 22 | // How to reverse string 23 | StringBuffer sb = new StringBuffer(str1); 24 | String reversed = sb.reverse().toString(); 25 | System.out.println(reversed); 26 | // How to split 27 | str1 = "jan-feb-march"; 28 | String[] temp; 29 | String delimeter = "-"; 30 | temp = str1.split(delimeter); 31 | for(String item : temp) { 32 | System.out.println(item); 33 | } 34 | // to uppercase 35 | System.out.println(str1.toUpperCase()); 36 | // string + string 37 | System.out.println(str1+str2); 38 | // string + string using stringbuffer 39 | sb.append("ap1"); 40 | sb.append("ap2"); 41 | System.out.println(sb); 42 | 43 | } 44 | 45 | private static String removeCharAt(String s, int pos) { 46 | return s.substring(0, pos) + s.substring(pos+1); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Craking the Coding Interview/2.5_add_lists.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Linked List 4 | input: 7-1-6, 5-9-2 # 617 + 295 5 | output: 912 6 | add two linked list and return int value 7 | """ 8 | import unittest 9 | 10 | class Node: 11 | def __init__(self, item): 12 | self.val = item 13 | self.next = None 14 | 15 | class LinkedList: 16 | def __init__(self, item): 17 | self.head = Node(item) 18 | 19 | def add(self, item): 20 | cur = self.head 21 | while cur.next is not None: 22 | cur = cur.next 23 | cur.next = Node(item) 24 | 25 | def getHead(self): 26 | return self.head 27 | 28 | def printlist(self): 29 | cur = self.head 30 | res = [] 31 | while cur is not None: 32 | res.append(cur.val) 33 | cur = cur.next 34 | return str(res) 35 | 36 | def solution(list1, list2): 37 | v1 = list1.getHead() 38 | v2 = list2.getHead() 39 | carry = 0 40 | while v1 is not None: 41 | val = ((v1.val + v2.val) % 10) + carry 42 | carry = (v1.val + v2.val) // 10 43 | v1.val = val 44 | v1 = v1.next 45 | v2 = v2.next 46 | 47 | cur = list1.getHead() 48 | val = 0 49 | mul = 1 50 | while cur is not None: 51 | val = val + (cur.val * mul) 52 | mul = mul * 10 53 | cur = cur.next 54 | return val 55 | 56 | class LinkedListTest(unittest.TestCase): 57 | def test(self): 58 | list1 = LinkedList(7) 59 | list1.add(1) 60 | list1.add(6) 61 | 62 | list2 = LinkedList(5) 63 | list2.add(9) 64 | list2.add(2) 65 | 66 | self.assertEqual(912, solution(list1,list2)) -------------------------------------------------------------------------------- /Craking the Coding Interview/2.7_palindrome_linkedlist.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Palindrome 4 | a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. 5 | 1-3-5-3-1 is palindrome 6 | 5-9-2 is not palindrome 7 | """ 8 | import unittest 9 | 10 | class Node: 11 | def __init__(self, item): 12 | self.val = item 13 | self.next = None 14 | 15 | class LinkedList: 16 | def __init__(self, item): 17 | self.head = Node(item) 18 | 19 | def add(self, item): 20 | cur = self.head 21 | while cur.next is not None: 22 | cur = cur.next 23 | cur.next = Node(item) 24 | 25 | def getHead(self): 26 | return self.head 27 | 28 | def reverse(self): 29 | prev = None 30 | cur = self.head 31 | while cur is not None: 32 | next = cur.next 33 | cur.next = prev 34 | prev = cur 35 | cur = next 36 | self.head = prev 37 | 38 | def printlist(self): 39 | cur = self.head 40 | res = [] 41 | while cur is not None: 42 | res.append(cur.val) 43 | cur = cur.next 44 | return str(res) 45 | 46 | def solution(list): 47 | input = list.printlist() 48 | list.reverse() 49 | output = list.printlist() 50 | if input == output: 51 | return True 52 | else: 53 | return False 54 | 55 | class LinkedListTest(unittest.TestCase): 56 | def test(self): 57 | list1 = LinkedList(1) 58 | list1.add(3) 59 | list1.add(5) 60 | list1.add(3) 61 | list1.add(1) 62 | 63 | list2 = LinkedList(5) 64 | list2.add(9) 65 | list2.add(2) 66 | 67 | self.assertEqual(True, solution(list1)) 68 | self.assertEqual(False, solution(list2)) -------------------------------------------------------------------------------- /javaSolution/src/Sorts/MyMergeSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | import java.util.Arrays; 3 | /** 4 | * Created by Minsuk_Heo on 1/2/2017. 5 | */ 6 | public class MyMergeSort { 7 | int [] tmpArr; 8 | public static void main(String[] args) { 9 | int [] arr = {4,2,8,1,3,5,7,9,6}; 10 | MyMergeSort msort = new MyMergeSort(); 11 | msort.mergesort(arr); 12 | } 13 | 14 | public void mergesort(int[] arr) { 15 | tmpArr = new int[arr.length]; 16 | System.out.println("splitting"+Arrays.toString(arr)); 17 | merge(arr, 0, arr.length-1); 18 | 19 | } 20 | 21 | private void merge(int[] arr, int begin, int end) { 22 | if(begin < end) { 23 | int mid = (begin+end) / 2; 24 | merge(arr, begin, mid); 25 | merge(arr, mid+1, end); 26 | 27 | for(int i = begin; i<=end;i++) { 28 | tmpArr[i] = arr[i]; 29 | } 30 | 31 | int i=begin, j=mid+1, k=begin; 32 | while(i <= mid && j <= end) { 33 | if (tmpArr[i] < tmpArr[j]) { 34 | arr[k] = tmpArr[i]; 35 | i++; 36 | } 37 | else{ 38 | arr[k] = tmpArr[j]; 39 | j++; 40 | } 41 | k++; 42 | } 43 | while(i<=mid) { 44 | arr[k] = tmpArr[i]; 45 | i++; 46 | k++; 47 | } 48 | while(j<=end) { 49 | arr[k] = tmpArr[j]; 50 | j++; 51 | k++; 52 | } 53 | } 54 | 55 | System.out.println(Arrays.toString(arr)); 56 | } 57 | 58 | private void swap(int[] arr, int i,int j){ 59 | int tmp = arr[i]; 60 | arr[i] = arr[j]; 61 | arr[j] = tmp; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /sort/QuickSort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def quick_sort(list, start, end): 4 | # repeat until sublist has one item 5 | # because the algorithm is using in-place space, we can not use len(list) instead we use start, end for sublist 6 | if start < end: 7 | # get pivot using partition method 8 | pivot = partition(list, start, end) 9 | # recurse quick sort left side from pivot 10 | quick_sort(list, start, pivot-1) 11 | # recurse quick sort right side from pivot 12 | quick_sort(list,pivot+1, end) 13 | return list 14 | 15 | def partition(list, start, end): 16 | # use end item as initial pivot 17 | pivot = end 18 | # use start as initial wall index 19 | wall = start 20 | left = start 21 | # repeat until left item hit the end of list 22 | while left < pivot: 23 | # if left item is smaller than pivot, swap left item with wall and move wall to right 24 | # this will ensure items smaller than pivot stay left side from the wall and 25 | # the items greater than pivot stay right side from the wall 26 | if list[left] < list[pivot]: 27 | list[wall], list[left] = list[left], list[wall] 28 | wall = wall + 1 29 | left = left + 1 30 | # when left hit the end of list, swap pivot with wall 31 | list[wall], list[pivot] = list[pivot], list[wall] 32 | # now left side of wall are the items smaller than wall 33 | # now right side of pivot are the items greater than wall 34 | # wall is the new pivot 35 | pivot = wall 36 | return pivot 37 | 38 | class unit_test(unittest.TestCase): 39 | def test(self): 40 | list = [8, 13, 2, 6, 1, 4] 41 | self.assertEqual([1, 2, 4, 6, 8, 13], quick_sort(list,0,len(list)-1)) 42 | list = [8, 1, 2, 5, 10, 14, 7, 21] 43 | self.assertEqual([1, 2, 5, 7, 8, 10, 14, 21], quick_sort(list, 0, len(list) - 1)) -------------------------------------------------------------------------------- /coding_interview_2018/graph/find_path_two_nodes_in_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 3 | /\ 4 | 2 5 5 | / \ \ 6 | 9 8 10 7 | \ 8 | 4 9 | 10 | (9,4) : 9-2-8-4 11 | (4,10) : 4-8-2-3-5-10 12 | """ 13 | 14 | class Node: 15 | def __init__(self, item): 16 | self.val = item 17 | self.left = None 18 | self.right = None 19 | 20 | 21 | def print_tree(cur): 22 | if cur.left: 23 | print_tree(cur.left) 24 | print(cur.val) 25 | if cur.right: 26 | print_tree(cur.right) 27 | 28 | 29 | def find_node(cur, target, path): 30 | if not cur: 31 | return [] 32 | 33 | if cur.val == target: 34 | return path + [cur] 35 | else: 36 | lpath = find_node(cur.left, target, path + [cur]) 37 | rpath = find_node(cur.right, target, path + [cur]) 38 | 39 | if lpath is None and rpath is None: 40 | return [] 41 | if lpath: 42 | return lpath 43 | if rpath: 44 | return rpath 45 | 46 | def find_path(tree, n1, n2): 47 | # find first node 48 | n1_path = find_node(tree, n1, []) 49 | ans = [] 50 | if not n1_path: 51 | return None 52 | else: 53 | n1_path = n1_path[::-1] 54 | 55 | for idx, cur in enumerate(n1_path): 56 | n2_path = find_node(cur, n2, []) 57 | if n2_path: 58 | ans = n1_path[:idx]+n2_path 59 | break 60 | 61 | return ans 62 | 63 | head = Node(3) 64 | head.left = Node(2) 65 | head.right = Node(5) 66 | head.left.left = Node(9) 67 | head.left.right = Node(8) 68 | head.right.right = Node(10) 69 | head.left.right.right = Node(4) 70 | 71 | 72 | print([node.val for node in find_path(head, 9, 4)]) 73 | print([node.val for node in find_path(head, 4, 10)]) 74 | print([node.val for node in find_path(head, 4, 4)]) 75 | print([node.val for node in find_path(head, 4, 99)]) 76 | 77 | -------------------------------------------------------------------------------- /Craking the Coding Interview/2.4_split_and_merge_linkedlist.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Linked List 4 | input: 6-3-8-1-5-9,5 5 | output: 1-3-5-6-8-9 6 | sort linked list with a key, 7 | """ 8 | import unittest 9 | 10 | class Node: 11 | def __init__(self, item): 12 | self.val = item 13 | self.next = None 14 | 15 | class LinkedList: 16 | def __init__(self, item): 17 | self.head = Node(item) 18 | 19 | def add(self, item): 20 | cur = self.head 21 | while cur.next is not None: 22 | cur = cur.next 23 | cur.next = Node(item) 24 | 25 | def getHead(self): 26 | return self.head 27 | 28 | def printlist(self): 29 | cur = self.head 30 | res = [] 31 | while cur is not None: 32 | res.append(cur.val) 33 | cur = cur.next 34 | return str(res) 35 | 36 | def solution(ll, key): 37 | cur = ll.getHead() 38 | pre = None 39 | post = None 40 | while cur is not None: 41 | if cur.val != key: 42 | if cur.val > key: 43 | if post is None: 44 | post = LinkedList(cur.val) 45 | else: 46 | post.add(cur.val) 47 | elif cur.val < key: 48 | if pre is None: 49 | pre = LinkedList(cur.val) 50 | else: 51 | pre.add(cur.val) 52 | cur = cur.next 53 | 54 | cur = pre.getHead() 55 | while cur.next is not None: 56 | cur = cur.next 57 | cur.next = Node(key) 58 | cur.next.next = post.getHead() 59 | return pre.printlist() 60 | 61 | 62 | 63 | 64 | class LinkedListTest(unittest.TestCase): 65 | def test(self): 66 | ll = LinkedList(6) 67 | ll.add(3) 68 | ll.add(8) 69 | ll.add(1) 70 | ll.add(5) 71 | ll.add(9) 72 | self.assertEqual("[3, 1, 5, 6, 8, 9]", solution(ll,5)) 73 | -------------------------------------------------------------------------------- /coding_interview_2018/etc/lru_cache.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,k,v): 3 | self.key = k 4 | self.val = v 5 | self.prev = None 6 | self.next = None 7 | 8 | 9 | class LRU: 10 | def __init__(self, capacity): 11 | self.capacity = capacity 12 | self.dict = {} 13 | self.head = Node(0,0) 14 | self.tail = Node(0,0) 15 | self.head.next = self.tail 16 | self.tail.prev = self.head 17 | 18 | def remove_node(self, node): 19 | prev = node.prev 20 | next = node.next 21 | prev.next = next 22 | next.prev = prev 23 | 24 | def add_node(self, node): 25 | prev = self.tail.prev 26 | prev.next = node 27 | node.prev = prev 28 | node.next = self.tail 29 | self.tail.prev = node 30 | 31 | def get(self, k): 32 | if k in self.dict: 33 | return self.dict[k].val 34 | else: 35 | return -1 36 | 37 | def put(self, k, v): 38 | if k in self.dict: 39 | node = Node(k,v) 40 | self.remove_node(self.dict[k]) 41 | self.dict[k] = node 42 | self.add_node(node) 43 | else: 44 | if len(self.dict) >= self.capacity: 45 | first = self.head.next 46 | second = self.head.next.next 47 | self.head.next = second 48 | second.prev = self.head 49 | del dict[first.key] 50 | 51 | node = Node(k, v) 52 | self.dict[k] = node 53 | self.add_node(node) 54 | 55 | 56 | def status(self): 57 | cur = self.head 58 | while cur: 59 | print(cur.val) 60 | cur = cur.next 61 | 62 | cache = LRU(3) 63 | cache.put(1,1) 64 | cache.put(2,2) 65 | cache.put(3,3) 66 | cache.put(3,3) 67 | #cache.put(2,2) 68 | cache.status() 69 | print(cache.get(1)) 70 | print(cache.get(2)) 71 | print(cache.get(3)) 72 | print(cache.get(4)) -------------------------------------------------------------------------------- /Craking the Coding Interview/2.2_k_th_from_last_linkedlist.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Linked List 4 | k th node value from last node 5 | """ 6 | import unittest 7 | 8 | class Node: 9 | def __init__(self, item): 10 | self.val = item 11 | self.next = None 12 | 13 | class LinkedList: 14 | def __init__(self, item): 15 | self.head = Node(item) 16 | 17 | def add(self, item): 18 | cur = self.head 19 | while cur.next is not None: 20 | cur = cur.next 21 | cur.next = Node(item) 22 | 23 | def printlist(self): 24 | cur = self.head 25 | res = [] 26 | while cur is not None: 27 | res.append(cur.val) 28 | cur = cur.next 29 | return str(res) 30 | 31 | def kth_element_from_last(self,k): 32 | p1 = self.head 33 | p2 = self.head 34 | if k != 0: 35 | for i in range(k): 36 | p2 = p2.next 37 | # over flow k is greater than linkedlist length 38 | if p2 is None: 39 | return None 40 | # run until p2 reach the end 41 | while p2.next is not None: 42 | p2 = p2.next 43 | p1 = p1.next 44 | # since p2 - p1 is the k, now p1 position is the k th from last node 45 | return p1.val 46 | 47 | 48 | class LinkedListTest(unittest.TestCase): 49 | def test(self): 50 | ll = LinkedList(3) 51 | ll.add(4) 52 | ll.add(5) 53 | ll.add(6) 54 | ll.add(4) 55 | ll.add(7) 56 | ll.add(4) 57 | self.assertEqual(4, ll.kth_element_from_last(0)) 58 | self.assertEqual(7, ll.kth_element_from_last(1)) 59 | self.assertEqual(4, ll.kth_element_from_last(2)) 60 | self.assertEqual(6, ll.kth_element_from_last(3)) 61 | self.assertEqual(5, ll.kth_element_from_last(4)) 62 | self.assertEqual(4, ll.kth_element_from_last(5)) 63 | self.assertEqual(3, ll.kth_element_from_last(6)) 64 | self.assertEqual(None, ll.kth_element_from_last(7)) 65 | -------------------------------------------------------------------------------- /coding_interview_2018/binary_search/find_k_rotated_sorted_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | [1,2,3,4,5] k=4, return 3 3 | [1,2,3,4,5] k=6, return -1 4 | [4,5,1,2,3] k=4, return 0 5 | """ 6 | 7 | def find_pivot(arr,l, r): 8 | if len(arr) < 1: 9 | return -1 10 | if arr[l] < arr[r]: 11 | return -1 12 | 13 | while l < r: 14 | mid = (l + r) // 2 15 | if arr[mid] < arr[mid-1]: 16 | return mid -1 17 | else: 18 | if arr[mid] > arr[l]: 19 | l = mid 20 | else: 21 | r = mid - 1 22 | return l 23 | 24 | 25 | def find_k(arr, pivot, k): 26 | if arr[pivot] == k : 27 | return pivot 28 | 29 | if pivot == -1: 30 | #binary search on arr 31 | l, r = 0, len(arr)-1 32 | elif pivot == 0: 33 | l, r = pivot+1, len(arr)-1 34 | else: 35 | #binary search considering pivot 36 | if k >= arr[0] and k < arr[pivot]: 37 | l, r = 0, pivot-1 38 | else: 39 | l, r = pivot+1, len(arr)-1 40 | 41 | while l < r: 42 | mid = (l + r) // 2 43 | if arr[mid] == k: 44 | return mid 45 | else: 46 | if arr[mid] < k: 47 | l = mid + 1 48 | else: 49 | r = mid - 1 50 | 51 | return l if arr[l] == k else -1 52 | 53 | 54 | arr = [5,1,2,3,4] 55 | pivot = find_pivot(arr, 0 ,len(arr)-1) 56 | #print(pivot) 57 | #print(find_k(arr, pivot, 4)) 58 | 59 | 60 | arr = [4,5,1,2,3] 61 | pivot = find_pivot(arr, 0 ,len(arr)-1) 62 | #print(pivot) 63 | #print(find_k(arr, pivot, 4)) 64 | 65 | 66 | arr = [3,4,5,1,2] 67 | pivot = find_pivot(arr, 0 ,len(arr)-1) 68 | #print(pivot) 69 | #print(find_k(arr, pivot, 4)) 70 | 71 | arr = [2,3,4,5,1] 72 | pivot = find_pivot(arr, 0 ,len(arr)-1) 73 | #print(pivot) 74 | #print(find_k(arr, pivot, 4)) 75 | 76 | arr = [1,2,3,4,5] 77 | pivot = find_pivot(arr, 0 ,len(arr)-1) 78 | #print(pivot) 79 | #print(find_k(arr, pivot, 4)) 80 | 81 | arr = [1,2,3,4,5] 82 | pivot = find_pivot(arr, 0 ,len(arr)-1) 83 | print(pivot) 84 | print(find_k(arr, pivot, 40)) -------------------------------------------------------------------------------- /javaSolution/src/data_structure/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | package data_structure; 2 | 3 | /** 4 | * Created by Minsuk_Heo on 1/1/2017. 5 | */ 6 | public class MyLinkedList { 7 | Node head = null; 8 | 9 | public void add(int n){ 10 | Node newNode = new Node(n); 11 | if(head == null){ 12 | head = newNode; 13 | } else{ 14 | Node cur = head; 15 | while(cur.next != null){ 16 | cur = cur.next; 17 | } 18 | cur.next = newNode; 19 | } 20 | } 21 | 22 | public void remove(int n){ 23 | Node cur = head; 24 | 25 | if(head.val == n) { 26 | head = cur.next; 27 | cur = null; 28 | } else { 29 | while(cur.next != null) { 30 | if(cur.next.val == n) { 31 | cur.next = cur.next.next; 32 | System.out.println(n+ " removed successfully"); 33 | return; 34 | } 35 | cur = cur.next; 36 | } 37 | System.out.println(n+" is not in linkedlist"); 38 | } 39 | } 40 | 41 | public void reverse(){ 42 | Node cur = head; 43 | Node prev = null; 44 | Node next = null; 45 | 46 | while(cur != null){ 47 | next = cur.next; 48 | cur.next = prev; 49 | prev = cur; 50 | cur = next; 51 | } 52 | head = prev; 53 | } 54 | 55 | public void print(){ 56 | Node cur = head; 57 | 58 | while(cur != null){ 59 | System.out.println(cur.val); 60 | cur = cur.next; 61 | } 62 | } 63 | 64 | public static void main(String[] args) { 65 | MyLinkedList ml = new MyLinkedList(); 66 | ml.add(1); 67 | ml.add(2); 68 | ml.add(3); 69 | ml.add(4); 70 | ml.print(); 71 | ml.reverse(); 72 | ml.print(); 73 | } 74 | } 75 | 76 | class Node{ 77 | int val; 78 | Node next; 79 | 80 | public Node(int n){ 81 | val = n; 82 | next = null; 83 | } 84 | } -------------------------------------------------------------------------------- /oop/restaurant.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class person: 4 | def __init__(self, name, phone): 5 | self.name = name 6 | self.phone = phone 7 | 8 | class caller(person): 9 | def __init__(self, name, phone): 10 | person.__init__(self, name, phone) 11 | 12 | def setNumberOfPeople(self, count): 13 | self.numberOfPeople = count 14 | 15 | def getNumberOfPeople(self): 16 | return self.numberOfPeople 17 | 18 | def setSchedule(self, schedule): 19 | self.schedule = schedule 20 | 21 | def getSchedule(self): 22 | return self.schedule 23 | 24 | class employee(person): 25 | def __init__(self, name, phone, title): 26 | person.__init__(self, name, phone) 27 | self.setTitle(title) 28 | 29 | def setTitle(self, title): 30 | self.title = title 31 | 32 | 33 | class restaurant: 34 | def __init__(self): 35 | self.TABLE_COUNT = 4 36 | self.tablelist = [] 37 | self.tablelist.append(table(2)) 38 | self.tablelist.append(table(4)) 39 | self.tablelist.append(table(6)) 40 | self.tablelist.append(table(8)) 41 | 42 | def makeReservation(self, caller): 43 | print(caller.getSchedule()) 44 | for i in self.tablelist: 45 | if i.capacity >= caller.getNumberOfPeople(): 46 | if i.schedule.timetable[caller.getSchedule()] is None: 47 | i.schedule.timetable[caller.getSchedule()] = caller 48 | print(caller.name + "has scheulded on " + caller.getSchedule() + "at " + str(i.capacity) + " size table") 49 | return True 50 | 51 | class table: 52 | def __init__(self, capacity): 53 | self.capacity = capacity 54 | self.schedule = schedule() 55 | 56 | class schedule: 57 | def __init__(self): 58 | self.timetable = {"12-1": None, "1-2": None, "2-3": None, "3-4": None, "4-5": None} 59 | 60 | class RestaurantTest(unittest.TestCase): 61 | def test(self): 62 | bj = restaurant() 63 | caller1 = caller("caller1", "619-999-9999") 64 | caller1.setNumberOfPeople(3) 65 | caller1.setSchedule("1-2") 66 | 67 | self.assertTrue(True, bj.makeReservation(caller1)) 68 | 69 | 70 | -------------------------------------------------------------------------------- /javaSolution/src/Graphs/MyDFS.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | /** 7 | * Created by Minsuk_Heo on 1/5/2017. 8 | */ 9 | public class MyDFS { 10 | public static void main(String[] args) { 11 | ArrayList vertexList = new ArrayList<>(); 12 | vertexList.add(0); 13 | vertexList.add(1); 14 | vertexList.add(2); 15 | vertexList.add(3); 16 | vertexList.add(4); 17 | vertexList.add(5); 18 | vertexList.add(6); 19 | 20 | ArrayList edgeList = new ArrayList<>(); 21 | edgeList.add(new int[]{0, 1}); 22 | edgeList.add(new int[]{0, 2}); 23 | edgeList.add(new int[]{1, 0}); 24 | edgeList.add(new int[]{1, 3}); 25 | edgeList.add(new int[]{2, 0}); 26 | edgeList.add(new int[]{2, 4}); 27 | edgeList.add(new int[]{2, 5}); 28 | edgeList.add(new int[]{3, 1}); 29 | edgeList.add(new int[]{4, 2}); 30 | edgeList.add(new int[]{4, 6}); 31 | edgeList.add(new int[]{4, 5}); 32 | edgeList.add(new int[]{5, 4}); 33 | edgeList.add(new int[]{5, 2}); 34 | edgeList.add(new int[]{6, 4}); 35 | 36 | MyDFS dfs = new MyDFS(); 37 | ArrayList visitedNodeList = dfs.run(vertexList,edgeList, 0); 38 | System.out.println(visitedNodeList.toString()); 39 | 40 | } 41 | 42 | private ArrayList run(ArrayList vertexList, ArrayList edgeList, int n) { 43 | ArrayList visitedList = new ArrayList<>(); 44 | Stack myStack = new Stack(); 45 | myStack.push(n); 46 | 47 | ArrayList[] adjacencyList = new ArrayList[vertexList.size()]; 48 | for(int i=0; i(); 50 | } 51 | 52 | for(int[] edge : edgeList){ 53 | adjacencyList[edge[0]].add(edge[1]); 54 | } 55 | 56 | int current; 57 | while(!myStack.isEmpty()) { 58 | current = myStack.pop(); 59 | for (int neighbor : adjacencyList[current]) { 60 | if(!visitedList.contains(neighbor)){ 61 | myStack.push(neighbor); 62 | } 63 | } 64 | visitedList.add(current); 65 | } 66 | return visitedList; 67 | } 68 | } -------------------------------------------------------------------------------- /javaSolution/src/Graphs/MyBFS.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Created by Minsuk_Heo on 1/3/2017. 8 | */ 9 | public class MyBFS { 10 | 11 | public static void main(String[] args) { 12 | ArrayList vertexList = new ArrayList<>(); 13 | vertexList.add(0); 14 | vertexList.add(1); 15 | vertexList.add(2); 16 | vertexList.add(3); 17 | vertexList.add(4); 18 | vertexList.add(5); 19 | vertexList.add(6); 20 | 21 | ArrayList edgeList = new ArrayList<>(); 22 | edgeList.add(new int[]{0, 1}); 23 | edgeList.add(new int[]{1, 2}); 24 | edgeList.add(new int[]{1, 3}); 25 | edgeList.add(new int[]{3, 4}); 26 | edgeList.add(new int[]{4, 5}); 27 | edgeList.add(new int[]{1, 6}); 28 | 29 | MyBFS bfs = new MyBFS(); 30 | ArrayList visitedNodeList = bfs.run(vertexList,edgeList, 0); 31 | System.out.println(visitedNodeList.toString()); 32 | 33 | } 34 | 35 | private ArrayList run(ArrayList vertexList, ArrayList edgeList, int n) { 36 | ArrayList visitedList = new ArrayList<>(); 37 | myQueue queue = new myQueue(); 38 | queue.enqueue(n); 39 | 40 | ArrayList[] adjacencyList = new ArrayList[vertexList.size()]; 41 | for(int i=0; i(); 43 | } 44 | 45 | for(int[] edge : edgeList){ 46 | adjacencyList[edge[0]].add(edge[1]); 47 | } 48 | 49 | int current; 50 | while(!queue.isEmpty()) { 51 | current = queue.dequeue(); 52 | for (int neighbor : adjacencyList[current]) { 53 | if(!visitedList.contains(neighbor)){ 54 | queue.enqueue(neighbor); 55 | } 56 | } 57 | visitedList.add(current); 58 | } 59 | return visitedList; 60 | } 61 | } 62 | 63 | class myQueue { 64 | ArrayList list = new ArrayList(); 65 | 66 | public void enqueue(int n){ 67 | list.add(n); 68 | } 69 | 70 | public int dequeue(){ 71 | return list.remove(0); 72 | } 73 | 74 | public boolean isEmpty(){ 75 | return list.isEmpty(); 76 | } 77 | } -------------------------------------------------------------------------------- /leetcode/src/addTwoNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Minsuk_Heo on 12/17/2016. 3 | * https://leetcode.com/problems/add-two-numbers/ 4 | * You are given two linked lists representing two non-negative numbers. 5 | * The digits are stored in reverse order and each of their nodes contain a single digit. 6 | * Add the two numbers and return it as a linked list. 7 | * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 8 | * Output: 7 -> 0 -> 8 9 | */ 10 | public class addTwoNumbers { 11 | public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { 12 | int carry = 0; 13 | ListNode head = new ListNode(0); 14 | ListNode result = head; 15 | 16 | // when two number still available 17 | while (l1 != null && l2 != null) { 18 | head.next = new ListNode((l1.val + l2.val + carry) % 10); 19 | head = head.next; 20 | carry = (l1.val + l2.val + carry) / 10; 21 | l1 = l1.next; 22 | l2 = l2.next; 23 | } 24 | 25 | // when l2 is done 26 | while (l1 != null) { 27 | head.next = new ListNode( (l1.val + carry) % 10 ); 28 | carry = (l1.val + carry) / 10; 29 | head = head.next; 30 | l1 = l1.next; 31 | } 32 | 33 | // when l1 is done 34 | while (l2 != null) { 35 | head.next = new ListNode( (l2.val + carry) % 10 ); 36 | carry = (l2.val + carry) / 10; 37 | head = head.next; 38 | l2 = l2.next; 39 | } 40 | 41 | // when carry has value 42 | if(carry != 0) { 43 | head.next = new ListNode(carry); 44 | carry = 0; 45 | } 46 | 47 | // abandon first value of result which is garbage 48 | return result.next; 49 | } 50 | 51 | public static void main(String [] args) { 52 | ListNode l1 = new ListNode(2); 53 | l1.next = new ListNode(4); 54 | l1.next.next = new ListNode(3); 55 | 56 | ListNode l2 = new ListNode(5); 57 | l2.next = new ListNode(6); 58 | l2.next.next = new ListNode(4); 59 | 60 | ListNode result = addTwoNumbers(l1, l2); 61 | while(result != null) { 62 | System.out.println(result.val); 63 | result = result.next; 64 | } 65 | } 66 | } 67 | 68 | class ListNode { 69 | int val; 70 | ListNode next; 71 | ListNode(int x) {val = x;} 72 | } -------------------------------------------------------------------------------- /javaSolution/src/Sorts/MyQuickSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | import java.util.Arrays; 3 | 4 | /** 5 | * Created by Minsuk_Heo on 1/3/2017. 6 | */ 7 | public class MyQuickSort { 8 | public static void main(String[] args) { 9 | int[] arr = {4,5,1,3,8,6,9,7,2}; 10 | MyQuickSort qsort = new MyQuickSort(); 11 | qsort.sort(arr); 12 | System.out.println(Arrays.toString(arr)); 13 | } 14 | 15 | public void sort(int[] arr) { 16 | quicksort(arr, 0, arr.length-1); 17 | } 18 | 19 | private void quicksort(int[] arr, int start, int end) { 20 | // repeat until sublist has one item 21 | // because the algorithm is using in-place space, we can not use len(list) instead we use start, end for sublist 22 | if(start < end) { 23 | // get pivot using partition method 24 | int pivot = partition(arr, start, end); 25 | // recurse quick sort left side from pivot 26 | quicksort(arr, start, pivot-1); 27 | // recurse quick sort right side from pivot 28 | quicksort(arr,pivot+1, end); 29 | } 30 | } 31 | 32 | private int partition(int[] arr, int start, int end) { 33 | // use end item as initial pivot 34 | int pivot = end; 35 | // use start as initial wall index 36 | int wall = start; 37 | int left = start; 38 | // repeat until left item hit the end of list 39 | while (left < pivot) { 40 | // if left item is smaller than pivot, swap left item with wall and move wall to right 41 | // this will ensure items smaller than pivot stay left side from the wall and 42 | // the items greater than pivot stay right side from the wall 43 | if (arr[left] < arr[pivot]) { 44 | swap(arr, wall, left); 45 | wall = wall + 1; 46 | } 47 | left = left + 1; 48 | } 49 | 50 | // when left hit the end of list, swap pivot with wall 51 | swap(arr, wall, pivot); 52 | // now left side of wall are the items smaller than wall 53 | // now right side of pivot are the items greater than wall 54 | // wall is the new pivot 55 | pivot = wall; 56 | return pivot; 57 | } 58 | 59 | private void swap(int[] arr, int i,int j){ 60 | int tmp = arr[i]; 61 | arr[i] = arr[j]; 62 | arr[j] = tmp; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Craking the Coding Interview/3.3_set_of_stacks.py: -------------------------------------------------------------------------------- 1 | """ 2 | set of stacks 3 | push and pop 4 | when stack is full, add one more stack and push to added stack 5 | when stack is empty, remove empty stack and use previous stack. 6 | . 7 | """ 8 | import unittest 9 | 10 | class Stack: 11 | def __init__(self): 12 | self.items = [] 13 | self.max = 3 14 | 15 | def push(self, item): 16 | self.items.append(item) 17 | 18 | def pop(self): 19 | self.items.pop() 20 | 21 | def print_stack(self): 22 | print(self.items) 23 | 24 | def peek(self): 25 | return self.items[len(self.items) - 1] 26 | 27 | def is_empty(self): 28 | return self.items == [] 29 | 30 | def size(self): 31 | return len(self.items) 32 | 33 | class Stacks(): 34 | def __init__(self): 35 | self.stacklist = [] 36 | self.max_stack_size = 3 37 | #initialize first stack in stack list 38 | self.stacklist.append(Stack()) 39 | 40 | def push(self, item): 41 | st = self.getLastStack(); 42 | if self.max_stack_size == st.size(): 43 | new_st = Stack() 44 | new_st.push(item) 45 | self.stacklist.append(new_st) 46 | else: 47 | st.push(item) 48 | 49 | def pop(self): 50 | st = self.getLastStack(); 51 | if st.is_empty(): 52 | self.stacklist.pop() 53 | st = self.getLastStack(); 54 | st.pop() 55 | else: 56 | st.pop() 57 | 58 | def getLastStack(self): 59 | return self.stacklist[len(self.stacklist)-1] 60 | 61 | def getStacksCount(self): 62 | return len(self.stacklist) 63 | 64 | def printStacks(self): 65 | result = [] 66 | for st in self.stacklist: 67 | for item in st.items: 68 | result.append(item) 69 | return result 70 | 71 | class test(unittest.TestCase): 72 | def test(self): 73 | stacks = Stacks() 74 | stacks.push(5) 75 | stacks.push(3) 76 | stacks.push(2) 77 | stacks.push(7) 78 | self.assertEqual([5, 3, 2, 7], stacks.printStacks()) 79 | self.assertEqual(2, stacks.getStacksCount()) 80 | stacks.pop() 81 | self.assertEqual([5, 3, 2], stacks.printStacks()) 82 | stacks.pop() 83 | self.assertEqual([5, 3], stacks.printStacks()) 84 | self.assertEqual(1, stacks.getStacksCount()) 85 | 86 | -------------------------------------------------------------------------------- /data_structure/LinkedList.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | """ 3 | Linked List 4 | """ 5 | import unittest 6 | 7 | class Node: 8 | def __init__(self, item): 9 | self.val = item 10 | self.next = None 11 | 12 | class LinkedList: 13 | def __init__(self, item): 14 | self.head = Node(item) 15 | 16 | def add(self, item): 17 | cur = self.head 18 | while cur.next is not None: 19 | cur = cur.next 20 | cur.next = Node(item) 21 | 22 | def remove(self, item): 23 | if self.head.val == item: 24 | self.head = self.head.next 25 | else: 26 | cur = self.head 27 | while cur.next is not None: 28 | if cur.val == item: 29 | self.removeItem(item) 30 | return 31 | cur = cur.next 32 | print("item does not exist in linked list") 33 | 34 | def removeItem(self, item): 35 | cur = self.head 36 | while cur.next is not None: 37 | if cur.next.val == item: 38 | nextnode = cur.next.next 39 | cur.next = nextnode 40 | break 41 | 42 | def reverse(self): 43 | prev = None 44 | cur = self.head 45 | while cur is not None: 46 | next = cur.next 47 | cur.next = prev 48 | prev = cur 49 | cur = next 50 | self.head = prev 51 | 52 | def printlist(self): 53 | cur = self.head 54 | while cur is not None: 55 | print(cur.val) 56 | cur = cur.next 57 | 58 | 59 | class LinkedListTest(unittest.TestCase): 60 | def test(self): 61 | ll = LinkedList(3) 62 | self.assertEqual(ll.head.val, 3) 63 | ll.add(4) 64 | self.assertEqual(ll.head.next.val, 4) 65 | ll.add(5) 66 | self.assertEqual(ll.head.next.next.val, 5) 67 | ll.remove(3) 68 | self.assertEqual(ll.head.val, 4) 69 | ll.remove(4) 70 | self.assertEqual(ll.head.val, 5) 71 | ll.add(6) 72 | self.assertEqual(ll.head.next.val, 6) 73 | ll.add(7) 74 | self.assertEqual(ll.head.next.next.val, 7) 75 | ll.printlist() 76 | ll.remove(6) 77 | self.assertEqual(ll.head.next.val, 7) 78 | 79 | ll2 = LinkedList(9) 80 | ll2.add(8) 81 | ll2.add(7) 82 | ll2.reverse() 83 | self.assertEqual(ll2.head.val, 7) 84 | self.assertEqual(ll2.head.next.val, 8) 85 | 86 | -------------------------------------------------------------------------------- /sort/HeapSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Minsuk Heo' 2 | #======================================================================= 3 | # Title: Heapsort 4 | # 5 | # Statement: 6 | # Given a disordered list of integers (or any other items), 7 | # rearrange the integers in natural order. 8 | # 9 | # Sample Input: [8,5,3,1,9,6,0,7,4,2,5] 10 | # Sample Output: [0,1,2,3,4,5,5,6,7,8,9] 11 | # 12 | # Time Complexity of Solution: 13 | # Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)). 14 | # 15 | # Approach: 16 | # Heap sort happens in two phases. In the first phase, the array 17 | # is transformed into a heap. A heap is a binary tree where 18 | # 1) each node is greater than each of its children 19 | # 2) the tree is perfectly balanced 20 | # 3) all leaves are in the leftmost position available. 21 | # In phase two the heap is continuously reduced to a sorted array: 22 | # 1) while the heap is not empty 23 | # - remove the top of the head into an array 24 | # - fix the heap. 25 | # Heap sort was invented by John Williams not by B. R. Heap. 26 | # 27 | # MoveDown: 28 | # The movedown method checks and verifies that the structure is a heap. 29 | # 30 | # Technical Details: 31 | # A heap is based on an array just as a hashmap is based on an 32 | # array. For a heap, the children of an element n are at index 33 | # 2n+1 for the left child and 2n+2 for the right child. 34 | # 35 | # The movedown function checks that an element is greater than its 36 | # children. If not the values of element and child are swapped. The 37 | # function continues to check and swap until the element is at a 38 | # position where it is greater than its children. 39 | #======================================================================= 40 | 41 | def heapsort(a): 42 | 43 | def swap(a,i,j): 44 | tmp = a[i] 45 | a[i] = a[j] 46 | a[j] = tmp 47 | 48 | def siftdown(a, i, size): 49 | l = 2*i+1 50 | r = 2*i+2 51 | largest = i 52 | if l <= size-1 and a[l] > a[i]: 53 | largest = l 54 | if r <= size-1 and a[r] > a[largest]: 55 | largest = r 56 | if largest != i: 57 | swap(a, i, largest) 58 | siftdown(a, largest, size) 59 | 60 | def heapify(a, size): 61 | p = (size//2)-1 62 | while p>=0: 63 | siftdown(a, p, size) 64 | p -= 1 65 | 66 | size = len(a) 67 | heapify(a, size) 68 | end = size-1 69 | while(end > 0): 70 | swap(a, 0, end) 71 | siftdown(a, 0, end) 72 | end -= 1 73 | 74 | arr = [1,3,2,4,9,7] 75 | heapsort(arr) 76 | print(arr) 77 | -------------------------------------------------------------------------------- /javaSolution/src/Arrays/MyArrayTest.java: -------------------------------------------------------------------------------- 1 | package Arrays; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /** 8 | * Created by Minsuk_Heo on 12/31/2016. 9 | */ 10 | public class MyArrayTest { 11 | public static void main(String[] args) { 12 | int[] array = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; 13 | //Sort 14 | Arrays.sort(array); 15 | printArray("Sorted array", array); 16 | int index = Arrays.binarySearch(array, 2); 17 | System.out.println("Found 2 @ " + index); 18 | 19 | // reverse 20 | ArrayList arrayList = new ArrayList(); 21 | arrayList.add("A"); 22 | arrayList.add("B"); 23 | arrayList.add("C"); 24 | arrayList.add("D"); 25 | arrayList.add("E"); 26 | System.out.println(arrayList); 27 | Collections.reverse(arrayList); 28 | System.out.println(arrayList); 29 | 30 | // merge two array 31 | String[] a = {"A", "B", "C"}; 32 | String[] b = {"O", "U"}; 33 | List list = new ArrayList(Arrays.asList(a)); 34 | list.addAll(Arrays.asList(b)); 35 | Object[] c = list.toArray(); 36 | System.out.println(Arrays.toString(c)); 37 | 38 | // fill array at once 39 | int[] arr = new int[6]; 40 | Arrays.fill(arr, 100); 41 | for(int i : arr){ 42 | System.out.println(i); 43 | } 44 | 45 | // remove array item 46 | ArrayList intArr = new ArrayList(); 47 | intArr.add(0); 48 | intArr.add(1); 49 | intArr.add(300); 50 | System.out.println(intArr); 51 | intArr.remove(0); 52 | System.out.println(intArr); 53 | 54 | ArrayList stArr = new ArrayList(); 55 | stArr.add("abc"); 56 | stArr.add("efg"); 57 | System.out.println(stArr); 58 | stArr.remove("efg"); 59 | System.out.println(stArr); 60 | 61 | // compare two array 62 | int[] ary = {1,2,3,4,5,6}; 63 | int[] ary1 = {1,2,3,4,5,6}; 64 | int[] ary2 = {1,2,3,4}; 65 | System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1)); 66 | System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2)); 67 | 68 | } 69 | 70 | private static void printArray(String message, int array[]) { 71 | System.out.println(message + ": [length: " + array.length + "]"); 72 | 73 | for (int i = 0; i < array.length; i++) { 74 | if(i != 0) { 75 | System.out.print(", "); 76 | } 77 | System.out.print(array[i]); 78 | } 79 | System.out.println(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /javaSolution/src/Graphs/FindShortestPathNoWeight.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by Minsuk_Heo on 1/6/2017. 10 | */ 11 | public class FindShortestPathNoWeight { 12 | public static void main(String[] args) { 13 | FindShortestPathNoWeight solution = new FindShortestPathNoWeight(); 14 | 15 | List vertexList = new ArrayList<>(); 16 | vertexList.add(0); 17 | vertexList.add(1); 18 | vertexList.add(2); 19 | vertexList.add(3); 20 | vertexList.add(4); 21 | vertexList.add(5); 22 | vertexList.add(6); 23 | 24 | List edgeList = new ArrayList<>(); 25 | edgeList.add(new int[]{0, 1}); 26 | edgeList.add(new int[]{1, 2}); 27 | edgeList.add(new int[]{1, 3}); 28 | edgeList.add(new int[]{3, 4}); 29 | edgeList.add(new int[]{4, 5}); 30 | edgeList.add(new int[]{1, 6}); 31 | 32 | 33 | List visitedNodeList = solution.bfs(vertexList,edgeList, 1, 5); 34 | System.out.println("path is : " + visitedNodeList.toString()); 35 | System.out.println("distance is : " + visitedNodeList.size()); 36 | } 37 | 38 | private List bfs(List vertexList, List edgeList, int start, int target) { 39 | List visitedList = new ArrayList<>(); 40 | Map parentMap = new HashMap<>(); 41 | parentMap.put(start, null); 42 | myQueue1 queue = new myQueue1(); 43 | queue.enqueue(start); 44 | 45 | List[] adjacencyList = new ArrayList[vertexList.size()]; 46 | for(int i=0; i(); 48 | } 49 | 50 | for(int[] edge : edgeList){ 51 | adjacencyList[edge[0]].add(edge[1]); 52 | } 53 | 54 | int current; 55 | while(!queue.isEmpty()) { 56 | current = queue.dequeue(); 57 | for (int neighbor : adjacencyList[current]) { 58 | if(!visitedList.contains(neighbor)){ 59 | queue.enqueue(neighbor); 60 | parentMap.put(neighbor, current); 61 | if(neighbor == target) { 62 | break; 63 | } 64 | } 65 | } 66 | visitedList.add(current); 67 | } 68 | List pathToTarget = new ArrayList<>(); 69 | int cur = target; 70 | while(parentMap.get(cur) != null) { 71 | pathToTarget.add(0,parentMap.get(cur)); 72 | cur = parentMap.get(cur); 73 | } 74 | return pathToTarget; 75 | } 76 | } 77 | 78 | class myQueue1 { 79 | List list = new ArrayList(); 80 | 81 | public void enqueue(int n){ 82 | list.add(n); 83 | } 84 | 85 | public int dequeue(){ 86 | return list.remove(0); 87 | } 88 | 89 | public boolean isEmpty(){ 90 | return list.isEmpty(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Craking the Coding Interview/4.1_is_balanced_binary_tree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import math 3 | 4 | __author__ = 'Minsuk Heo' 5 | 6 | """ 7 | Binary Tree 8 | 9 | check if the Binary tree is balanced 10 | """ 11 | 12 | 13 | class Node: 14 | def __init__(self, item): 15 | self.val = item 16 | self.left = None 17 | self.right = None 18 | 19 | 20 | class BinaryTree: 21 | def __init__(self): 22 | self.head = Node(None) 23 | 24 | #test purpose lists 25 | self.preorder_list = [] 26 | self.inorder_list = [] 27 | self.postorder_list = [] 28 | 29 | def add(self, item): 30 | if self.head.val is None: 31 | self.head.val = item 32 | else: 33 | self.__add_node(self.head, item) 34 | 35 | def __add_node(self, cur, item): 36 | if cur.val >= item: 37 | if cur.left is not None: 38 | self.__add_node(cur.left, item) 39 | else: 40 | cur.left = Node(item) 41 | else: 42 | if cur.right is not None: 43 | self.__add_node(cur.right, item) 44 | else: 45 | cur.right = Node(item) 46 | 47 | def traverse(self, cur): 48 | if cur is None: 49 | return True 50 | if cur.left is not None: 51 | lDepth = self.getHeight(cur.left) 52 | else: 53 | lDepth = 0 54 | if cur.right is not None: 55 | rDepth = self.getHeight(cur.right) 56 | else: 57 | rDepth = 0 58 | 59 | heightDiff = math.fabs(lDepth - rDepth) 60 | if heightDiff > 1: 61 | return False 62 | 63 | else: 64 | return self.traverse(cur.left) and self.traverse(cur.right) 65 | 66 | def getHeight(self, node): 67 | if node is None: 68 | return 0 69 | return max(self.getHeight(node.left), self.getHeight(node.right))+1 70 | 71 | def is_balanced(self): 72 | if self.checkHeight(self.head) == -1: 73 | return False 74 | else: 75 | return True 76 | 77 | def checkHeight(self, node): 78 | if node is None: 79 | return 0 80 | 81 | # if left subtree is balanced 82 | leftHeight = self.checkHeight(node.left) 83 | if leftHeight == -1: 84 | return -1 85 | # if right subtree is balanced 86 | rightHeight = self.checkHeight(node.right) 87 | if rightHeight == -1: 88 | return -1 89 | 90 | # if current node is balanced 91 | heightDiff = leftHeight - rightHeight 92 | if abs(heightDiff) > 1: 93 | return -1 94 | else: 95 | return max(leftHeight, rightHeight) + 1 96 | 97 | 98 | class binary_tree_test(unittest.TestCase): 99 | def test(self): 100 | bt = BinaryTree() 101 | self.assertEqual(True, bt.is_balanced()) 102 | bt.add(5) 103 | self.assertEqual(True, bt.is_balanced()) 104 | bt.add(3) 105 | self.assertEqual(True, bt.is_balanced()) 106 | bt.add(1) 107 | self.assertEqual(False, bt.is_balanced()) 108 | 109 | 110 | -------------------------------------------------------------------------------- /graph/dijkstra.py: -------------------------------------------------------------------------------- 1 | # dijkstra's algorithm 2 | """ 3 | 1. Assign to every node a distance value. Set it to zero for our initial node 4 | and to infinity for all other nodes. 5 | 6 | 2. Mark all nodes as unvisited. Set initial node as current. 7 | 8 | 3. For current node, consider all its unvisited neighbors and calculate their 9 | tentative distance (from the initial node). For example, if current node 10 | (A) has distance of 6, and an edge connecting it with another node (B) 11 | is 2, the distance to B through A will be 6+2=8. If this distance is less 12 | than the previously recorded distance (infinity in the beginning, zero 13 | for the initial node), overwrite the distance. 14 | 15 | 4. When we are done considering all neighbors of the current node, mark it as 16 | visited. A visited node will not be checked ever again; its distance 17 | recorded now is final and minimal. 18 | 19 | 5. If all nodes have been visited, finish. Otherwise, set the unvisited node 20 | with the smallest distance (from the initial node) as the next "current 21 | node" and continue from step 3. 22 | 23 | - source: wikipedia http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm 24 | """ 25 | 26 | 27 | class Graph(object): 28 | """ 29 | A simple undirected, weighted graph 30 | """ 31 | 32 | def __init__(self): 33 | self.nodes = set() 34 | self.edges = {} 35 | self.distances = {} 36 | 37 | def add_node(self, value): 38 | self.nodes.add(value) 39 | 40 | def add_edge(self, from_node, to_node, distance): 41 | self._add_edge(from_node, to_node, distance) 42 | self._add_edge(to_node, from_node, distance) 43 | 44 | def _add_edge(self, from_node, to_node, distance): 45 | self.edges.setdefault(from_node, []) 46 | self.edges[from_node].append(to_node) 47 | self.distances[(from_node, to_node)] = distance 48 | 49 | 50 | def dijkstra(graph, initial_node): 51 | visited = {initial_node: 0} 52 | current_node = initial_node 53 | path = {} 54 | 55 | nodes = set(graph.nodes) 56 | 57 | while nodes: 58 | min_node = None 59 | for node in nodes: 60 | if node in visited: 61 | if min_node is None: 62 | min_node = node 63 | elif visited[node] < visited[min_node]: 64 | min_node = node 65 | 66 | if min_node is None: 67 | break 68 | 69 | nodes.remove(min_node) 70 | cur_wt = visited[min_node] 71 | 72 | for edge in graph.edges[min_node]: 73 | wt = cur_wt + graph.distances[(min_node, edge)] 74 | if edge not in visited or wt < visited[edge]: 75 | visited[edge] = wt 76 | path[edge] = min_node 77 | 78 | return visited, path 79 | 80 | 81 | def shortest_path(graph, initial_node, goal_node): 82 | distances, paths = dijkstra(graph, initial_node) 83 | route = [goal_node] 84 | 85 | while goal_node != initial_node: 86 | route.append(paths[goal_node]) 87 | goal_node = paths[goal_node] 88 | 89 | route.reverse() 90 | return route 91 | 92 | 93 | if __name__ == '__main__': 94 | g = Graph() 95 | g.nodes = set(range(1, 7)) 96 | g.add_edge(1, 2, 7) 97 | g.add_edge(1, 3, 9) 98 | g.add_edge(1, 6, 14) 99 | g.add_edge(2, 3, 10) 100 | g.add_edge(2, 4, 15) 101 | g.add_edge(3, 4, 11) 102 | g.add_edge(3, 6, 2) 103 | g.add_edge(4, 5, 6) 104 | g.add_edge(5, 6, 9) 105 | assert shortest_path(g, 1, 5) == [1, 3, 6, 5] 106 | assert shortest_path(g, 5, 1) == [5, 6, 3, 1] 107 | assert shortest_path(g, 2, 5) == [2, 3, 6, 5] 108 | assert shortest_path(g, 1, 4) == [1, 3, 4] -------------------------------------------------------------------------------- /Craking the Coding Interview/3.1_three_stacks_in_one_array.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | array has three stacks inside 5 | 6 | """ 7 | 8 | class stacks_in_array(): 9 | def __init__(self, stack_size): 10 | #create three stacks in the array and give input stack size on each stack 11 | self.array = [None] * stack_size * 3 12 | self.stack_size = stack_size 13 | 14 | self.stack1_bottom = 0 15 | self.stack1_top = self.stack1_bottom + self.stack_size 16 | 17 | self.stack2_bottom = self.stack1_top 18 | self.stack2_top = self.stack2_bottom + self.stack_size 19 | 20 | self.stack3_bottom = self.stack2_top 21 | self.stack3_top = self.stack3_bottom + self.stack_size 22 | 23 | self.stack1_idx = 0 24 | self.stack2_idx = self.stack1_idx + self.stack_size 25 | self.stack3_idx = self.stack2_idx + self.stack_size 26 | 27 | def push_stack1(self, val): 28 | if self.stack1_idx == self.stack1_top: 29 | print("stack1 is full") 30 | return False 31 | else: 32 | self.array[self.stack1_idx] = val 33 | self.stack1_idx = self.stack1_idx + 1 34 | return True 35 | 36 | def push_stack2(self, val): 37 | if self.stack2_idx == self.stack2_top: 38 | print("stack2 is full") 39 | return False 40 | else: 41 | self.array[self.stack2_idx] = val 42 | self.stack2_idx = self.stack2_idx + 1 43 | return True 44 | 45 | def push_stack3(self, val): 46 | if self.stack3_idx == self.stack3_top: 47 | print("stack3 is full") 48 | return False 49 | else: 50 | self.array[self.stack3_idx] = val 51 | self.stack3_idx = self.stack3_idx + 1 52 | return True 53 | 54 | def pop_stack1(self): 55 | if self.stack1_idx > self.stack1_bottom: 56 | self.stack1_idx = self.stack1_idx - 1 57 | self.array[self.stack1_idx] = None 58 | return True 59 | else: 60 | print("stack1 is empty") 61 | return False 62 | 63 | def pop_stack2(self): 64 | if self.stack2_idx > self.stack2_bottom: 65 | self.stack2_idx = self.stack2_idx - 1 66 | self.array[self.stack2_idx] = None 67 | return True 68 | else: 69 | print("stack1 is empty") 70 | return False 71 | 72 | def pop_stack3(self): 73 | if self.stack3_idx > self.stack3_bottom: 74 | self.stack3_idx = self.stack3_idx - 1 75 | self.array[self.stack3_idx] = None 76 | return True 77 | else: 78 | print("stack3 is empty") 79 | return False 80 | 81 | 82 | def printArray(self): 83 | return str(self.array) 84 | 85 | class stacktest(unittest.TestCase): 86 | def test(self): 87 | test_array = stacks_in_array(3) 88 | self.assertEqual("[None, None, None, None, None, None, None, None, None]", test_array.printArray()) 89 | test_array.push_stack1(1) 90 | test_array.push_stack2(1) 91 | test_array.push_stack3(1) 92 | self.assertEqual("[1, None, None, 1, None, None, 1, None, None]", test_array.printArray()) 93 | test_array.push_stack1(2) 94 | test_array.push_stack2(2) 95 | test_array.push_stack3(2) 96 | self.assertEqual("[1, 2, None, 1, 2, None, 1, 2, None]", test_array.printArray()) 97 | test_array.push_stack1(3) 98 | test_array.push_stack2(3) 99 | test_array.push_stack3(3) 100 | self.assertEqual("[1, 2, 3, 1, 2, 3, 1, 2, 3]", test_array.printArray()) 101 | 102 | self.assertFalse(test_array.push_stack1(3)) 103 | self.assertFalse(test_array.push_stack2(3)) 104 | self.assertFalse(test_array.push_stack3(3)) 105 | 106 | test_array.pop_stack1() 107 | test_array.pop_stack2() 108 | test_array.pop_stack3() 109 | self.assertEqual("[1, 2, None, 1, 2, None, 1, 2, None]", test_array.printArray()) 110 | 111 | test_array.pop_stack1() 112 | test_array.pop_stack2() 113 | test_array.pop_stack3() 114 | self.assertEqual("[1, None, None, 1, None, None, 1, None, None]", test_array.printArray()) 115 | 116 | test_array.pop_stack1() 117 | test_array.pop_stack2() 118 | test_array.pop_stack3() 119 | self.assertEqual("[None, None, None, None, None, None, None, None, None]", test_array.printArray()) 120 | 121 | self.assertFalse(test_array.pop_stack1()) 122 | self.assertFalse(test_array.pop_stack2()) 123 | self.assertFalse(test_array.pop_stack3()) 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /javaSolution/src/Graphs/Dijkstra.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import com.sun.javafx.geom.Edge; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Collections; 10 | 11 | /** 12 | * Created by Minsuk_Heo on 1/6/2017. 13 | */ 14 | public class Dijkstra { 15 | public static void main(String[] args) { 16 | Graph g = new Graph(); 17 | 18 | //add vertices 19 | g.addVertex(1); 20 | g.addVertex(2); 21 | g.addVertex(3); 22 | g.addVertex(4); 23 | g.addVertex(5); 24 | g.addVertex(6); 25 | 26 | //add edges with weight 27 | g.addEdge(1, 2, 7); 28 | g.addEdge(2, 1, 7); 29 | g.addEdge(1, 3, 9); 30 | g.addEdge(3, 1, 9); 31 | g.addEdge(1, 6, 14); 32 | g.addEdge(6, 1, 14); 33 | g.addEdge(2, 3, 10); 34 | g.addEdge(3, 2, 10); 35 | g.addEdge(2, 4, 15); 36 | g.addEdge(4, 2, 15); 37 | g.addEdge(3, 4, 11); 38 | g.addEdge(4, 3, 11); 39 | g.addEdge(3, 6, 2); 40 | g.addEdge(6, 3, 2); 41 | g.addEdge(4, 5, 6); 42 | g.addEdge(5, 4, 6); 43 | g.addEdge(5, 6, 9); 44 | g.addEdge(6, 5, 9); 45 | 46 | Dijkstra dijkstra = new Dijkstra(); 47 | dijkstra.shortestPath(g,1,4); 48 | 49 | 50 | } 51 | 52 | private void shortestPath(Graph g, int from, int to) { 53 | Map path = new HashMap(); 54 | // use first vertex as start point of dijkstra algorithm 55 | path = dijkstra(g, g.vertexList.get(0)); 56 | 57 | List route = new ArrayList(); 58 | route.add(to); 59 | 60 | while(to != from) { 61 | route.add(path.get(to)); 62 | to = path.get(to); 63 | } 64 | 65 | //reverse 66 | Collections.reverse(route); 67 | System.out.println(route); 68 | } 69 | 70 | private Map dijkstra(Graph g, Integer start) { 71 | Map visitedVertex = new HashMap(); 72 | visitedVertex.put(start, 0); 73 | Map path = new HashMap(); 74 | 75 | while(g.vertexList.size() > 0){ 76 | //suppose vertex should be > -1 77 | int minVertex = -1; 78 | for(int vertex : g.vertexList){ 79 | if(visitedVertex.containsKey(vertex)){ 80 | if(minVertex == -1){ 81 | minVertex = vertex; 82 | } 83 | else if(visitedVertex.get(vertex) < visitedVertex.get(minVertex)){ 84 | minVertex = vertex; 85 | } 86 | } 87 | } 88 | if(minVertex == -1){ 89 | break; 90 | } 91 | 92 | for(int i=0;i adjacencyVertice = g.adjacencyList.get(minVertex); 100 | 101 | for(int vertex : adjacencyVertice){ 102 | int weight = curWeight + g.weightOnEdge.get(Integer.toString(minVertex)+","+Integer.toString(vertex)); 103 | if(!visitedVertex.containsKey(vertex) || weight < visitedVertex.get(vertex)){ 104 | visitedVertex.put(vertex, weight); 105 | path.put(vertex, minVertex); 106 | } 107 | } 108 | } 109 | 110 | return path; 111 | } 112 | } 113 | 114 | class Graph{ 115 | public List vertexList = new ArrayList(); 116 | public Map adjacencyList = new HashMap(); 117 | public Map weightOnEdge = new HashMap(); 118 | 119 | public void addVertex(int i) { 120 | vertexList.add(i); 121 | } 122 | 123 | public void addEdge(int from, int to, int weight) { 124 | if(adjacencyList.containsKey(from)){ 125 | // update adjacencyList 126 | adjacencyList.get(from).add(to); 127 | weightOnEdge.put(Integer.toString(from)+","+Integer.toString(to), weight); 128 | } 129 | else { 130 | List vertexList = new ArrayList(); 131 | vertexList.add(to); 132 | // add vertex in adjacencyList 133 | adjacencyList.put(from, vertexList); 134 | // store weight on edge 135 | weightOnEdge.put(Integer.toString(from)+","+Integer.toString(to), weight); 136 | } 137 | 138 | } 139 | } 140 | 141 | -------------------------------------------------------------------------------- /javaSolution/src/data_structure/myBST.java: -------------------------------------------------------------------------------- 1 | package data_structure; 2 | 3 | /** 4 | * Created by Minsuk_Heo on 1/1/2017. 5 | */ 6 | public class myBST { 7 | treeNode head; 8 | 9 | public void insert(int n){ 10 | if (head == null) { 11 | head = new treeNode(n); 12 | } else { 13 | insertNode(head, n); 14 | } 15 | } 16 | 17 | private void insertNode(treeNode cur, int n){ 18 | if (cur.val > n) { 19 | if(cur.left == null){ 20 | cur.left = new treeNode(n); 21 | } else { 22 | insertNode(cur.left, n); 23 | } 24 | } else { 25 | if(cur.right == null){ 26 | cur.right = new treeNode(n); 27 | } else { 28 | insertNode(cur.right, n); 29 | } 30 | } 31 | } 32 | 33 | public void remove(int n){ 34 | // if head is the value 35 | if(head.val == n) { 36 | if(head.left != null && head.right == null) { 37 | head = head.left; 38 | } 39 | else if (head.left == null && head.right != null) { 40 | head = head.right; 41 | } 42 | else if (head.left != null && head.right != null) { 43 | head.val = getMostLeftChild(head.right).val; 44 | removeMostLeftChild(head, head.right); 45 | } 46 | // head has no children 47 | else{ 48 | head = null; 49 | } 50 | } 51 | // else, find the value using binary search and remove 52 | else { 53 | if(head.val > n) { 54 | removeItem(head, head.left, n); 55 | } 56 | else{ 57 | removeItem(head, head.right, n); 58 | } 59 | } 60 | } 61 | 62 | private void removeMostLeftChild(treeNode parent, treeNode cur) { 63 | if(cur.left != null) { 64 | removeMostLeftChild(cur, cur.left); 65 | } else { 66 | // if most left item is the head's right child, just remove right child 67 | if(parent == head) { 68 | parent.right = null; 69 | } else { 70 | parent.left = null; 71 | } 72 | } 73 | } 74 | 75 | private void removeItem(treeNode parent, treeNode cur, int n){ 76 | if(cur.val == n ) { 77 | if(cur.left != null && cur.right == null) { 78 | if(parent.val > n) { 79 | parent.left = cur.left; 80 | } 81 | else { 82 | parent.right = cur.left; 83 | } 84 | } 85 | else if (cur.left == null && cur.right != null) { 86 | if(parent.val > n) { 87 | parent.left = cur.right; 88 | } 89 | else { 90 | parent.right = cur.right; 91 | } 92 | } 93 | else if (cur.left != null && cur.right != null) { 94 | cur.val = getMostLeftChild(cur.right).val; 95 | removeMostLeftChild(cur, cur.right); 96 | } 97 | // head has no children 98 | else{ 99 | if(parent.val > n) { 100 | parent.left = null; 101 | } 102 | else { 103 | parent.right = null; 104 | } 105 | } 106 | } 107 | else { 108 | if(cur.val > n) { 109 | removeItem(cur, cur.left, n); 110 | } 111 | else{ 112 | removeItem(cur, cur.right, n); 113 | } 114 | } 115 | } 116 | 117 | private treeNode getMostLeftChild(treeNode cur) { 118 | if(cur.left != null) { 119 | return getMostLeftChild(cur.left); 120 | } else { 121 | return cur; 122 | } 123 | } 124 | 125 | public void inorder() { 126 | inorderTraverse(head); 127 | } 128 | 129 | private void inorderTraverse(treeNode cur){ 130 | if(cur != null){ 131 | inorderTraverse(cur.left); 132 | System.out.println(cur.val); 133 | inorderTraverse(cur.right); 134 | } 135 | } 136 | 137 | public static void main(String[] args) { 138 | myBST bst = new myBST(); 139 | bst.insert(7); 140 | bst.insert(5); 141 | bst.insert(15); 142 | bst.insert(14); 143 | bst.insert(17); 144 | bst.insert(16); 145 | //bst.inorder(); 146 | bst.remove(15); 147 | bst.inorder(); 148 | } 149 | } 150 | 151 | class treeNode{ 152 | int val; 153 | treeNode left; 154 | treeNode right; 155 | 156 | public treeNode(int n){ 157 | val = n; 158 | left = null; 159 | right = null; 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /data_structure/BinaryTree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | __author__ = 'Minsuk Heo' 4 | 5 | """ 6 | Binary Tree 7 | 8 | remove : 9 | 1) Node to be removed has no children. 10 | This case is quite simple. Algorithm sets corresponding link of the parent to NULL and disposes the node. 11 | 2) Node to be removed has one child. 12 | It this case, node is cut from the tree and algorithm links single child (with it's subtree) directly to the parent of the removed node. 13 | 3) Node to be removed has two children. 14 | (1) find a minimum value in the right subtree; 15 | (2) replace value of the node to be removed with found minimum. Now, right subtree contains a duplicate! 16 | (3) apply remove to the right subtree to remove a duplicate. 17 | """ 18 | 19 | 20 | class Node: 21 | def __init__(self, item): 22 | self.val = item 23 | self.left = None 24 | self.right = None 25 | 26 | 27 | class BinaryTree: 28 | def __init__(self): 29 | self.head = Node(None) 30 | 31 | #test purpose lists 32 | self.preorder_list = [] 33 | self.inorder_list = [] 34 | self.postorder_list = [] 35 | 36 | def search(self, item): 37 | if self.head.val is None: 38 | return False 39 | else: 40 | return self.__search_node(self.head, item) 41 | 42 | def __search_node(self, cur, item): 43 | if cur.val == item: 44 | return True 45 | else: 46 | if cur.val >= item: 47 | if cur.left is not None: 48 | return self.__search_node(cur.left, item) 49 | else: 50 | return False 51 | else: 52 | if cur.right is not None: 53 | return self.__search_node(cur.right, item) 54 | else: 55 | return False 56 | 57 | def add(self, item): 58 | if self.head.val is None: 59 | self.head.val = item 60 | else: 61 | self.__add_node(self.head, item) 62 | 63 | def __add_node(self, cur, item): 64 | if cur.val >= item: 65 | if cur.left is not None: 66 | self.__add_node(cur.left, item) 67 | else: 68 | cur.left = Node(item) 69 | else: 70 | if cur.right is not None: 71 | self.__add_node(cur.right, item) 72 | else: 73 | cur.right = Node(item) 74 | 75 | def remove(self, item): 76 | if self.head.val is None: 77 | print ("there is no item: in BST", item) 78 | if self.head.val == item: 79 | # 1) Node to be removed has no children. 80 | if self.head.left is None and self.head.right is None: 81 | self.head = None 82 | # 2) Node to be removed has one child. 83 | elif self.head.left is None and self.head.right is not None: 84 | self.head = self.head.right 85 | # 3) Node to be removed has one child. 86 | elif self.head.left is not None and self.head.right is None: 87 | self.head = self.head.left 88 | # 4) Node to be removed has two children. 89 | else: 90 | self.head.val = self.__most_left_val_from_right_node(self.head.right).val 91 | self.__removeitem(self.head, self.head.right, self.head.val) 92 | else: 93 | if self.head.val > item: 94 | self.__remove(self.head, self.head.left, item) 95 | else: 96 | self.__remove(self.head, self.head.right, item) 97 | 98 | def __remove(self, parent, cur, item): 99 | if cur is None: 100 | print ("There is no item: ", item) 101 | if cur.val == item: 102 | # 1) Node to be removed has no children. 103 | if cur.left is None and cur.right is None: 104 | if parent.left == cur: 105 | parent.left = None 106 | else: 107 | parent.right = None 108 | # 2) Node to be removed has one child. 109 | elif cur.left is None and cur.right is not None: 110 | if parent.left == cur: 111 | parent.left = cur.right 112 | else: 113 | parent.right = cur.right 114 | # 3) Node to be removed has one child. 115 | elif cur.left is not None and cur.right is None: 116 | if parent.left == cur: 117 | parent.left = cur.left 118 | else: 119 | parent.right = cur.left 120 | # 4) Node to be removed has two children. 121 | else: 122 | cur.val = self.__most_left_val_from_right_node(cur.right).val 123 | self.__removeitem(cur, cur.right, cur.val) 124 | 125 | 126 | def __most_left_val_from_right_node(self, cur): 127 | if cur.left is None: 128 | return cur 129 | else: 130 | return self.__most_left_val_from_right_node(cur.left) 131 | 132 | def __removeitem(self, parent, cur, item): 133 | if cur.val == item: 134 | if parent.left == cur: 135 | parent.left = None 136 | else: 137 | parent.right = None 138 | else: 139 | if cur.val > item: 140 | self.__removeitem(cur, cur.left, item) 141 | else: 142 | self.__removeitem(cur, cur.right, item) 143 | 144 | def preorder_traverse(self): 145 | if self.head is not None: 146 | self.__preorder(self.head) 147 | 148 | def __preorder(self, cur): 149 | self.preorder_list.append(cur.val) 150 | print (cur.val) 151 | if cur.left is not None: 152 | self.__preorder(cur.left) 153 | if cur.right is not None: 154 | self.__preorder(cur.right) 155 | 156 | def inorder_traverse(self): 157 | if self.head is not None: 158 | self.__inorder(self.head) 159 | 160 | def __inorder(self, cur): 161 | if cur.left is not None: 162 | self.__inorder(cur.left) 163 | 164 | self.inorder_list.append(cur.val) 165 | print (cur.val) 166 | 167 | if cur.right is not None: 168 | self.__inorder(cur.right) 169 | 170 | def postorder_traverse(self): 171 | if self.head is not None: 172 | self.__postorder(self.head) 173 | 174 | def __postorder(self, cur): 175 | if cur.left is not None: 176 | self.__postorder(cur.left) 177 | 178 | if cur.right is not None: 179 | self.__postorder(cur.right) 180 | 181 | self.postorder_list.append(cur.val) 182 | print (cur.val) 183 | 184 | 185 | class binary_tree_test(unittest.TestCase): 186 | def test(self): 187 | bt = BinaryTree() 188 | bt.add(5) 189 | bt.add(3) 190 | bt.add(4) 191 | bt.add(1) 192 | bt.add(7) 193 | print("pre order") 194 | bt.preorder_traverse() 195 | self.assertEqual(bt.preorder_list, [5,3,1,4,7]) 196 | 197 | print("in order") 198 | bt.inorder_traverse() 199 | self.assertEqual(bt.inorder_list, [1,3,4,5,7]) 200 | 201 | print("post order") 202 | bt.postorder_traverse() 203 | self.assertEqual(bt.postorder_list, [1,4,3,7,5]) 204 | 205 | print ("bt root remove") 206 | bt_root_remove_test = BinaryTree() 207 | bt_root_remove_test.add(60) 208 | bt_root_remove_test.add(50) 209 | bt_root_remove_test.add(70) 210 | bt_root_remove_test.remove(60) 211 | bt_root_remove_test.preorder_traverse() 212 | self.assertEqual(bt_root_remove_test.preorder_list, [70,50]) 213 | 214 | print ("bt root remove2") 215 | bt_root_remove_test = BinaryTree() 216 | bt_root_remove_test.add(60) 217 | bt_root_remove_test.add(50) 218 | bt_root_remove_test.remove(60) 219 | bt_root_remove_test.preorder_traverse() 220 | self.assertEqual(bt_root_remove_test.preorder_list, [50]) 221 | 222 | print ("bt root remove3") 223 | bt_root_remove_test = BinaryTree() 224 | bt_root_remove_test.add(60) 225 | bt_root_remove_test.add(70) 226 | bt_root_remove_test.remove(60) 227 | bt_root_remove_test.preorder_traverse() 228 | self.assertEqual(bt_root_remove_test.preorder_list, [70]) 229 | 230 | print ("bt left remove 1") 231 | bt_left_remove_test_1 = BinaryTree() 232 | bt_left_remove_test_1.add(60) 233 | bt_left_remove_test_1.add(50) 234 | bt_left_remove_test_1.add(70) 235 | bt_left_remove_test_1.remove(50) 236 | bt_left_remove_test_1.preorder_traverse() 237 | self.assertEqual(bt_left_remove_test_1.preorder_list, [60,70]) 238 | 239 | print ("bt left remove 2") 240 | bt_left_remove_test_2_left = BinaryTree() 241 | bt_left_remove_test_2_left.add(60) 242 | bt_left_remove_test_2_left.add(50) 243 | bt_left_remove_test_2_left.add(70) 244 | bt_left_remove_test_2_left.add(40) 245 | bt_left_remove_test_2_left.remove(50) 246 | bt_left_remove_test_2_left.preorder_traverse() 247 | self.assertEqual(bt_left_remove_test_2_left.preorder_list, [60,40,70]) 248 | 249 | print ("bt right remove 2") 250 | bt_left_remove_test_2_right = BinaryTree() 251 | bt_left_remove_test_2_right.add(60) 252 | bt_left_remove_test_2_right.add(50) 253 | bt_left_remove_test_2_right.add(70) 254 | bt_left_remove_test_2_right.add(55) 255 | bt_left_remove_test_2_right.remove(50) 256 | bt_left_remove_test_2_right.preorder_traverse() 257 | self.assertEqual(bt_left_remove_test_2_right.preorder_list, [60,55,70]) 258 | 259 | print ("bt right remove 1") 260 | bt_right_remove_test_1 = BinaryTree() 261 | bt_right_remove_test_1.add(60) 262 | bt_right_remove_test_1.add(50) 263 | bt_right_remove_test_1.add(70) 264 | bt_right_remove_test_1.remove(70) 265 | bt_right_remove_test_1.preorder_traverse() 266 | self.assertEqual(bt_right_remove_test_1.preorder_list, [60,50]) 267 | 268 | print ("bt right remove 2") 269 | bt_right_remove_test_2_left = BinaryTree() 270 | bt_right_remove_test_2_left.add(60) 271 | bt_right_remove_test_2_left.add(50) 272 | bt_right_remove_test_2_left.add(70) 273 | bt_right_remove_test_2_left.add(65) 274 | bt_right_remove_test_2_left.remove(70) 275 | bt_right_remove_test_2_left.preorder_traverse() 276 | self.assertEqual(bt_right_remove_test_2_left.preorder_list, [60,50,65]) 277 | 278 | print ("bt right remove 2") 279 | bt_right_remove_test_2_right = BinaryTree() 280 | bt_right_remove_test_2_right.add(60) 281 | bt_right_remove_test_2_right.add(50) 282 | bt_right_remove_test_2_right.add(70) 283 | bt_right_remove_test_2_right.add(75) 284 | bt_right_remove_test_2_right.remove(70) 285 | bt_right_remove_test_2_right.preorder_traverse() 286 | self.assertEqual(bt_right_remove_test_2_right.preorder_list, [60,50,75]) 287 | 288 | print ("bt left remove 3") 289 | bt_left_remove_test_3 = BinaryTree() 290 | bt_left_remove_test_3.add(60) 291 | bt_left_remove_test_3.add(50) 292 | bt_left_remove_test_3.add(70) 293 | bt_left_remove_test_3.add(40) 294 | bt_left_remove_test_3.add(55) 295 | bt_left_remove_test_3.add(52) 296 | bt_left_remove_test_3.remove(50) 297 | bt_left_remove_test_3.preorder_traverse() 298 | self.assertEqual(bt_left_remove_test_3.preorder_list, [60,52,40,55,70]) 299 | 300 | print("BST search test") 301 | bt_search_test = BinaryTree() 302 | bt_search_test.add(60) 303 | bt_search_test.add(50) 304 | bt_search_test.add(70) 305 | bt_search_test.add(40) 306 | bt_search_test.add(55) 307 | bt_search_test.add(52) 308 | self.assertTrue(bt_search_test.search(60)) 309 | self.assertTrue(bt_search_test.search(50)) 310 | self.assertTrue(bt_search_test.search(70)) 311 | self.assertTrue(bt_search_test.search(40)) 312 | self.assertTrue(bt_search_test.search(55)) 313 | self.assertTrue(bt_search_test.search(52)) 314 | self.assertFalse(bt_search_test.search(61)) 315 | self.assertFalse(bt_search_test.search(81)) 316 | 317 | 318 | -------------------------------------------------------------------------------- /coding_interview_2018/.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 126 | 127 | 128 | 129 | input 130 | 131 | 132 | arr 133 | 134 | 135 | 136 | 161 | 162 | 163 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 191 | 192 | 195 | 196 | 199 | 200 | 201 | 202 | 205 | 206 | 209 | 210 | 213 | 214 | 215 | 216 | 219 | 220 | 223 | 224 | 227 | 228 | 229 | 230 | 233 | 234 | 237 | 238 | 241 | 242 | 243 | 244 | 247 | 248 | 251 | 252 | 255 | 256 | 257 | 258 | 261 | 262 | 265 | 266 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 296 | 297 | 313 | 314 | 330 | 331 | 347 | 348 | 364 | 365 | 381 | 382 | 393 | 394 | 412 | 413 | 431 | 432 | 452 | 453 | 474 | 475 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 518 | 519 | 520 | 521 | 1524802481822 522 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | --------------------------------------------------------------------------------