├── general-purpose-algorithm ├── 1_sorting │ ├── bubble_sort │ │ ├── README.md │ │ └── python │ │ │ └── bubble_sort.py │ ├── merge_sort │ │ ├── README.md │ │ └── python │ │ │ └── merge_sort.py │ ├── heap_sort │ │ ├── README.md │ │ └── python │ │ │ ├── min_heap_sort.py │ │ │ └── max_heap_sort.py │ ├── quick_sort │ │ ├── README.md │ │ └── python │ │ │ └── quick_sort.py │ ├── insertion_sort │ │ ├── README.md │ │ └── python │ │ │ └── insertion_sort.py │ ├── README.md │ └── selection_sort │ │ ├── README.md │ │ └── python │ │ └── selection_sort.py ├── 2_data_structure │ ├── link_lists │ │ └── single_linked_list │ │ │ ├── README.md │ │ │ └── remove_kth_from_end.py │ ├── stack │ │ ├── check_balanced_brackets │ │ │ ├── README.md │ │ │ └── python │ │ │ │ └── balanced_bracket.py │ │ ├── README.md │ │ └── python │ │ │ └── min_max_stack.py │ └── heap │ │ ├── README.md │ │ ├── find_median │ │ ├── README.md │ │ └── python │ │ │ └── find_median.py │ │ └── min_max_heap │ │ └── python │ │ └── heap.py ├── .DS_Store └── KMP-algorithm │ ├── .DS_Store │ ├── kmp-algorithm-java │ ├── KMP.code-workspace │ ├── bin │ │ └── app │ │ │ └── App.class │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── src │ │ └── app │ │ └── App.java │ └── README.md ├── .DS_Store ├── .gitattributes ├── funny-topic ├── .DS_Store └── making RNG │ ├── question.md │ ├── making_RNG.py │ └── description.md ├── interview-challenges ├── mathmatical │ ├── Monte-Carlo-Pi │ │ ├── README.md │ │ ├── python │ │ │ └── monte-carlo-pi.py │ │ └── analysis.md │ └── powersets │ │ ├── python │ │ └── powersets.py │ │ └── description.md ├── recursive │ └── quick-int-exp-calc │ │ ├── README.md │ │ ├── analysis.md │ │ └── python │ │ └── quick-exp-calc.py ├── hashing │ └── add-up-to-K │ │ ├── README.md │ │ ├── python │ │ └── add-up-to-K.py │ │ └── analysis.md ├── bit_manipulation │ └── find-distinctive-digit │ │ ├── README.md │ │ ├── python │ │ └── find_distinctive_num.py │ │ └── analysis.md ├── linked_list │ ├── find_intersection │ │ └── README.md │ └── XOR_linked_list │ │ └── README.md ├── dynamic_programming │ └── max_sub_array │ │ └── README.md ├── binary_tree │ ├── unival_tree │ │ ├── README.md │ │ └── python │ │ │ └── unival_tree.py │ └── binary_tree_serializer │ │ └── README.md ├── sorting │ └── find-inversions │ │ ├── README.md │ │ ├── python │ │ └── find-inversions.py │ │ └── analysis.md ├── searching_algorithm │ ├── walk_away_from_wall │ │ └── README.md │ └── boggle_board │ │ └── python │ │ └── boggle_board.py └── string_processing │ ├── longest-unique-string │ └── python │ │ └── longest-unique-string.py │ ├── absolute_directory │ └── README.md │ ├── match_pattern │ └── python │ │ └── match_pattern.py │ └── add_underscore │ └── python │ └── add_underscore.py ├── .gitignore ├── entry_level_question └── smallest_diff │ └── python │ └── smallest_diff.py ├── README.md └── LICENSE /general-purpose-algorithm/1_sorting/bubble_sort/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/merge_sort/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/heap_sort/README.md: -------------------------------------------------------------------------------- 1 | ### Heap Sort -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/quick_sort/README.md: -------------------------------------------------------------------------------- 1 | ## Quick Sort -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/link_lists/single_linked_list/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShepherdMOZ/algorithm-handbook/HEAD/.DS_Store -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /funny-topic/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShepherdMOZ/algorithm-handbook/HEAD/funny-topic/.DS_Store -------------------------------------------------------------------------------- /general-purpose-algorithm/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShepherdMOZ/algorithm-handbook/HEAD/general-purpose-algorithm/.DS_Store -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShepherdMOZ/algorithm-handbook/HEAD/general-purpose-algorithm/KMP-algorithm/.DS_Store -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/insertion_sort/README.md: -------------------------------------------------------------------------------- 1 | ## Insertion Sort 2 | Time Complexity: Avg.O(n^2) Best.O(n) Worst.O(n^2) 3 | 4 | Stability: Stable 5 | 6 | 7 | -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/KMP.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "/Users/joshlu/Git/Algorithm Handbook" 5 | } 6 | ] 7 | } -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/bin/app/App.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShepherdMOZ/algorithm-handbook/HEAD/general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/bin/app/App.class -------------------------------------------------------------------------------- /funny-topic/making RNG/question.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). -------------------------------------------------------------------------------- /funny-topic/making RNG/making_RNG.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def rand7(): 4 | seed = random.randint(1,5) * 5 + random.randint(1,5) -5 5 | if seed < 22: 6 | return seed % 7 + 1 7 | return rand7() 8 | 9 | 10 | print(rand7()) -------------------------------------------------------------------------------- /interview-challenges/mathmatical/Monte-Carlo-Pi/README.md: -------------------------------------------------------------------------------- 1 | ## Monte Carlo Pi 2 | 3 | ### Question 4 | 5 | The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. 6 | 7 | Hint: The basic equation of a circle is x^2 + y^2 = r^2. -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 1 - Sorting 2 | ## TL;DR 3 | This chapter will cover the topics about most common sorting algorithms, including the design of the algorithm, comparing their efficiency in time and space, and a little bit discussion about the sorting stability. 4 | 5 | -------------------------------------------------------------------------------- /interview-challenges/mathmatical/powersets/python/powersets.py: -------------------------------------------------------------------------------- 1 | def get_power_sets(array): 2 | result = [[]] 3 | for x in array: 4 | for i in range(len(result)): 5 | new_set = result[i] + [x] 6 | result.append(new_set) 7 | return result 8 | 9 | print(get_power_sets([1,2,3])) -------------------------------------------------------------------------------- /interview-challenges/recursive/quick-int-exp-calc/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. 4 | 5 | Do this faster than the naive method of repeated multiplication. 6 | 7 | For example, pow(2, 10) should return 1024. -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/stack/check_balanced_brackets/README.md: -------------------------------------------------------------------------------- 1 | ### Question 2 | Given an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp = “[()]{}{[()()]()}” and false for exp = “[(])” -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | Given a long string (length = n), e.g "abcdababdcbdcabdcdbabcddab", could you find a way to determine whether a substring (length = m), e.g. "abdcd", is a matched substring in this long string? Because in the real world n could be a very large number, can you do this in O(n+m) ? -------------------------------------------------------------------------------- /interview-challenges/hashing/add-up-to-K/README.md: -------------------------------------------------------------------------------- 1 | ## Add-up-to-K 2 | 3 | This problem was recently asked by Google. 4 | 5 | Given a list of numbers and a number k, return whether any two numbers from the list add up to k. 6 | 7 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 8 | 9 | Bonus: Can you do this in one pass? -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /interview-challenges/bit_manipulation/find-distinctive-digit/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer. 3 | 4 | For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19. 5 | 6 | Do this in O(N) time and O(1) space. -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/insertion_sort/python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def insertion_sort(array:List[int]) -> List[int]: 4 | for i in range(1,len(array)): 5 | j = i 6 | while j > 0 and array[j] < array [j-1]: 7 | array[j], array[j-1] = array[j-1], array[j] 8 | j -= 1 9 | 10 | return array 11 | 12 | 13 | if __name__ == "__main__": 14 | print(insertion_sort([1,4,2,3,6])) -------------------------------------------------------------------------------- /interview-challenges/linked_list/find_intersection/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. 3 | 4 | For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. 5 | 6 | In this example, assume nodes with the same value are the exact same node objects. 7 | 8 | Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/bubble_sort/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def bubble_sort(array:List[int]) -> List[int]: 4 | for i in range(len(array)-1): 5 | for j in range(1,len(array)): 6 | if array[j] < array[j-1]: 7 | array[j-1], array[j] = array[j], array[j-1] 8 | 9 | return array 10 | 11 | 12 | if __name__ == "__main__": 13 | print(bubble_sort([5,6,1,3,2,4])) 14 | print(bubble_sort([1,2,3,4,5,6])) -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/selection_sort/README.md: -------------------------------------------------------------------------------- 1 | ## Selection Sort 2 | Time Complexity: Avg.O(n^2) Best.O(n^2) Worst.O(n^2) 3 | 4 | Stability: Unstable 5 | 6 | ### Design 7 | 8 | Repeat the following steps: 9 | 1. scan the whole array 10 | 2. find the min/max number 11 | 3. move the number to the begin/end of the array by swapping the first/last element with the min/max value 12 | 4. set the begin of scan to the first position of unsorted part of the array 13 | 14 | 15 | Until the array is in-order -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/heap/README.md: -------------------------------------------------------------------------------- 1 | ## Heap 2 | 3 | Heap is a binary tree with special character. If a binary tree is a max/min heap, in any given part in this tree, its parent node will always have a larger / smaller value than its child. 4 | 5 | The are a few standard methods for a heap class: 6 | 7 | Method | Description | Time Complexity 8 | ------:|------------:|:--------------:| 9 | build | build an heap | O(n) 10 | insert | insert an element to the heap | O(log n) 11 | update | -------------------------------------------------------------------------------- /interview-challenges/hashing/add-up-to-K/python/add-up-to-K.py: -------------------------------------------------------------------------------- 1 | from typing import Set,List 2 | 3 | def find_pairs(array:List[int], k:int) -> bool: 4 | 5 | # init an empty set to store the diff between k and array elements 6 | diff_set:Set = set() 7 | 8 | for number in array: 9 | if number in diff_set: 10 | return True 11 | diff_set.add(k-number) 12 | 13 | return False 14 | 15 | 16 | if __name__ == "__main__": 17 | print(find_pairs([10, 15, 3, 7], 17)) 18 | 19 | -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/stack/README.md: -------------------------------------------------------------------------------- 1 | ## Stack 2 | 3 | 4 | ### What is stack 5 | Just imaging the stack is a stack of boxes that containes data. If you want something in the middle of stack, you need to remove the boxes above it first. And that's what exactly the stack do in your computer's memory. 6 | 7 | A stack would have to basic operation, pop and push. Pop means remove the top of the stack. Push means put thing on the top of the stack. 8 | 9 | The stack is usually implemented by using an array. 10 | 11 | -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | kmp-algorithm 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | -------------------------------------------------------------------------------- /interview-challenges/recursive/quick-int-exp-calc/analysis.md: -------------------------------------------------------------------------------- 1 | ## Analysis 2 | 3 | When calculating the m^n, the classic way is usually muliply integer m by n times, which leads to the time complexity of O(n) 4 | 5 | But you might think, "ummmmm, what if I can divide those multipliers to a few equivalent-sized groups and multiply the results of these groups afterwards. For instance, if we do, 2^4, instead of calculating 2 * 2 * 2 * 2 = 16, can we do 2 * 2 = 4, then 4 * 4 = 16? 6 | 7 | The answer is definitely yes, by using some tricks in recursive programming. -------------------------------------------------------------------------------- /interview-challenges/bit_manipulation/find-distinctive-digit/python/find_distinctive_num.py: -------------------------------------------------------------------------------- 1 | 2 | def find_distinctive_number(array): 3 | once = 0 4 | twice = 0 5 | for number in array: 6 | twice = twice | (once & number) 7 | once = once ^ number 8 | bit_mask = ~(twice & once) 9 | once &= bit_mask 10 | twice &= bit_mask 11 | 12 | return once 13 | 14 | print(find_distinctive_number([6, 1, 3, 3, 3, 6, 6])) 15 | print(find_distinctive_number([13, 19, 13, 13])) 16 | print(find_distinctive_number([1,2,3,4,1,2,3,1,2,3])) -------------------------------------------------------------------------------- /interview-challenges/dynamic_programming/max_sub_array/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k. 4 | 5 | For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: 6 | ``` 7 | 10 = max(10, 5, 2) 8 | 7 = max(5, 2, 7) 9 | 8 = max(2, 7, 8) 10 | 8 = max(7, 8, 7) 11 | ``` 12 | Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results. You can simply print them out as you compute them. -------------------------------------------------------------------------------- /interview-challenges/linked_list/XOR_linked_list/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. 3 | 4 | If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. -------------------------------------------------------------------------------- /interview-challenges/binary_tree/unival_tree/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. 4 | 5 | Given the root to a binary tree, count the number of unival subtrees. 6 | 7 | For example, the following tree has 5 unival subtrees: 8 | ``` 9 | 0 10 | / \ 11 | 1 0 12 | / \ 13 | 1 0 14 | / \ 15 | 1 1 16 | ``` 17 | 18 | They are: 19 | ``` 20 | 1 * 3 (the three bottom child node without any further child) ; 21 | 0 (the only child node without any child); 22 | and 23 | 1 24 | / \ 25 | 1 1 26 | ``` -------------------------------------------------------------------------------- /interview-challenges/hashing/add-up-to-K/analysis.md: -------------------------------------------------------------------------------- 1 | ### Analysis 2 | 3 | To do this in O(n^2) is simple. You just need another array to save the sum of all pairs of two digits, starting from 1st and 2nd, untill (n-1)th and nth. Then we scan the sum array when new sum is added, to check if anything inside these sums equals k, 4 | 5 | But we want to get the bonus, which means doing this in linear time constrain O(n). So, we want a new data structure to store sums that we can access to any values instantly, without scanning the whole array. That is the Hashmap 6 | 7 | Luckily, both Python and Java provide built-in class to do this. -------------------------------------------------------------------------------- /interview-challenges/sorting/find-inversions/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. 4 | 5 | Given an array, count the number of inversions it has. Do this faster than O(N^2) time. 6 | 7 | You may assume each element in the array is distinct. 8 | 9 | For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. -------------------------------------------------------------------------------- /interview-challenges/mathmatical/powersets/description.md: -------------------------------------------------------------------------------- 1 | 2 | ## Question 3 | 4 | The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. 5 | 6 | For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. 7 | 8 | You may also use a list or array to represent a set. 9 | 10 | ## Analysis 11 | 12 | This is equivalent to find out the all sub sets of a given set. It is a __Combination__ type question. 13 | 14 | A pair of nested loop can solve the problem. The first loop enumerate elements in the source set, the second loop concatenate the element from first loop to all previous generated powersets. -------------------------------------------------------------------------------- /interview-challenges/binary_tree/binary_tree_serializer/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | This problem was asked by Google. 3 | 4 | Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. 5 | 6 | For example, given the following Node class 7 | ``` 8 | class Node: 9 | def __init__(self, val, left=None, right=None): 10 | self.val = val 11 | self.left = left 12 | self.right = right 13 | ``` 14 | The following test should pass: 15 | ``` 16 | node = Node('root', Node('left', Node('left.left')), Node('right')) 17 | assert deserialize(serialize(node)).left.left.val == 'left.left' 18 | ``` -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=10 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=10 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=10 12 | -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/selection_sort/python/selection_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def selection_sort(array: List[int]) -> List[int]: 4 | ''' 5 | This method will sort the pass-in array in asceding order 6 | ''' 7 | for i in range(len(array)-1): 8 | min_value = float('inf') 9 | min_position = -1 10 | for j in range(i, len(array)): 11 | if array[j] < min_value: 12 | min_value = array[j] 13 | min_position = j 14 | 15 | if min_position is not -1: 16 | array[min_position] = array[i] 17 | array[i] = min_value 18 | return array 19 | 20 | 21 | 22 | if __name__ == "__main__": 23 | print(selection_sort([3,4,2,1,6])) 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /interview-challenges/mathmatical/Monte-Carlo-Pi/python/monte-carlo-pi.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import random 3 | 4 | def monte_carlo_pi(interval: int) -> float: 5 | ''' 6 | We assume that the central point of the circle is at the origin point 7 | (0,0) of the 2D coordinates. it's radius equals 1. Also, it 8 | circumscribeds a 2x2 square 9 | ''' 10 | R:int = 1 11 | point_in_square:int = 0 12 | point_in_cicle:int = 0 13 | 14 | for i in range(interval): 15 | point_in_square += 1 16 | x:float = round(random.uniform(-R,R), 3) 17 | y:float = round(random.uniform(-R,R), 3) 18 | if pow(x,2) + pow(y,2) <= pow(R,2): 19 | point_in_cicle += 1 20 | 21 | return round(4*(point_in_cicle / point_in_square),3) 22 | 23 | if __name__ == "__main__": 24 | print(monte_carlo_pi(1200)) -------------------------------------------------------------------------------- /interview-challenges/recursive/quick-int-exp-calc/python/quick-exp-calc.py: -------------------------------------------------------------------------------- 1 | def quick_exp_calc(base: int, exponent: int) -> int: 2 | ''' 3 | Time Complexity: O(logn) 4 | Space Complexity: O(1) 5 | ''' 6 | if exponent == 0: 7 | ### anything's power of 0 is one 8 | return 1 9 | elif exponent % 2 ==0: 10 | ### if the exponent is an even number, just divide it into half, which is: 11 | ### m^(n//2) * m^(n//2) = m^n 12 | return quick_exp_calc(base, exponent//2) * quick_exp_calc(base, exponent//2) 13 | else: 14 | ### if the exponent is a odd number, you need to compensate an additional multiplier to the result, 15 | ### which is: m * m^(n//2) * m^(n//2) = m^n 16 | return base * quick_exp_calc(base, exponent//2) * quick_exp_calc(base, exponent//2) 17 | 18 | if __name__ == "__main__": 19 | print(quick_exp_calc(5,3)) -------------------------------------------------------------------------------- /interview-challenges/searching_algorithm/walk_away_from_wall/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on. 4 | 5 | Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board. 6 | 7 | For example, given the following board: 8 | ``` 9 | [[f, f, f, f], 10 | [t, t, f, t], 11 | [f, f, f, f], 12 | [f, f, f, f]] 13 | ``` 14 | and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row. -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/heap/find_median/README.md: -------------------------------------------------------------------------------- 1 | The median of a dataset of integers is the midpoint value of the dataset for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your dataset of integers in non-decreasing order, then: 2 | 3 | - If your dataset contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted dataset [1,2,3] , 2 is the median. 4 | 5 | - If your dataset contains an even number of elements, the median is the average of the two middle elements of the sorted sample. In the sorted dataset [1,2,3,4], 2.5 is the median. 6 | 7 | 8 | Given an input stream of integers, you must perform the following task for each integer: 9 | 10 | 1. Add the ith integer to a running list of integers. 11 | 2. Find the median of the updated list (i.e., for the first element through the ith element). 12 | 3. Print the list's updated median on a new line. The printed value must be a double-precision number scaled to 1 decimal place. 13 | 14 | 15 | -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/quick_sort/python/quick_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def quick_sort(array:List[int], start:int, end:int) -> None: 4 | ''' 5 | Complexity: 6 | Best: O(nlog(n)) time | O(log(n)) space 7 | Avg: O(nlog(n)) time | O(log(n)) space 8 | Worst: O(n^2) time | O(log(n)) space 9 | 10 | ''' 11 | if start >= end: 12 | return 13 | else: 14 | pivot:int = array[start] 15 | left:int = start +1 16 | right:int = end 17 | while left <= right: 18 | if array[left] > pivot and array[right] < pivot: 19 | array[left], array[right] = array[right], array[left] 20 | if array[left] <= pivot: 21 | left += 1 22 | if array[right] >= pivot: 23 | right -= 1 24 | 25 | array[start] = array[right] 26 | array[right] = pivot 27 | quick_sort(array, start, right-1) 28 | quick_sort(array, right+1, end) 29 | 30 | 31 | if __name__ == "__main__": 32 | array = [5,6,1,3,2,4,7] 33 | quick_sort(array,0,len(array)-1) 34 | print(array) -------------------------------------------------------------------------------- /interview-challenges/string_processing/longest-unique-string/python/longest-unique-string.py: -------------------------------------------------------------------------------- 1 | def longestSubstringWithoutDuplication(string): 2 | # Write your code here. 3 | start_idx = 0 4 | end_idx = 1 5 | str_slice = [] 6 | used_char = {} 7 | used_char[string[start_idx]] = start_idx 8 | while end_idx < len(string): 9 | if string[end_idx] not in used_char.keys(): 10 | used_char[string[end_idx]] = end_idx 11 | end_idx += 1 12 | else: 13 | char = string[end_idx] 14 | str_slice.append(string[start_idx: used_char[char] + 1]) 15 | start_idx = used_char[char] + 1 16 | used_char = {} 17 | used_char[string[start_idx]] = start_idx 18 | end_idx = start_idx + 1 19 | str_slice.append(string[start_idx:end_idx]) 20 | max_string = '' 21 | for string in str_slice: 22 | if len(string) > len(max_string): 23 | max_string = string 24 | 25 | return max_string 26 | 27 | if __name__ == "__main__": 28 | string = "clementisacap" 29 | longestSubstringWithoutDuplication(string) 30 | 31 | 32 | -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/stack/check_balanced_brackets/python/balanced_bracket.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict, Set 2 | 3 | class BracketStack(): 4 | 5 | def __init__(self): 6 | self.stack: List[str] = [] 7 | 8 | def pop(self): 9 | return self.stack.pop() 10 | 11 | def peek(self): 12 | if len(self.stack): 13 | return self.stack[len(self.stack) - 1] 14 | else: 15 | return None 16 | 17 | def is_empty(self): 18 | if len(self.stack): 19 | return False 20 | return True 21 | 22 | def push(self, value): 23 | BRACKET_PAIR: Dict[str,str] = {']':'[','}':'{',')':'('} 24 | if value in BRACKET_PAIR.values(): 25 | self.stack.append(value) 26 | elif value in BRACKET_PAIR.keys(): 27 | if len(self.stack) and self.peek() == BRACKET_PAIR.get(value): 28 | self.pop() 29 | else: 30 | return False 31 | 32 | def check_balance(sample:str): 33 | brackets = BracketStack() 34 | for char in sample: 35 | if brackets.push(char) is False: 36 | return False 37 | if brackets.is_empty(): 38 | return True 39 | 40 | return False 41 | 42 | 43 | if __name__ == "__main__": 44 | print(check_balance("()()()({})([{}])")) 45 | print(check_balance("{[}]")) 46 | 47 | 48 | -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/heap_sort/python/min_heap_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def build_min_heap(array: List[int]): 4 | first_parent = (len(array) -2) // 2 5 | for current_parent in reversed(range(first_parent + 1)): 6 | sift_down(current_parent, len(array)-1, array) 7 | return array 8 | 9 | def sift_down(current_parent:int, end_idx:int, array:List[int]): 10 | first_child = current_parent * 2 + 1 11 | while first_child <= end_idx: 12 | second_child = current_parent * 2 + 2 if current_parent * 2 + 2 <= end_idx else -1 13 | if second_child is not -1 and array[first_child] > array[second_child]: 14 | swap_idx = second_child 15 | else: 16 | swap_idx = first_child 17 | if array[current_parent] > array[swap_idx]: 18 | array[current_parent], array[swap_idx] = array[swap_idx], array[current_parent] 19 | current_parent = swap_idx 20 | first_child = current_parent * 2 + 1 21 | else: 22 | return 23 | 24 | def min_heap_sort(array: List[int]): 25 | build_min_heap(array) 26 | for endI in reversed(range(1,len(array))): 27 | array[0], array[endI] = array[endI], array[0] 28 | sift_down(0, endI-1, array) 29 | return array[::-1] 30 | 31 | 32 | 33 | if __name__ == "__main__": 34 | print(min_heap_sort([8,5,2,9,5,6,3])) 35 | 36 | -------------------------------------------------------------------------------- /interview-challenges/sorting/find-inversions/python/find-inversions.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple, Any 2 | 3 | def find_inversions(array: List[int]) -> List[Tuple[int,int]]: 4 | return merge_sort(array, [])[1] 5 | 6 | 7 | def merge_sort(array: List[int], inverted:List[Tuple[int,int]]) -> Tuple[List[int], List[Tuple[int,int]]]: 8 | 9 | if len(array) == 1: 10 | return array, [] 11 | else: 12 | mid_point:int = len(array) // 2 13 | left: Any = merge_sort(array[0:mid_point], inverted)[0] 14 | right: Any = merge_sort(array[mid_point:], inverted)[0] 15 | merged: List[int] = [] 16 | i:int = 0 17 | j:int = 0 18 | #print("Left is", left) 19 | #print("Right is", right) 20 | 21 | while i < len(left) and j < len(right) : 22 | if left[i] <= right[j]: 23 | ### Normal order 24 | merged.append(left[i]) 25 | i += 1 26 | else: 27 | ### Inverted order 28 | for number in left[i:]: 29 | inverted.append((number,right[j])) 30 | merged.append(right[j]) 31 | j += 1 32 | 33 | ## Append remaining part 34 | merged += left[i:] 35 | merged += right[j:] 36 | 37 | return merged, inverted 38 | 39 | 40 | if __name__ == "__main__": 41 | print(find_inversions([5,4,3,2,1])) 42 | 43 | 44 | -------------------------------------------------------------------------------- /interview-challenges/mathmatical/Monte-Carlo-Pi/analysis.md: -------------------------------------------------------------------------------- 1 | ### Anlysis 2 | 3 | Before start, let's have a look at Monte Carlo Method. 4 | 5 | This method uses random generated numbers to estimate the result within a certain mathmatical constrains or model. What it does is basically using large amount of random generated "points" to fill a constrained target area (used to represent the demanded result) as much as possible (Actually this is the integration in math). As for its name, Monte Carlo, is a place in America that is famous for gambling. You guessed it, the way that Monte Carlo method works is just like gambling. 6 | 7 | It is certainly difficult to actually calculate $\pi$. But just using Monte Carlo, we can estimate $\pi$ just using this two formulars: 8 | 9 | x^2 + y^2 = r^2 10 | 11 | S = $\pi$r ^2 12 | 13 | 14 | Now imaging that everything is sitted inside a 2D coordinate system. Firstly, we can randomly generate points (x,y) x,y $\in$ [-1.000,1.000] with 3 demical places. And than put these numbers into the first equation to find out which points actually fit. If so then we know that these points are in the circle. Once we get enough accumulation of points, we can use the count of points as an estimate of area size of circle, and then calculate (it is indeed estimate) the Pi using S = $\pi$r^2 15 | 16 | A thing to notice, since we are actually 'filling' things, the more points we can generate, the higher accuracy we can get. To get a satisfied result in this case, we need at least 1000 estimation -------------------------------------------------------------------------------- /interview-challenges/string_processing/absolute_directory/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | Suppose we represent our file system by a string in the following manner: 3 | 4 | The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: 5 | ``` 6 | dir 7 | subdir1 8 | subdir2 9 | file.ext 10 | ``` 11 | The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. 12 | 13 | The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: 14 | ``` 15 | dir 16 | subdir1 17 | file1.ext 18 | subsubdir1 19 | subdir2 20 | subsubdir2 21 | file2.ext 22 | ``` 23 | The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. 24 | 25 | We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). 26 | 27 | Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. 28 | 29 | Note: 30 | 31 | The name of a file contains at least a period and an extension. 32 | 33 | The name of a directory or sub-directory will not contain a period. -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/heap_sort/python/max_heap_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def build_heap(array:List[int]): 4 | first_parent_idx:int = (len(array) - 2) // 2 5 | for current_parent_node in reversed(range(first_parent_idx + 1)): 6 | sift_down(current_parent_node, len(array)-1, array) 7 | return array 8 | 9 | def sift_down(current_idx:int, end:int, heap:List[int]) -> None: 10 | left_child_idx:int = current_idx * 2 + 1 11 | while left_child_idx <= end: 12 | right_child_idx:int = current_idx * 2 + 2 if current_idx * 2 + 2 <= end else -1 13 | if right_child_idx != -1 and heap[right_child_idx] > heap[left_child_idx]: 14 | swap_idx:int = right_child_idx 15 | else: 16 | swap_idx = left_child_idx 17 | 18 | if heap[current_idx] < heap[swap_idx]: 19 | heap[swap_idx], heap[current_idx] = heap[current_idx], heap[swap_idx] 20 | current_idx = swap_idx 21 | left_child_idx = current_idx * 2 + 1 22 | else: 23 | return None 24 | 25 | def sift_up(current_idx:int, heap:List[int]) -> None: 26 | parent_idx:int = (current_idx - 1) // 2 27 | while parent_idx >= 0 and heap[current_idx] < heap[parent_idx]: 28 | heap[parent_idx], heap[current_idx] = heap[current_idx], heap[parent_idx] 29 | current_idx = parent_idx 30 | parent_idx = (current_idx - 1) // 2 31 | 32 | def heap_sort(array:List[int]) -> List[int]: 33 | build_heap(array) 34 | for endI in reversed(range(1,len(array))): 35 | array[0], array[endI] = array[endI], array[0] 36 | sift_down(0, endI-1, array) 37 | 38 | return array 39 | 40 | if __name__ == "__main__": 41 | print(heap_sort([8,5,2,9,5,6,3])) -------------------------------------------------------------------------------- /funny-topic/making RNG/description.md: -------------------------------------------------------------------------------- 1 | ## Analysis 2 | Think about this case, how can you generate all number from 1 to n^2, using a function that can only return each integer from 1 to n exactly once? 3 | 4 | Suppose the function is: 5 | ``` 6 | def getint(): 7 | return [1, 2, 3] 8 | ``` 9 | We can get what we want by using the offsetting calculation: 10 | ``` 11 | for x in getint(): 12 | for y in getint(): 13 | print(3 * x + y - 3) 14 | ``` 15 | 16 | What happened here? Let's look into the result [1, 2, 3, 4, 5, 6, 7, 8, 9]. You may notice that this can be evenly divide into three parts, [1, 2, 3], [4, 5, 6] and [7, 8, 9]. For [1, 2, 3], each number can be represented by 3*1 + i - 3, i = {1, 2, 3}. For [4, 5, 6], each number can be represented by 3*2 + i - 3, i = {1, 2, 3}. For [7, 8, 9], each number can be represented by 3*3 + i - 3, i = {1, 2, 3} 17 | 18 | So, we can dirive our findings, giving a set of integers from 1 to n, we can generate all integer from 1 towards n^2 using the formular n*m + i - n (The variable m represents which segment the number is located in, and the variable i represents its position in the segment) 19 | 20 | But what if I got [1,2,3] but I only need [1,2,3,4,5]. Still easy, we can achieve this by limiting the the variable m and i. So 4 and 5 is in the second segment and the position of final integer 5 is 2. So we just apply m <= 2 and i <= 2 21 | 22 | The situation is pretty similar while 1 to n is given randomly. If we have rand() = random.randint(1,5), we can get any random number from 1 to 7 by applying dice = 5*rand() + rand() -5 first, and if this dice value is not exceed 21, we can then do dice % 7 + 1 to get the random value at the range we want. Otherwise, we just re-roll dice. Well, technically if we use this method, the distribution of number between 1 to 7 is NOT perfectly even. This is beacause 7 is not a multiple of 5. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # IPython 77 | profile_default/ 78 | ipython_config.py 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | .dmypy.json 111 | dmypy.json 112 | 113 | # Pyre type checker 114 | .pyre/ 115 | .DS_Store 116 | .DS_Store 117 | -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/stack/python/min_max_stack.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict 2 | 3 | class MinMaxStack: 4 | 5 | def __init__(self): 6 | self.stack:List[int] = [] 7 | self.min_max_stack: List[Dict] = [] 8 | 9 | 10 | def pop(self): 11 | ''' 12 | Complexity: Time O(1), Space O(1) 13 | Pop the top of stack 14 | ''' 15 | self.min_max_stack.pop() 16 | return self.stack.pop() 17 | 18 | def push(self, value): 19 | ''' 20 | Complexity: Time O(1), Space O(1) 21 | Push a new item to the stack, also caching the min/max value of stack 22 | ''' 23 | min_max:Dict[str,int]= {'min': value ,'max': value} 24 | if len(self.min_max_stack): 25 | last_cache = self.min_max_stack[len(self.min_max_stack) - 1] 26 | min_max['min'] = min(last_cache['min'], value) 27 | min_max['max'] = max(last_cache['max'], value) 28 | self.min_max_stack.append(min_max) 29 | self.stack.append(value) 30 | 31 | def peek(self): 32 | return self.stack[len(self.stack) - 1] 33 | 34 | def get_min(self): 35 | if len(self.min_max_stack): 36 | return self.min_max_stack[len(self.min_max_stack) - 1]['min'] 37 | else: 38 | return self.stack.peek() 39 | 40 | def get_max(self): 41 | if len(self.min_max_stack): 42 | return self.min_max_stack[len(self.min_max_stack) - 1]['max'] 43 | else: 44 | return self.stack.peek() 45 | 46 | def peek_all(self): 47 | return self.stack 48 | 49 | 50 | if __name__ == "__main__": 51 | new_stack = MinMaxStack() 52 | new_stack.push(1) 53 | print(new_stack.get_min()) 54 | print(new_stack.get_max()) 55 | new_stack.push(2) 56 | new_stack.push(3) 57 | new_stack.push(4) 58 | new_stack.push(5) 59 | print(new_stack.peek_all()) 60 | print(new_stack.peek()) 61 | print(new_stack.get_min()) 62 | print(new_stack.get_max()) 63 | new_stack.pop() 64 | print(new_stack.peek()) 65 | print(new_stack.get_max()) 66 | 67 | 68 | -------------------------------------------------------------------------------- /entry_level_question/smallest_diff/python/smallest_diff.py: -------------------------------------------------------------------------------- 1 | def smallestDifference(arrayOne, arrayTwo): 2 | # Write your code here. 3 | 4 | arrayOne = merge_sort(arrayOne) 5 | arrayTwo = merge_sort(arrayTwo) 6 | smallest_diff = float('inf') 7 | diff = 0 8 | smallest_set = [None, None] 9 | array_one_idx = 0 10 | array_two_idx = 0 11 | while array_one_idx < len (arrayOne) and array_two_idx < len(arrayTwo): 12 | first_number = arrayOne[array_one_idx] 13 | second_number = arrayTwo[array_two_idx] 14 | if first_number > second_number: 15 | diff = first_number - second_number 16 | array_two_idx += 1 17 | elif first_number < second_number: 18 | diff = second_number - first_number 19 | array_one_idx += 1 20 | else: 21 | return [arrayOne[array_one_idx], arrayTwo[array_two_idx]] 22 | 23 | if diff < smallest_diff: 24 | smallest_diff = diff 25 | smallest_set[0] = first_number 26 | smallest_set[1] = second_number 27 | 28 | return smallest_set 29 | 30 | 31 | def merge_sort(array): 32 | if len(array) == 1: 33 | return array 34 | else: 35 | mid = len(array) // 2 36 | left = merge_sort(array[:mid]) 37 | right = merge_sort(array[mid:]) 38 | return do_merge(left, right) 39 | 40 | def do_merge(left, right): 41 | left_idx = 0 42 | right_idx = 0 43 | merged = [] 44 | while left_idx < len(left) and right_idx < len(right): 45 | if left[left_idx] > right[right_idx]: 46 | merged.append(right[right_idx]) 47 | right_idx += 1 48 | else: 49 | merged.append(left[left_idx]) 50 | left_idx += 1 51 | 52 | while left_idx < len(left): 53 | merged.append(left[left_idx]) 54 | left_idx += 1 55 | 56 | while right_idx < len(right): 57 | merged.append(right[right_idx]) 58 | right_idx += 1 59 | 60 | return merged 61 | 62 | if __name__ == "__main__": 63 | print(smallestDifference([-1,5,10,20,3],[26,134,135,15,17])) 64 | 65 | -------------------------------------------------------------------------------- /general-purpose-algorithm/KMP-algorithm/kmp-algorithm-java/src/app/App.java: -------------------------------------------------------------------------------- 1 | package app; 2 | import java.util.Arrays; 3 | 4 | 5 | 6 | public class App { 7 | public static void main(String[] args) throws Exception { 8 | 9 | String main = "The quick brown fox jumps over a lazy dog"; 10 | String sub = "lazy dog"; 11 | int[] pattern = buildPattern(sub); 12 | 13 | System.out.println(Arrays.toString(buildPattern(sub))); 14 | System.out.println(checkPattern(main,sub,pattern)); 15 | } 16 | 17 | public static int[] buildPattern(String substring){ 18 | int[] pattern = new int[substring.length()]; 19 | 20 | // Init the array to -1 for the convience of string indexing 21 | Arrays.fill(pattern, -1); 22 | int i = 1; // Starting point of a pre/suffix match 23 | int j = 0; // Length of a matched pre/suffix string 24 | while (i 0){ 32 | // reset the length to the last matched point. 33 | j = pattern[j-1] + 1; // Remember to plus one and turn it to normal string index 34 | } else { 35 | i++; 36 | } 37 | } 38 | return pattern; 39 | 40 | } 41 | 42 | public static boolean checkPattern(String mainString, String subString, int[] pattern){ 43 | int i = 0; // This is different from buildPattern(), because now we want a full match 44 | int j = 0; 45 | while (i + subString.length() - j <= mainString.length()){ 46 | if (mainString.charAt(i) == subString.charAt(j)){ 47 | if (j == subString.length() - 1) return true; // This means we get substring fully matched to the main 48 | i++; 49 | j++; 50 | } else if (j > 0){ 51 | // reset the length to the last matched point. 52 | j = pattern[j-1] + 1; // Remember to plus one and turn it to normal string index 53 | } else { 54 | i++; 55 | } 56 | } 57 | return false; 58 | } 59 | } -------------------------------------------------------------------------------- /interview-challenges/binary_tree/unival_tree/python/unival_tree.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | 4 | class Tree: 5 | def __init__(self, value, left=None, right=None): 6 | self.value = value 7 | self.left = left 8 | self.right = right 9 | 10 | def insert_left(self, value): 11 | self.left = Tree(value) 12 | return self 13 | 14 | def insert_right(self, value): 15 | self.right = Tree(value) 16 | return self 17 | 18 | def count_unival_tree(tree: Tree): 19 | counter = 0 20 | tree, counter = unival_counter(tree, counter) 21 | return counter 22 | 23 | def unival_counter(sub_tree: Tree, counter): 24 | if sub_tree.left is None and sub_tree.right is None: 25 | counter += 1 26 | return (sub_tree, counter) 27 | else: 28 | left = None 29 | right = None 30 | 31 | if sub_tree.left is not None: 32 | left, count_left = unival_counter(sub_tree.left, counter) 33 | if sub_tree.right is not None: 34 | right, count_right = unival_counter(sub_tree.right, counter) 35 | 36 | counter += count_left + count_right 37 | 38 | if left and right: 39 | if left.value == sub_tree.value and right.value == sub_tree.value: 40 | counter += 1 41 | 42 | return (sub_tree, counter) 43 | 44 | class TestCase(unittest.TestCase): 45 | tree_1 = Tree(1).insert_left(1).insert_right(1) 46 | tree_0 = Tree(0).insert_left(0).insert_right(0) 47 | 48 | ## tree_case_1 has 4 unival sub tree 49 | tree_case_1 = Tree(0, left=tree_1, right=Tree(0)) 50 | 51 | ## tree_case_2 has 5 unival sub tree 52 | tree_case_2 = Tree(0, left=Tree(1), right=tree_case_1) 53 | 54 | ## tree_case_3 has 7 unival sub tree 55 | tree_case_3 = Tree(0, left=tree_1, right=tree_case_1) 56 | 57 | ## tree_case_4 has 7 unival sub tree 58 | tree_case_4 = Tree(1, left=tree_1, right=tree_1) 59 | 60 | ## tree_case_5 has 6 unival sub tree 61 | tree_case_5 = Tree(0, left=tree_1, right=tree_1) 62 | 63 | 64 | def test_point_1(self): 65 | self.assertEqual(count_unival_tree(self.tree_case_1), 4) 66 | 67 | def test_point_2(self): 68 | self.assertEqual(count_unival_tree(self.tree_case_2), 5) 69 | 70 | def test_point_3(self): 71 | self.assertEqual(count_unival_tree(self.tree_case_3), 7) 72 | 73 | def test_point_4(self): 74 | self.assertEqual(count_unival_tree(self.tree_case_4), 7) 75 | 76 | def test_point_5(self): 77 | self.assertEqual(count_unival_tree(self.tree_case_5), 6) 78 | 79 | if __name__=="__main__": 80 | unittest.main() -------------------------------------------------------------------------------- /interview-challenges/sorting/find-inversions/analysis.md: -------------------------------------------------------------------------------- 1 | ## Analysis 2 | 3 | To do this in O(n^2), or quadratic time constrain, is quite simple, it is just a similar apporach to the bubble sort. However, if we want to get the outcome quicker, we need to find some non-linear structure to store and proceed the data. 4 | 5 | You might start thinking, "Well, does any sorting algorithm help to solve the issue". Definetely! As I mentioned earlier, the quadratic time solution is based on bubble sort. And if we want to do something faster, like in quasilinear time... Wait! Is the description of question mentioned something I saw somewhere else before? "Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j...". 6 | 7 | Aha, merge sort! 8 | 9 | The O(nlogn) solution for the question is exactly based on a tiny clever modification on the classic merge sort algorithm. Let's just quickly recall this algorithm. To get [2,4,1,3,5] -> [1,2,3,4,5], the merge sort will 10 | 11 | 1. Divide the array in two parts recursively, until there is only one element left in each child node 12 | ``` 13 | [2,4,1,3,5] 14 | / \ 15 | [2,4] [1,3,5] 16 | / \ / \ 17 | [2] [4] [1] [3,5] 18 | / \ 19 | [3] [5] 20 | ``` 21 | 2. Merge two array. If the array itself is in order, the left side is expect to have smaller integers than right side. So we always append left side's element first unless a integer in the right side is smaller than the left side. In this example, when we merge [2,4] and [1,3,5] 22 | 23 | (1) 1 is smaller than 2,4, so we append 1 first 24 | 25 | (2) 3 is larger than 2, so we append 2 26 | 27 | (3) 3 is smllar than 4, so we append 3 28 | 29 | (4) Moving on, the remaining part can already be appended in predetermined order 30 | 31 | The rule in 2 is applied to this code: 32 | ``` 33 | while i < len(left) and j < len(right) : 34 | if left[i] <= right[j]: 35 | ### Normal order 36 | merged.append(left[i]) 37 | i += 1 38 | else: 39 | ### Inverted order 40 | merged.append(right[j]) 41 | j += 1 42 | ``` 43 | 44 | Now we find that, if we can add something to store the state in the "Inverted order" part of code, we find our answer. 45 | 46 | And that is: 47 | ``` 48 | else: 49 | ### Inverted order 50 | for number in left[i:]: 51 | inverted.append((number,right[j])) 52 | merged.append(right[j]) 53 | j += 1 54 | ``` 55 | 56 | Hey, before you move to the next question, think about this question. Why: 57 | ``` 58 | for number in left[i:]: 59 | nverted.append((number,right[j])) 60 | ``` 61 | is able to give us all the inverted parts against right[j] in the array? -------------------------------------------------------------------------------- /interview-challenges/string_processing/match_pattern/python/match_pattern.py: -------------------------------------------------------------------------------- 1 | def get_pattern_construc(pattern): 2 | x_count = y_count = 0 3 | for value in pattern: 4 | if value == 'x': 5 | x_count += 1 6 | if value == 'y': 7 | y_count += 1 8 | return (x_count, y_count) 9 | 10 | def count_word(string, start, b_slice): 11 | count = 0 12 | b_idx = 0 13 | i = start 14 | while i < len(string): 15 | if string[i] == b_slice[b_idx]: 16 | b_idx += 1 17 | else: 18 | b_idx = 0 19 | if b_slice[b_idx] == string[i]: 20 | b_idx += 1 21 | if b_idx == len(b_slice): 22 | count += 1 23 | b_idx = 0 24 | i += 1 25 | return count 26 | 27 | def adjust_overlap(short_str, long_str, long_str_count): 28 | if len(short_str) < len(long_str) and short_str in long_str: 29 | return long_str_count 30 | else: 31 | return 0 32 | 33 | def find_word_block(string, x_count, y_count, pattern): 34 | start = 0 35 | x_word = '' 36 | y_word = '' 37 | if y_count > 0: 38 | first_y = pattern.index('y') 39 | else: 40 | first_y = -1 41 | for end in range(start + 1, len(string) + 1 - start): 42 | b_slice = string[start:end] 43 | b_slice_count = count_word(string, start, b_slice) 44 | if first_y != -1: 45 | y_start = len(b_slice) * first_y 46 | if y_start < string.index(b_slice) + len(b_slice): 47 | continue 48 | y_len = (len(string) - len(b_slice) * x_count) // y_count 49 | if y_len <= 0: 50 | break 51 | y_slice = string[y_start: y_start + y_len] 52 | 53 | if count_word(string, y_start, y_slice) - adjust_overlap(y_slice, b_slice, x_count) == y_count and b_slice_count - adjust_overlap(b_slice, y_slice, y_count) == x_count: 54 | if len(b_slice) > len(x_word): 55 | x_word = b_slice 56 | y_word = y_slice 57 | elif b_slice_count == x_count and len(b_slice) > len(x_word): 58 | x_word = b_slice 59 | 60 | if x_word == '' and y_word == '': 61 | return [] 62 | return [x_word, y_word] 63 | 64 | 65 | 66 | def patternMatcher(pattern, string): 67 | # Write your code here. 68 | matched_word = [] 69 | x_count, y_count = get_pattern_construc(pattern) 70 | matched_word = find_word_block(string, x_count, y_count, pattern) 71 | return matched_word 72 | 73 | 74 | if __name__ == "__main__": 75 | print(patternMatcher('yy', 'abab')) 76 | print(patternMatcher('xyxxyx','yesnoyesyesnoyes')) 77 | print(patternMatcher('xyxy', 'abab')) 78 | print(patternMatcher('xyxxxyyx', 'yesnoyesyesyesnonoyes')) 79 | print(patternMatcher('xxyxxy', 'abababcabababc')) 80 | print(patternMatcher('xyxxxyyx', 'ababcababababcabcab')) -------------------------------------------------------------------------------- /general-purpose-algorithm/1_sorting/merge_sort/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def merge_sort_sd(array:List[int]) -> List[int]: 4 | ''' 5 | Complexity: 6 | Best: O(nlog(n)) time | O(nlog(n)) space 7 | Avg: O(nlog(n)) time | O(nlog(n)) space 8 | Worst: O(nlog(n)) time | O(nlog(n)) space 9 | ''' 10 | if len(array) == 1: 11 | return array 12 | else: 13 | mid:int = len(array) // 2 14 | left: List[int] = merge_sort_sd(array[:mid]) 15 | right: List[int] = merge_sort_sd(array[mid:]) 16 | 17 | left_idx:int = 0 18 | right_idx:int = 0 19 | merged: List[int] = [] 20 | 21 | while left_idx < len(left) and right_idx < len(right): 22 | if right[right_idx] < left[left_idx]: 23 | merged.append(right[right_idx]) 24 | right_idx += 1 25 | else: 26 | merged.append(left[left_idx]) 27 | left_idx += 1 28 | 29 | while left_idx < len(left): 30 | merged.append(left[left_idx]) 31 | left_idx += 1 32 | 33 | while right_idx < len(right): 34 | merged.append(right[right_idx]) 35 | right_idx += 1 36 | 37 | return merged 38 | 39 | 40 | def merge_sort_opt(array:List[int], aux_array:List[int], start_idx:int, end_idx:int) -> None: 41 | ''' 42 | Complexity: 43 | Best: O(nlog(n)) time | O(n) space 44 | Avg: O(nlog(n)) time | O(n) space 45 | Worst: O(nlog(n)) time | O(n) space 46 | ''' 47 | if start_idx >= end_idx: 48 | return 49 | else: 50 | mid_idx:int = (start_idx + end_idx) // 2 51 | merge_sort_opt(aux_array, array, start_idx, mid_idx) 52 | merge_sort_opt(aux_array, array, mid_idx+1, end_idx) 53 | 54 | do_merge(array, aux_array, start_idx, mid_idx, end_idx) 55 | 56 | def do_merge(array:List[int], aux_array:List[int], left_limit:int, mid_idx:int, right_limit:int) -> None: 57 | array_ref: int = left_limit 58 | left_idx:int = left_limit 59 | right_idx:int = mid_idx + 1 60 | 61 | while left_idx <= mid_idx and right_idx <= right_limit: 62 | if aux_array[left_idx] >= aux_array[right_idx]: 63 | array[array_ref] = aux_array[right_idx] 64 | right_idx +=1 65 | else: 66 | array[array_ref] = aux_array[left_idx] 67 | left_idx += 1 68 | 69 | array_ref += 1 70 | 71 | while left_idx <= mid_idx: 72 | array[array_ref] = aux_array[left_idx] 73 | left_idx += 1 74 | array_ref += 1 75 | 76 | while right_idx <= right_limit: 77 | array[array_ref] = aux_array[right_idx] 78 | right_idx += 1 79 | array_ref += 1 80 | 81 | 82 | 83 | if __name__ == "__main__": 84 | array: List[int] = [5,6,1,3,2,4,7] 85 | #print(merge_sort_sd(array)) 86 | aux_array = array[:] 87 | merge_sort_opt(array, aux_array, 0, len(array)-1) 88 | print(array) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Moz's Algorithm Handbook 2 | Together, land on dream jobs in the world of software engineering! 3 | 4 | ## Who is this handbook for ? 5 | This handbook is made for beginners who just start learning computer programming and algorithms. Also, this handbook is intended to become a high-quality resource for newbies who are preparing for coding interviews, just like me. 6 | 7 | ## What coding languagues is this handbook written in ? 8 | **Java & Python 3**. These will provide you with examples in both static-typed and dynamic-typed (duck-typed) styles. Most of the cases discussed will come with Python code and test cases first. (Since I am writing these mostly by myself, it is quite difficult to cover both Java and Python part simultaneously T_T) 9 | 10 | ## How to use this handbook? 11 | Rules are simple. (1) Read the question. (2) Think about it for about 15 minutes (3) Implement your idea. (4) Run test cases (5) Check analysis.md and the code (6) Discuss it with your friends, if possible. 12 | 13 | ## About author 14 | I am a 2018 master graduate from the University of Melbourne, Australia, studying in Information Systems. Before that I was a commerce student learning economics and finance. I learned most of these CS-related knowledges during secondary and high school. Besides, I am the lead developer in the [IT Department of Chinese Student and Scholoar Association, Unimelb.](https://cssaunimelb.com/department/information/) 15 | 16 | ## Table of Content (Updating in progress) 17 | - General Purpose Algorithm 18 | 19 | This part covers most of the commonly discussed coding topics 20 | 21 | - Sorting 22 | - Depth First Search 23 | - [KMP Algorithm](general-purpose-algorithm/KMP-algorithm) 24 | 25 | - Funny topic 26 | 27 | - Coding Interview Questions 28 | 29 | Sources: https://dailycodingproblem.com/ 30 | 31 | - Google: 32 | - [Find the distinctive number](google/find-distinctive-digit) 33 | - [Fast exponent calculator](google/quick-int-exp-calc) 34 | - [Find inversions](google/find-inversions) 35 | - [Add up to K](google/add-up-to-K) 36 | 37 | 38 | ## Find bugs? 39 | If you find any issue, such as bugs in example code, uncovered edge cases, typos, ambiguous description, English grammar mistakes... 40 | 41 | Please report it at this repo's issue page or send me an email -> joshlubox@gmail.com 42 | ambiguous 43 | 44 | Thanks for any valuable suggestions in advance. 45 | 46 | 47 | ## To be an Contributor 48 | Send me an email -> joshlubox@gmail.com 49 | 50 | Let's work together and make this handbook better 51 | 52 | 53 | ## License 54 | 55 | The included codes are all licensed under GNU GPLv3 56 | 57 | 58 | Creative Commons License
The all related documents are licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. -------------------------------------------------------------------------------- /interview-challenges/bit_manipulation/find-distinctive-digit/analysis.md: -------------------------------------------------------------------------------- 1 | ## Analysis 2 | 3 | Think about a simply version of this question [2, 2, 5, 2] 4 | 5 | It is indeed difficult to find the '5' that is shown up exactly once, in decimal place... 6 | 7 | But, if we re-visit this issue using binary version: 8 | 9 | | Num / Bit | 3 | 2 | 1 | 0 | 10 | | ---- | :-:| :-: | :-: | :-: | 11 | | 2 | 0 | 0 | 1 | 0 | 12 | | 2 | 0 | 0 | 1 | 0 | 13 | | 5 | 0 | 1 | 0 | 1 | 14 | | 2 | 0 | 0 | 1 | 0 | 15 | 16 | Suddenly, we notice that if we can store the result in a array that can store all the bits in every bit position that exactly appears %3 == 1 (e.g, 1, 4, 7 ...) times. Then we find what we want. (in this case, [0, 1, 0, 1] == 5) 17 | 18 | This works with any cases, e.g. [6, 1, 3, 3, 3, 6, 6], 19 | | Num / Bit | 3 | 2 | 1 | 0 | 20 | | ---- | :-:| :-: | :-: | :-: | 21 | | 6 | 0 | 1 | 1 | 0 | 22 | | 1 | 0 | 0 | 0 | 1 | 23 | | 3 | 0 | 0 | 1 | 1 | 24 | | 3 | 0 | 0 | 1 | 1 | 25 | | 3 | 0 | 0 | 1 | 1 | 26 | | 6 | 0 | 1 | 1 | 0 | 27 | | 6 | 0 | 1 | 1 | 0 | 28 | 29 | So the bit that appears exactly %3 == 1 (e.g, 1, 4, 7 ...) times is the "1" at position 0 (4 times), which is [0, 0, 0, 1] == 1 30 | 31 | Then, how can we achive this? 32 | 33 | Think about what we learned from AND, OR, XOR operants. 34 | 35 | - AND == 1 when bits of a and b are exactly SAME and have True values. 36 | 37 | - OR == 1 when bits of a and b are at least one have a True value 38 | 39 | - XOR == 1 when bits of a and b are exactly OPPOSITE (e.g 0x10b XOR 0x01b == 0x11b) 40 | 41 | Notice something, right? If a bit appears once, its OR operation result will be 1. if it appears twice, its AND operation result will be also 1. What about three times? Well, if it reached three-time appearance, we want to remove (or 'reset') this bit, using XOR. 42 | 43 | We use variable 'once' and 'twice' to store the pervious state of bits in all position. Initially, they are all zeros. Also, we implement a bit mask to filter out bits that occurs every three times. Lets back to case [2, 2, 5, 2] to see how the algorithm works when triversing [2, 2, 5, 2]: 44 | 1. bin(2) == 0x0010, once = once ^ bin(2) = 0x0010 (Note: 0 XOR any non-zero value equals that value) 45 | 2. bin(2) == 0x0010, twice = twice | ( once & bin(2) ) = 0x0010, once = once ^ bin(2) = 0x0000 46 | 3. bin(5) == 0x0101, twice = twice | ( once & bin(5) ) = 0x0010, once = once ^ bin(5) = 0x0101 47 | 48 | Before we enter the final step of the triversing loop, let's recall the purpose of the mask first. It is used to filter out the duplicated bits and remain the bit that shown exactly once. So, firstly, if a bit had shown twice, it will be the 1 in relating positions in once and twice. 49 | 50 | 4. bin(2) == 0x0010, twice = twice = twice | ( once & bin(2) ) = 0x0010, once = once ^ bin(2) = 0x0111 51 | 52 | - If we check the common bits in once and twice, using twice & once, we get 0x0010, which is exactly the number 2 we want to exclude 53 | - To exclude, it, we can do a inverse operation, ~(twice & once) = 0x1101. This is the mask we want 54 | - To apply this mask, we simply do: 55 | ``` 56 | once &= mask 57 | twice &= mask 58 | ``` 59 | This remove the bits that appears eactly three times at current stage 60 | 61 | Finally, we get the result __5__ we want. In O(n) time and O(1) space. 62 | -------------------------------------------------------------------------------- /interview-challenges/string_processing/add_underscore/python/add_underscore.py: -------------------------------------------------------------------------------- 1 | def backward_index(string, char): 2 | i = len(string) - 1 3 | while i >= 0: 4 | if string[i] == char: 5 | return i 6 | i -= 1 7 | return -1 8 | 9 | 10 | def check_overlap(main_idx, string, substring): 11 | if string[main_idx] not in substring: 12 | return False 13 | offset_amount = backward_index(substring, string[main_idx]) 14 | sub_idx = 0 15 | if main_idx - offset_amount < 0: 16 | return False 17 | while offset_amount > 0: 18 | if string[main_idx-offset_amount] != substring[sub_idx]: 19 | return False 20 | offset_amount -= 1 21 | sub_idx += 1 22 | return True 23 | 24 | def resolve_overlap(main_idx, sub_idx, string, substring, pattern_match): 25 | offset_amount = backward_index(substring, string[main_idx]) 26 | sub_idx = offset_amount 27 | j = main_idx 28 | while offset_amount > 0: 29 | pattern_match[j] = offset_amount 30 | j -= 1 31 | offset_amount -= 1 32 | 33 | def underscorifySubstring(string, substring): 34 | # Write your code here. 35 | sub_idx = 0 36 | main_idx = 0 37 | pattern_match = [-1 for i in range(len(string))] 38 | while main_idx < len(string): 39 | if string[main_idx] == substring[sub_idx]: 40 | # if check_overlap(main_idx, string, substring): 41 | # resolve_overlap(main_idx, sub_idx, string, substring, pattern_match) 42 | # else: 43 | pattern_match[main_idx] = sub_idx 44 | sub_idx += 1 45 | elif check_overlap(main_idx, string, substring): 46 | resolve_overlap(main_idx, sub_idx, string, substring, pattern_match) 47 | else: 48 | j = main_idx 49 | while pattern_match[j] != len(substring)-1 and j >= 0: 50 | pattern_match[j] = -1 51 | j -= 1 52 | sub_idx = 0 53 | if sub_idx == len(substring): 54 | sub_idx = 0 55 | main_idx += 1 56 | if sub_idx > 0: 57 | j = main_idx - 1 58 | sub_idx -= 1 59 | while sub_idx >= 0 and j >= 0: 60 | pattern_match[j] = -1 61 | j -= 1 62 | sub_idx -= 1 63 | 64 | comp_string = '' 65 | in_range = False 66 | for i in range(len(string)): 67 | if pattern_match[i] != -1: 68 | if not in_range: 69 | in_range = True 70 | comp_string += '_' 71 | comp_string += string[i] 72 | continue 73 | else: 74 | if in_range: 75 | in_range = False 76 | comp_string += '_' 77 | comp_string += string[i] 78 | continue 79 | 80 | comp_string += string[i] 81 | if in_range: 82 | comp_string += '_' 83 | print("Pattern", pattern_match) 84 | return comp_string 85 | 86 | if __name__ == '__main__': 87 | # print(underscorifySubstring('aaaaaaaab', 'aaa')) 88 | # print(underscorifySubstring('aacaacaaab', 'aaca')) 89 | print(underscorifySubstring('ttesttest', 'ttest')) 90 | # print(underscorifySubstring('testthis is a testest to testestes it is work', 'test')) 91 | # print(underscorifySubstring('ttttttttttttttbtttttctatawtatttttastvb','ttt')) 92 | -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/link_lists/single_linked_list/remove_kth_from_end.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | 5 | class SingleLinkedList(): 6 | 7 | def __init__(self, value): 8 | self.value = value 9 | self.next = None 10 | 11 | def add_nodes(self, array): 12 | if len(array) > 0: 13 | last_node = self 14 | while last_node.next is not None: 15 | last_node = last_node.next 16 | 17 | for i in range(len(array)): 18 | new_node = SingleLinkedList(array[i]) 19 | last_node.next = new_node 20 | last_node = new_node 21 | return self 22 | 23 | def get_nodes_to_array(self): 24 | nodes = [] 25 | current = self 26 | while current is not None: 27 | nodes.append(current.value) 28 | current = current.next 29 | return nodes 30 | 31 | def remove_kth(self, k): 32 | ''' 33 | Complexity: Time = O(n); Space = O(1) 34 | ''' 35 | if k <= 0: 36 | return False 37 | interval_length = 1 38 | interval_start = self 39 | interval_end = self 40 | 41 | ## Move interval end to the position 42 | while interval_length <= k: 43 | interval_end = interval_end.next 44 | interval_length += 1 45 | 46 | ## Reach the start of the linked list 47 | if interval_end is None: 48 | interval_start.value = interval_start.next.value 49 | interval_start.next = interval_start.next.next 50 | return self 51 | 52 | ## move interval start to the place where item is for removing. 53 | while interval_end.next is not None: 54 | interval_start = interval_start.next 55 | interval_end = interval_end.next 56 | 57 | interval_start.next = interval_start.next.next 58 | 59 | return self 60 | 61 | def reverse(self): 62 | prev = None 63 | current = self 64 | while current is not None: 65 | next_node = current.next 66 | current.next = prev 67 | prev = current 68 | current = next_node 69 | self = prev 70 | return self 71 | 72 | 73 | 74 | 75 | class TestCases(unittest.TestCase): 76 | 77 | ## Test the correctness of Single List Class 78 | 79 | def test_case_1(self): 80 | case = SingleLinkedList(0).add_nodes([1,2,3,4,5]) 81 | self.assertEqual(case.get_nodes_to_array(),[0,1,2,3,4,5]) 82 | 83 | def test_case_2(self): 84 | case = SingleLinkedList(0).add_nodes([1,2,3]) 85 | self.assertEqual(case.get_nodes_to_array(),[0,1,2,3]) 86 | 87 | def test_case_3(self): 88 | case = SingleLinkedList(0).add_nodes([1,2,3]).add_nodes([4,5]) 89 | self.assertEqual(case.get_nodes_to_array(),[0,1,2,3,4,5]) 90 | 91 | ## Test Remove Kth function 92 | def test_case_4(self): 93 | case = SingleLinkedList(0).add_nodes([1,2,3,4,5,6]).add_nodes([7,8,9]) 94 | self.assertEqual(case.remove_kth(3).get_nodes_to_array(),[0,1,2,3,4,5,6,8,9]) 95 | 96 | def test_case_5(self): 97 | case = SingleLinkedList(0).add_nodes([1,2,3]).add_nodes([4,5]) 98 | self.assertEqual(case.remove_kth(6).get_nodes_to_array(),[1,2,3,4,5]) 99 | 100 | def test_case_6(self): 101 | case = SingleLinkedList(0).add_nodes([1,2,3]).add_nodes([4,5]) 102 | self.assertEqual(case.reverse().get_nodes_to_array(),[5,4,3,2,1,0]) 103 | 104 | 105 | if __name__ == "__main__": 106 | unittest.main() -------------------------------------------------------------------------------- /interview-challenges/searching_algorithm/boggle_board/python/boggle_board.py: -------------------------------------------------------------------------------- 1 | def boggleBoard(board, words): 2 | # Write your code here. 3 | tree = SufTree() 4 | for word in words: 5 | tree.insert(word) 6 | 7 | found_strings = [] 8 | find_string(tree, board, found_strings) 9 | return found_strings 10 | 11 | 12 | def find_string(tree, board, found_strings): 13 | for i in range(len(board)): 14 | for j in range(len(board[i])): 15 | letter = board[i][j] 16 | node = tree.node 17 | if letter in node: 18 | check_word(i,j,board,node[letter],tree,letter,found_strings) 19 | 20 | def check_word(row,col,board,node,tree,word,found_strings): 21 | if board[row][col] == '*': 22 | return 23 | 24 | if tree.end_symbol in node and node[tree.end_symbol] == word: 25 | found_strings.append(word) 26 | 27 | current_letter = board[row][col] 28 | board[row][col] = '*' 29 | #top-left 30 | if row-1 > 0 and col-1 > 0 and board[row-1][col-1] in node: 31 | letter = board[row-1][col-1] 32 | check_word(row-1, col-1, board, node[letter], tree ,word+letter, found_strings) 33 | board[row][col] = current_letter 34 | #top 35 | if row-1 > 0 and board[row-1][col] in node: 36 | letter = board[row-1][col] 37 | check_word(row-1, col, board, node[letter], tree ,word+letter, found_strings) 38 | board[row][col] = current_letter 39 | #top-right 40 | if row-1 > 0 and col+1 0 and board[row][col-1] in node: 46 | letter = board[row][col-1] 47 | check_word(row, col-1, board, node[letter], tree ,word+letter, found_strings) 48 | board[row][col] = current_letter 49 | #right 50 | if col+1 < len(board[row]) and board[row][col+1] in node: 51 | letter = board[row][col+1] 52 | check_word(row, col+1, board, node[letter], tree ,word+letter, found_strings) 53 | board[row][col] = current_letter 54 | #btm-left 55 | if row+1 < len(board) and col-1 > 0 and board[row+1][col-1] in node: 56 | letter = board[row+1][col-1] 57 | check_word(row+1, col-1, board, node[letter], tree ,word+letter, found_strings) 58 | board[row][col] = current_letter 59 | #btm 60 | if row+1 < len(board) and board[row+1][col] in node: 61 | letter = board[row+1][col] 62 | check_word(row+1, col, board, node[letter], tree ,word+letter, found_strings) 63 | board[row][col] = current_letter 64 | #btm-right 65 | if row+1 < len(board) and col+1 < len(board[row]) and board[row+1][col+1] in node: 66 | letter = board[row+1][col+1] 67 | check_word(row+1, col+1, board, node[letter], tree ,word+letter, found_strings) 68 | board[row][col] = current_letter 69 | 70 | board[row][col] = current_letter 71 | 72 | class SufTree: 73 | def __init__(self): 74 | self.node = {} 75 | self.end_symbol = '*' 76 | 77 | def insert(self, string): 78 | current_node = self.node 79 | for i in range(len(string)): 80 | letter = string[i] 81 | if letter not in current_node: 82 | current_node[letter] = {} 83 | current_node = current_node[letter] 84 | current_node[self.end_symbol] = string 85 | 86 | 87 | if __name__ == "__main__": 88 | board = [ 89 | ['a','b','c','d','e'], 90 | ['f','g','h','i','j'], 91 | ['k','l','m','n','o'], 92 | ['p','q','r','s','t'], 93 | ['u','v','w','x','y'], 94 | ] 95 | words = ["agmsy","agmsytojed","agmsytojedinhcbfl","agmsytojedinhcbgl"] 96 | print(boggleBoard(board,words)) 97 | -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/heap/min_max_heap/python/heap.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict 2 | 3 | class MinHeap(): 4 | 5 | def __init__(self, array:List[int]): 6 | self.heap: List[int] = self.build_heap(array) 7 | 8 | 9 | def build_heap(self, array:List[int]): 10 | first_parent_idx:int = (len(array) - 2) // 2 11 | for current_parent_node in reversed(range(first_parent_idx + 1)): 12 | self.sift_down(current_parent_node, len(array)-1, array) 13 | return array 14 | 15 | def sift_down(self, current_idx:int, end:int, heap:List[int]) -> None: 16 | left_child_idx:int = current_idx * 2 + 1 17 | while left_child_idx <= end: 18 | right_child_idx:int = current_idx * 2 + 2 if current_idx * 2 + 2 <= end else -1 19 | if right_child_idx != -1 and heap[right_child_idx] < heap[left_child_idx]: 20 | swap_idx:int = right_child_idx 21 | else: 22 | swap_idx = left_child_idx 23 | 24 | if heap[current_idx] > heap[swap_idx]: 25 | heap[swap_idx], heap[current_idx] = heap[current_idx], heap[swap_idx] 26 | current_idx = swap_idx 27 | left_child_idx = current_idx * 2 + 1 28 | else: 29 | return None 30 | 31 | def sift_up(self, current_idx:int, heap:List[int]) -> None: 32 | parent_idx:int = (current_idx - 1) // 2 33 | while parent_idx >= 0 and heap[current_idx] < heap[parent_idx]: 34 | heap[parent_idx], heap[current_idx] = heap[current_idx], heap[parent_idx] 35 | current_idx = parent_idx 36 | parent_idx = (current_idx - 1) // 2 37 | 38 | 39 | def peek(self): 40 | return (self.heap[0]) 41 | 42 | def remove(self): 43 | self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] 44 | removed_value:int = self.heap.pop() 45 | self.sift_down(0, len(self.heap) - 1, self.heap) 46 | return removed_value 47 | 48 | def insert(self, number): 49 | self.heap.append(number) 50 | self.sift_up(len(self.heap) - 1, self.heap) 51 | 52 | 53 | 54 | class MaxHeap(): 55 | 56 | def __init__(self, array:List[int]): 57 | self.heap: List[int] = self.build_heap(array) 58 | 59 | 60 | def build_heap(self, array:List[int]): 61 | first_parent_idx:int = (len(array) - 2) // 2 62 | for current_parent_node in reversed(range(first_parent_idx + 1)): 63 | self.sift_down(current_parent_node, len(array)-1, array) 64 | return array 65 | 66 | def sift_down(self, current_idx:int, end:int, heap:List[int]) -> None: 67 | left_child_idx:int = current_idx * 2 + 1 68 | while left_child_idx <= end: 69 | right_child_idx:int = current_idx * 2 + 2 if current_idx * 2 + 2 <= end else -1 70 | if right_child_idx != -1 and heap[right_child_idx] > heap[left_child_idx]: 71 | swap_idx:int = right_child_idx 72 | else: 73 | swap_idx = left_child_idx 74 | 75 | if heap[current_idx] < heap[swap_idx]: 76 | heap[swap_idx], heap[current_idx] = heap[current_idx], heap[swap_idx] 77 | current_idx = swap_idx 78 | left_child_idx = current_idx * 2 + 1 79 | else: 80 | return None 81 | 82 | def sift_up(self, current_idx:int, heap:List[int]) -> None: 83 | parent_idx:int = (current_idx - 1) // 2 84 | while parent_idx >= 0 and heap[current_idx] < heap[parent_idx]: 85 | heap[parent_idx], heap[current_idx] = heap[current_idx], heap[parent_idx] 86 | current_idx = parent_idx 87 | parent_idx = (current_idx - 1) // 2 88 | 89 | 90 | def peek(self): 91 | return (self.heap[0]) 92 | 93 | def remove(self): 94 | self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] 95 | removed_value:int = self.heap.pop() 96 | self.sift_down(0, len(self.heap) - 1, self.heap) 97 | return removed_value 98 | 99 | def insert(self, number): 100 | self.heap.append(number) 101 | self.sift_up(len(self.heap) - 1, self.heap) -------------------------------------------------------------------------------- /general-purpose-algorithm/2_data_structure/heap/find_median/python/find_median.py: -------------------------------------------------------------------------------- 1 | from typing import List, Any 2 | 3 | class LiveMedianHandler(): 4 | def __init__(self,): 5 | self.lower_part_max_heap: Heap = Heap(MAX_HEAP_COMPARE_FUNC, []) 6 | self.upper_part_min_heap: Heap = Heap(MIN_HEAP_COMPARE_FUNC, []) 7 | self.median:int = 0 8 | 9 | def insert(self, value) -> None: 10 | if self.lower_part_max_heap.length == 0 or self.lower_part_max_heap.peek() > value: 11 | self.lower_part_max_heap.insert(value) 12 | else: 13 | self.upper_part_min_heap.insert(value) 14 | 15 | if self.lower_part_max_heap.length - self.upper_part_min_heap.length >= 2: 16 | self.balance_heaps(self.lower_part_max_heap, self.upper_part_min_heap) 17 | 18 | if self.upper_part_min_heap.length - self.lower_part_max_heap.length >= 2: 19 | self.balance_heaps(self.upper_part_min_heap, self.lower_part_max_heap) 20 | 21 | self.update_median() 22 | 23 | 24 | def balance_heaps(self, long_heap: Any, short_heap: Any) -> None: 25 | exceed_note = long_heap.remove() 26 | short_heap.insert(exceed_note) 27 | 28 | def update_median(self) -> None: 29 | total_length = self.lower_part_max_heap.length + self.upper_part_min_heap.length 30 | if total_length % 2 == 0: 31 | self.median = round((self.lower_part_max_heap.peek() + self.upper_part_min_heap.peek()) / 2, 2) 32 | elif self.lower_part_max_heap.length < self.upper_part_min_heap.length: 33 | self.median = self.upper_part_min_heap.peek() 34 | else: 35 | self.median = self.lower_part_max_heap.peek() 36 | 37 | def getMedian(self) -> int: 38 | return self.median 39 | 40 | 41 | 42 | def MAX_HEAP_COMPARE_FUNC(a,b): 43 | return a < b 44 | 45 | def MIN_HEAP_COMPARE_FUNC(a,b): 46 | return a > b 47 | 48 | 49 | class Heap(): 50 | 51 | def __init__(self, compare_func:Any, array): 52 | self.heap:List[int] = self.build(array) 53 | self.compare_func = compare_func 54 | self.length:int = len(self.heap) 55 | 56 | 57 | def build(self,array) -> List[int]: 58 | # The first parent node index is different from subsidary parent node index, here you need -2, 59 | # because we considered that a heap trie is completed so first parrent node will have two children 60 | first_parrent_idx = (len(array) -2) // 2 61 | for current_idx in reversed(range(first_parrent_idx + 1)): 62 | self.sift_down(current_idx, len(array)-1, array) 63 | return array 64 | 65 | def sift_down(self, current_idx:int, heap_end_idx:int, heap:List[int]) -> None: 66 | first_child_idx = current_idx * 2 + 1 67 | while first_child_idx <= heap_end_idx: 68 | second_child_idx = current_idx * 2 + 2 if current_idx * 2 + 2 <= heap_end_idx else -1 69 | if second_child_idx is not -1: 70 | if self.compare_func(heap[first_child_idx], heap[second_child_idx]): 71 | swap_target_idx = second_child_idx 72 | else: 73 | swap_target_idx = first_child_idx 74 | else: 75 | swap_target_idx = first_child_idx 76 | if self.compare_func(heap[current_idx], heap[swap_target_idx]): 77 | heap[current_idx], heap[swap_target_idx] = heap[swap_target_idx], heap[current_idx] 78 | current_idx = swap_target_idx 79 | first_child_idx = current_idx * 2 + 1 80 | else: 81 | return 82 | 83 | def insert(self, value) -> None: 84 | self.heap.append(value) 85 | self.sift_up(len(self.heap)-1, self.heap) 86 | self.length += 1 87 | 88 | def remove(self) -> int: 89 | self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] 90 | removed_node = self.heap.pop() 91 | self.sift_down(0,len(self.heap)-1, self.heap) 92 | self.length -= 1 93 | return removed_node 94 | 95 | def sift_up(self, current_idx:int, heap:List[int]) -> None: 96 | parent_idx = (current_idx -1) // 2 97 | while current_idx >0 and self.compare_func(heap[parent_idx], heap[current_idx]): 98 | heap[current_idx], heap[parent_idx] = heap[parent_idx], heap[current_idx] 99 | current_idx = parent_idx 100 | parent_idx = (current_idx -1) // 2 101 | 102 | 103 | def peek(self): 104 | return self.heap[0] 105 | 106 | 107 | if __name__ == "__main__": 108 | median_seq = LiveMedianHandler() 109 | median_seq.insert(5) 110 | median_seq.insert(10) 111 | print(median_seq.getMedian()) 112 | median_seq.insert(100) 113 | print(median_seq.getMedian()) 114 | median_seq.insert(200) 115 | median_seq.insert(6) 116 | median_seq.insert(13) 117 | median_seq.insert(14) 118 | print(median_seq.getMedian()) 119 | median_seq.insert(50) 120 | print(median_seq.getMedian()) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------