├── .gitignore ├── README.md ├── module_1 ├── java │ ├── CoinChange.java │ ├── DiameterOfBinaryTree.java │ ├── FindAnagrams.java │ ├── GeneratePowerSet.java │ ├── HammingWeight.java │ ├── IsBipartite.java │ ├── LengthOfLongestSubstring.java │ ├── ReverseList.java │ ├── SearchRotatedArray.java │ └── StackFromQueue.java ├── javascript │ ├── CoinChange.js │ ├── DiameterOfBinaryTree.js │ ├── FindAnagrams.js │ ├── GeneratePowerSet.js │ ├── HammingWeight.js │ ├── IsBipartite.js │ ├── LengthOfLongestSubstring.js │ ├── ReverseList.js │ ├── SearchRotatedArray.js │ └── StackFromQueue.js └── python │ ├── coin_change.py │ ├── diameter_of_binary_tree.py │ ├── find_anagrams.py │ ├── generate_power_set.py │ ├── hamming_weight.py │ ├── is_bipartite.py │ ├── length_of_longest_substring.py │ ├── reverse_list.py │ ├── search_rotated_array.py │ └── stack_from_queue.py ├── module_2 ├── java │ ├── ClimbStairs.java │ ├── HasCycle.java │ ├── MaxDepthBinaryTree.java │ ├── MaxProfit.java │ ├── MaximumSubarray.java │ ├── MergeIntervals.java │ └── NumIslands.java ├── javascript │ ├── ClimbStairs.js │ └── HasCycle.js └── python │ ├── climb_stairs.py │ ├── has_cycle.py │ ├── max_depth_binary_tree.py │ ├── max_profit.py │ ├── maximum_subarray.py │ ├── merge_intervals.py │ └── num_islands.py ├── module_3 ├── java │ ├── ClimbStairs.java │ ├── FindMedianSortedArrays.java │ ├── GenerateParenthesis.java │ ├── HasCycle.java │ ├── LRUCache.java │ ├── LongestConsecutive.java │ ├── LongestPalindrome.java │ ├── MaxDepthBinaryTree.java │ ├── MaxProfit.java │ ├── MaximumSubarray.java │ ├── MergeIntervals.java │ ├── MergeKSorted.java │ ├── Template.java │ └── WordBreak.java └── python │ ├── climb_stairs.py │ ├── find_median_sorted_arrays.py │ ├── generate_parenthesis.py │ ├── has_cycle.py │ ├── longest_consecutive.py │ ├── longest_palindrome.py │ ├── lru_cache.py │ ├── max_depth_binary_tree.py │ ├── max_profit.py │ ├── maximum_subarray.py │ ├── merge_intervals.py │ ├── merge_k_lists.py │ ├── template.py │ └── word_break.py ├── module_4 ├── java │ ├── AddTwoNumbers.java │ ├── Calculate.java │ ├── FindMedian.java │ ├── FirstMissingPositive.java │ ├── HammingWeight.java │ ├── JustifyText.java │ ├── KClosest.java │ ├── LengthOfLongestSubstring.java │ ├── MissingNumber.java │ ├── RandomNode.java │ ├── SearchRotatedArray.java │ ├── SortList.java │ ├── SplitArray.java │ ├── Template.java │ ├── ThreeSum.java │ └── WordLadder.java └── python │ ├── add_two_numbers.py │ ├── calculate.py │ ├── find_median.py │ ├── first_missing_positive.py │ ├── hamming_weight.py │ ├── justify_text.py │ ├── k_closest.py │ ├── length_of_longest_substring.py │ ├── missing_number.py │ ├── random_node.py │ ├── search_rotated_array.py │ ├── sort_list.py │ ├── split_array.py │ ├── template.py │ ├── three_sum.py │ └── word_ladder.py ├── module_5 ├── java │ ├── CoinChange.java │ ├── InvalidParentheses.java │ ├── LCA.java │ ├── MaxArea.java │ ├── MaxPathSum.java │ ├── MaxRectangle.java │ ├── ProductExceptSelf.java │ ├── SerializeBinaryTree.java │ └── Template.java └── python │ ├── coin_change.py │ ├── invalid_parentheses.py │ ├── lca.py │ ├── max_area.py │ ├── max_path_sum.py │ ├── max_rectangle.py │ ├── product_except_self.py │ ├── serialize_binary_tree.py │ └── template.py ├── module_6 ├── java │ ├── CourseSchedule.java │ ├── MergeBinaryTrees.java │ ├── SlidingPuzzle.java │ ├── Template.java │ └── WordLadder.java └── python │ ├── course_schedule.py │ ├── merge_binary_trees.py │ ├── sliding_puzzle.py │ ├── template.py │ └── word_ladder.py └── quickstart_guides ├── .gitignore ├── arrays_strings ├── README.md ├── java │ ├── CompareVersion.java │ ├── EditDistance.java │ ├── FindAnagrams.java │ ├── IsAnagram.java │ ├── IsPalindrome.java │ ├── LengthOfLongestSubstring.java │ ├── LongestSubstring.java │ ├── MinWindowSubstring.java │ ├── RegexMatching.java │ ├── RemoveDuplicates.java │ ├── ReverseString.java │ ├── SortString.java │ ├── StringToBinary.java │ ├── StringToInt.java │ ├── SubstringConcat.java │ └── WildcardMatching.java └── python │ ├── compare_version.py │ ├── edit_distance.py │ ├── find_anagrams.py │ ├── is_anagram.py │ ├── is_palindrome.py │ ├── length_of_longest_substring.py │ ├── longest_substring.py │ ├── min_window_substring.py │ ├── regex_matching.py │ ├── remove_duplicates.py │ ├── reverse_string.py │ ├── sort_string.py │ ├── string_to_binary.py │ ├── string_to_int.py │ ├── substring_concat.py │ └── wildcard_matching.py ├── bit_manipulation ├── README.md ├── java │ ├── HammingDistance.java │ ├── HammingWeight.java │ ├── IsEvenOdd.java │ ├── MissingNumber.java │ ├── PowerOfFour.java │ ├── PowerOfTwo.java │ ├── ReverseSigned.java │ ├── SetNthBit.java │ └── SumTwoInts.java └── python │ ├── hamming_distance.py │ ├── hamming_weight.py │ ├── is_even_odd.py │ ├── missing_number.py │ ├── power_of_four.py │ ├── power_of_two.py │ ├── reverse_unsigned.py │ ├── set_nth_bit.py │ └── sum_two_ints.py ├── graphs ├── README.md ├── java │ ├── AlienDictionary.java │ ├── BFS.java │ ├── CloneGraph.java │ ├── CourseSchedule.java │ ├── DFS.java │ ├── IsBipartite.java │ └── NetworkDelay.java └── python │ ├── alien_dictionary.py │ ├── bfs.py │ ├── clone_graph.py │ ├── course_schedule.py │ ├── dfs.py │ ├── is_bipartite.py │ └── network_delay.py ├── linked_lists ├── README.md ├── java │ ├── IsPalindrome.java │ ├── MergeKSorted.java │ ├── NthToLast.java │ ├── PairsWithSum.java │ ├── RemoveSortedDuplicates.java │ ├── RemoveUnsortedDuplicates.java │ ├── ReorderList.java │ ├── ReverseList.java │ └── SwapNodes.java └── python │ ├── is_palindrome.py │ ├── merge_k_sorted.py │ ├── nth_to_last.py │ ├── pairs_with_sum.py │ ├── remove_sorted_duplicates.py │ ├── remove_unsorted_duplicates.py │ ├── reorder_list.py │ ├── reverse_list.py │ └── swap_nodes.py ├── recursion ├── README.md ├── java │ ├── BinarySearch.java │ ├── ClimbStairs.java │ ├── DistinctPerms.java │ ├── FindCombos.java │ ├── FindSubstrings.java │ ├── InterleavingStrings.java │ ├── IsPalindrome.java │ ├── Knapsack.java │ ├── MergeSort.java │ ├── NDigitSum.java │ ├── PermsOfSet.java │ ├── TowerOfHanoi.java │ └── UniqueBST.java └── python │ ├── binary_search.py │ ├── climb_stairs.py │ ├── distinct_perms.py │ ├── find_combos.py │ ├── find_substrings.py │ ├── interleaving_strings.py │ ├── is_palindrome.py │ ├── knapsack.py │ ├── merge_sort.py │ ├── n_digit_sum.py │ ├── perms_of_set.py │ ├── reverse_linked_list.py │ ├── tower_of_hanoi.py │ └── unique_bst.py ├── sorting_searching ├── README.md ├── java │ ├── BinarySearch.java │ ├── FindClosestNumber.java │ ├── FindFirstDuplicateEntry.java │ ├── FindFixedPoint.java │ ├── FindLargestNumber.java │ ├── FindRotatedArray.java │ ├── FindSqrt.java │ ├── MergeSort.java │ ├── QuickSort.java │ └── SortLinkedList.java └── python │ ├── binary_search.py │ ├── find_closest_number.py │ ├── find_first_duplicate_entry.py │ ├── find_fixed_point.py │ ├── find_largest_number.py │ ├── find_rotated_array.py │ ├── find_sqrt.py │ ├── merge_sort.py │ ├── quick_sort.py │ └── sort_linked_list.py └── trees ├── README.md ├── java ├── DiameterOfBinaryTree.java ├── InorderTraversal.java ├── InvertBinaryTree.java ├── IsBalancedBinaryTree.java ├── LevelorderTraversal.java ├── LowestCommonAncestor.java ├── MaxDepthBinaryTree.java ├── MaxPathSum.java ├── MergeBinaryTrees.java ├── PostorderTraversal.java ├── PreorderTraversal.java ├── SerializeBinaryTree.java └── TreeToList.java └── python ├── diameter_of_binary_tree.py ├── inorder_traversal.py ├── invert_binary_tree.py ├── is_balanced_binary_tree.py ├── levelorder_traversal.py ├── lowest_common_ancestor.py ├── max_depth_binary_tree.py ├── max_path_sum.py ├── merge_binary_trees.py ├── postorder_traversal.py ├── preorder_traversal.py ├── serialize_binary_tree.py └── tree_to_list.py /README.md: -------------------------------------------------------------------------------- 1 | # 6-Weeks-to-Interview-Ready 2 | This repo contains the code solutions for https://www.byte-by-byte.com/6-weeks-sp 3 | -------------------------------------------------------------------------------- /module_1/java/HammingWeight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Hamming Weight 3 | * Leetcode Link: https://leetcode.com/problems/number-of-1-bits/ 4 | * 5 | * Problem: Write a function that takes an unsigned integer and return the 6 | * number of '1' bits it has (also known as the Hamming weight). 7 | * 8 | * Input: 9 | * int n => Unsigned integer 10 | * Output: 11 | * int => Number of 1 bits in n 12 | * 13 | * Execution: javac HammingWeight.java && java -ea HammingWeight 14 | */ 15 | 16 | public class HammingWeight { 17 | 18 | /* 19 | * Solution #1: Brute force solution using bit shifting 20 | * 21 | * Continually shift bits right and check whether the lowest order bit is 1 22 | * 23 | * Time Complexity: O(log(n)) 24 | * Space Complexity: O(1) 25 | */ 26 | public static int hammingWeightBF(int n) { 27 | int sum = 0; 28 | while (n > 0) { 29 | // Check if the lowest-order bit is 1 30 | if ((n & 1) > 0) sum++; 31 | 32 | // Do an unsigned bitshift 33 | n >>>= 1; 34 | } 35 | return sum; 36 | } 37 | 38 | /* 39 | * Solution #2: Optimized solution 40 | * 41 | * n & n-1 removes the lowest-order 1 bit in the number. Repeat this until 42 | * n == 0 43 | * 44 | * Time Complexity: O(log(n)) => More optimal when few 1 bits 45 | * Space Complexity: O(1) 46 | */ 47 | public static int hammingWeight(int n) { 48 | int sum = 0; 49 | while (n != 0) { 50 | // This removes the lowest-order 1 bit 51 | n &= n-1; 52 | sum++; 53 | } 54 | return sum; 55 | } 56 | 57 | public static void main(String[] args) { 58 | assert hammingWeight(0b1011) == 3; 59 | assert hammingWeight(0b1000000) == 1; 60 | assert hammingWeight(0b11111111111111111111111111111101) == 31; 61 | 62 | // ADD TEST CASES HERE 63 | 64 | System.out.println("Passed all test cases"); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /module_1/javascript/HammingWeight.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Hamming Weight 3 | * Leetcode Link: https://leetcode.com/problems/number-of-1-bits/ 4 | * 5 | * Problem: Write a function that takes an unsigned integer and return the 6 | * number of '1' bits it has (also known as the Hamming weight). 7 | * 8 | * Input: 9 | * number n => Unsigned integer 10 | * Output: 11 | * number => Number of 1 bits in n 12 | * 13 | * Execution: node HammingWeight.js 14 | */ 15 | 16 | /** 17 | * Solution #1: Brute force solution using bit shifting 18 | * 19 | * Continually shift bits right and check whether the lowest order bit is 1 20 | * 21 | * Time Complexity: O(log(n)) 22 | * Space Complexity: O(1) 23 | * 24 | * @param {number} n 25 | * @return {number} 26 | */ 27 | var hammingWeightBF = function(n) { 28 | var sum = 0; 29 | while (n > 0) { 30 | // Check if the lowest-order bit is 1 31 | if ((n & 1) > 0) sum++; 32 | 33 | // Do an unsigned bitshift 34 | n >>>= 1; 35 | } 36 | return sum; 37 | } 38 | 39 | /** 40 | * Solution #2: Optimized solution 41 | * 42 | * n & n-1 removes the lowest-order 1 bit in the number. Repeat this until 43 | * n == 0 44 | * 45 | * Time Complexity: O(log(n)) => More optimal when few 1 bits 46 | * Space Complexity: O(1) 47 | * 48 | * @param {number} n 49 | * @return {number} 50 | */ 51 | var hammingWeight = function(n) { 52 | var sum = 0; 53 | while (n != 0) { 54 | // This removes the lowest-order 1 bit 55 | n &= n-1; 56 | sum++; 57 | } 58 | return sum; 59 | } 60 | 61 | var tester = function() { 62 | console.assert(hammingWeight(0b1011) == 3); 63 | console.assert(hammingWeight(0b100000) == 1); 64 | console.assert(hammingWeight(0b11111111111111111111111111111101) == 31); 65 | 66 | // ADD YOUR OWN TESTS HERE 67 | } 68 | 69 | tester(); 70 | -------------------------------------------------------------------------------- /module_1/python/hamming_weight.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Hamming Weight 3 | Leetcode Link: https://leetcode.com/problems/number-of-1-bits/ 4 | 5 | Problem: Write a function that takes an unsigned integer and return the 6 | number of '1' bits it has (also known as the Hamming weight). 7 | 8 | Input: 9 | int n => Unsigned integer 10 | Output: 11 | int => Number of 1 bits in n 12 | 13 | Execution: python hamming_weight.py 14 | """ 15 | import unittest 16 | 17 | """ 18 | Solution #1: Brute force solution using bit shifting 19 | 20 | Continually shift bits right and check whether the lowest order bit is 1 21 | 22 | Time Complexity: O(log(n)) 23 | Space Complexity: O(1) 24 | """ 25 | def hamming_weight_bf(n: int) -> int: 26 | sum = 0 27 | while n > 0: 28 | # Check if lowest order bit is 1 29 | if (n & 1) > 0: 30 | sum = sum+1 31 | 32 | # Do a bitshift 33 | n = n>>1 34 | 35 | return sum 36 | 37 | """ 38 | Solution #2: Optimized solution 39 | 40 | n & n-1 removes the lowest-order 1 bit in the number. Repeat this until 41 | n == 0 42 | 43 | Time Complexity: O(log(n)) => More optimal when few 1 bits 44 | Space Complexity: O(1) 45 | """ 46 | def hamming_weight(n: int) -> int: 47 | sum = 0 48 | while n != 0: 49 | # This removes the lowest-order 1 bit 50 | n &= (n - 1) 51 | sum = sum+1 52 | 53 | return sum 54 | 55 | class TestHammingWeight(unittest.TestCase): 56 | """Unit test for Hamming weight.""" 57 | 58 | def test_1(self): 59 | self.assertEqual(hamming_weight(int("0b1011", 2)), 3) 60 | 61 | def test_2(self): 62 | self.assertEqual(hamming_weight(int("0b100000", 2)), 1) 63 | 64 | def test_3(self): 65 | self.assertEqual(hamming_weight(int("0b11111111111111111111111111111101", 2)), 31) 66 | 67 | # ADD YOUR TESTS HERE 68 | 69 | if __name__ == '__main__': 70 | unittest.main() 71 | -------------------------------------------------------------------------------- /module_2/java/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Maximum subarray 3 | * 4 | * Problem:Given an integer array nums, find the contiguous subarray 5 | * (containing at least one number) which has the largest sum and return its 6 | * sum. 7 | * 8 | * Execution: javac MaximumSubarray && java MaximumSubarray 9 | */ 10 | 11 | 12 | public class MaximumSubarray { 13 | public static int maximumSubarray(int[] A) { 14 | int maxSoFar = A[0]; 15 | int maxEndingHere = A[0]; 16 | for (int i=1; i Integer.compare(i1[0], i2[0])); 21 | 22 | List result = new ArrayList<>(); 23 | int[] newInterval = intervals[0]; 24 | result.add(newInterval); 25 | for (int[] interval : intervals) { 26 | if (interval[0] <= newInterval[1]) // Overlapping intervals, move the end if needed 27 | newInterval[1] = Math.max(newInterval[1], interval[1]); 28 | else { // Disjoint intervals, add the new interval to the list 29 | newInterval = interval; 30 | result.add(newInterval); 31 | } 32 | } 33 | 34 | return result.toArray(new int[result.size()][]); 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[][] testIn_1 = { { 1, 3 }, { 2, 6 }, {8, 10}, {15, 18} }; 39 | int[][] testOut_1 = { {1, 6}, {8, 10}, {15, 18} }; 40 | assert Arrays.equals(mergeIntervals(testIn_1), testOut_1); 41 | System.out.println("Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]."); 42 | 43 | int[][] testIn_2 = { { 1, 4 }, {4, 5} }; 44 | int[][] testOut_2 = { {1, 5} }; 45 | assert Arrays.equals(mergeIntervals(testIn_2), testOut_2); 46 | System.out.println("Explanation: Intervals [1,4] and [4,5] are considered overlapping."); 47 | 48 | 49 | System.out.println("Passed all test cases"); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /module_2/java/NumIslands.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Count number of islands 3 | * 4 | * Problem:Given a 2d grid map of '1's (land) and '0's (water), count the 5 | * number of islands. An island is surrounded by water and is formed by 6 | * connecting adjacent lands horizontally or vertically. You may assume all 7 | * four edges of the grid are all surrounded by water. 8 | * 9 | * Execution: javac NumIslands.java && java NumIslands 10 | */ 11 | 12 | 13 | public class NumIslands{ 14 | private static int n; 15 | private static int m; 16 | 17 | public static int numIslands(char[][] grid) { 18 | int count = 0; 19 | n = grid.length; 20 | if (n == 0) return 0; 21 | m = grid[0].length; 22 | for (int i = 0; i < n; i++){ 23 | for (int j = 0; j < m; j++) 24 | if (grid[i][j] == '1') { 25 | DFSMarking(grid, i, j); 26 | ++count; 27 | } 28 | } 29 | return count; 30 | } 31 | 32 | public static void DFSMarking(char[][] grid, int i, int j) { 33 | if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return; 34 | grid[i][j] = '0'; 35 | DFSMarking(grid, i + 1, j); 36 | DFSMarking(grid, i - 1, j); 37 | DFSMarking(grid, i, j + 1); 38 | DFSMarking(grid, i, j - 1); 39 | } 40 | 41 | public static void main(String[] args) { 42 | char[][] testInput = new char[][]{ 43 | {'1', '1', '1', '1', '0'}, 44 | {'1', '1', '0', '1', '0'}, 45 | {'1', '1', '0', '0', '0'}, 46 | {'0', '0', '0', '0', '0'} 47 | }; 48 | assert numIslands(testInput) == 1; 49 | 50 | System.out.println("Passed all test cases"); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /module_2/python/max_depth_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Maximum depth of binary tree. 3 | 4 | Problem: 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root 8 | node down to the farthest leaf node. 9 | 10 | Note: A leaf is a node with no children. 11 | 12 | Execution: python max_depth_binary_tree.py 13 | """ 14 | import unittest 15 | 16 | 17 | class Node(): 18 | """Tree node class.""" 19 | def __init__(self, x): 20 | self.val = x 21 | self.left = None 22 | self.right = None 23 | 24 | class BinaryTree(): 25 | """Binary tree class.""" 26 | def __init__(self, root): 27 | self.root = Node(root) 28 | 29 | def max_depth_binary_tree(self, root): 30 | depth = 0 31 | level = [root] if root else [] 32 | while level: 33 | depth += 1 34 | queue = [] 35 | for el in level: 36 | if el.left: 37 | queue.append(el.left) 38 | if el.right: 39 | queue.append(el.right) 40 | level = queue 41 | return depth 42 | 43 | 44 | class TestMaxDepthBinaryTree(unittest.TestCase): 45 | """Unit test for max depth binary tree.""" 46 | 47 | def test_1(self): 48 | """ 49 | Given binary tree [3,9,20,null,null,15,7], 50 | 3 51 | / \ 52 | 9 20 53 | / \ 54 | 15 7 55 | """ 56 | tree = BinaryTree(3) 57 | tree.root.left = Node(9) 58 | tree.root.right = Node(20) 59 | tree.root.right.left = Node(15) 60 | tree.root.right.right = Node(7) 61 | self.assertEqual(tree.max_depth_binary_tree(tree.root), 3) 62 | 63 | 64 | if __name__ == '__main__': 65 | unittest.main() 66 | -------------------------------------------------------------------------------- /module_2/python/max_profit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Max profit 3 | 4 | Problem: 5 | Say you have an array for which the ith element is the price of a given 6 | stock on day i. 7 | 8 | If you were only permitted to complete at most one transaction (i.e., buy one 9 | and sell one share of the stock), design an algorithm to find the maximum 10 | profit. 11 | 12 | Note that you cannot sell a stock before you buy one. 13 | 14 | Execution: python max_profit.py 15 | """ 16 | import unittest 17 | from typing import List 18 | 19 | 20 | def max_profit(prices: List[int]): 21 | """Function for calculating the max profit.""" 22 | min_price = float("inf") 23 | max_profit = 0 24 | for i in range(len(prices)): 25 | if prices[i] < min_price: 26 | min_price = prices[i] 27 | elif prices[i] - min_price > max_profit: 28 | max_profit = prices[i] - min_price 29 | return max_profit 30 | 31 | 32 | class TestMaxProfit(unittest.TestCase): 33 | """Unit test for Max Profit.""" 34 | 35 | def test_1(self): 36 | test_input_1 = [7, 1, 5, 3, 6, 4] 37 | self.assertEqual(max_profit(test_input_1), 5) 38 | 39 | explanation = """ 40 | Explanation: Buy on day 2 (price = 1) and 41 | sell on day 5 (price = 6), profit = 6 - 1 = 5. 42 | """ 43 | print(explanation) 44 | 45 | def test_2(self): 46 | test_input_2 = [7, 6, 4, 3, 1] 47 | self.assertEqual(max_profit(test_input_2), 0) 48 | 49 | explanation = """ 50 | In this case, no transaction is done, i.e. max profit = 0. 51 | """ 52 | print(explanation) 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /module_2/python/maximum_subarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Maximum Sum Subarray 3 | 4 | Problem: 5 | Given an integer array nums, find the contiguous subarray (containing at 6 | least one number) which has the largest sum and return its sum. 7 | 8 | Execution: python max_sum_subarray.py 9 | """ 10 | import unittest 11 | from typing import List 12 | 13 | 14 | def maximum_subarray(nums: List[int]): 15 | """Function for calculating max sum in subarray. 16 | Brute force solution that takes O(n^2) time.""" 17 | max_val = float("-inf") 18 | 19 | for i in range(len(nums)): 20 | sum_val = 0 21 | for j in range(i, len(nums)): 22 | sum_val += nums[j] 23 | 24 | if sum_val > max_val: 25 | max_val = sum_val 26 | return max_val 27 | 28 | 29 | class TestMaximumSubarray(unittest.TestCase): 30 | """Unit test for maximum_subarray.""" 31 | 32 | def test_1(self): 33 | test_input_1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4] 34 | self.assertEqual(maximum_subarray(test_input_1), 6) 35 | print("Explanation: [4,-1,2,1] has the largest sum = 6.") 36 | 37 | 38 | if __name__ == '__main__': 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /module_2/python/merge_intervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Merge intervals 3 | 4 | Problem: Given a collection of intervals, merge all overlapping intervals. 5 | 6 | Execution: python merge_intervals.py 7 | """ 8 | import unittest 9 | from typing import List 10 | 11 | 12 | def merge_intervals(intervals: List[int]): 13 | """Function for merging intervals.""" 14 | intervals.sort(key=lambda interval: interval[0]) 15 | merged = [intervals[0]] 16 | for current in intervals: 17 | previous = merged[-1] 18 | if current[0] <= previous[1]: 19 | previous[1] = max(previous[1], current[1]) 20 | else: 21 | merged.append(current) 22 | return merged 23 | 24 | 25 | class TestMergeIntervals(unittest.TestCase): 26 | """Unit test for merge intervals problem.""" 27 | 28 | def test_1(self): 29 | test_input_1 = [[1,3],[2,6],[8,10],[15,18]] 30 | expected_output_1 = [[1,6],[8,10],[15,18]] 31 | self.assertEqual(merge_intervals(test_input_1), expected_output_1) 32 | print("Explanation:") 33 | print("Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].") 34 | 35 | def test_2(self): 36 | test_input_2 = [[1,4],[4,5]] 37 | expected_output_2 = [[1,5]] 38 | self.assertEqual(merge_intervals(test_input_2), expected_output_2) 39 | print("Explanation:") 40 | print("Intervals [1,4] and [4,5] are considered overlapping.") 41 | 42 | 43 | if __name__ == '__main__': 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /module_3/java/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Longest palindrome 3 | * 4 | * Problem: 5 | * 6 | * Given a string s, find the longest palindromic substring in s. You 7 | * may assume that the maximum length of s is 1000. 8 | * 9 | * Execution: javac LongestPalindrome.java && java LongestPalindrome 10 | */ 11 | 12 | 13 | public class LongestPalindrome { 14 | public static String longestPalindrome(String s) { 15 | String res = ""; 16 | int currLength = 0; 17 | for(int i=0; i Integer.compare(i1[0], i2[0])); 21 | 22 | List result = new ArrayList<>(); 23 | int[] newInterval = intervals[0]; 24 | result.add(newInterval); 25 | for (int[] interval : intervals) { 26 | if (interval[0] <= newInterval[1]) // Overlapping intervals, move the end if needed 27 | newInterval[1] = Math.max(newInterval[1], interval[1]); 28 | else { // Disjoint intervals, add the new interval to the list 29 | newInterval = interval; 30 | result.add(newInterval); 31 | } 32 | } 33 | 34 | return result.toArray(new int[result.size()][]); 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[][] testIn_1 = { { 1, 3 }, { 2, 6 }, {8, 10}, {15, 18} }; 39 | int[][] testOut_1 = { {1, 6}, {8, 10}, {15, 18} }; 40 | assert Arrays.equals(mergeIntervals(testIn_1), testOut_1); 41 | System.out.println("Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]."); 42 | 43 | int[][] testIn_2 = { { 1, 4 }, {4, 5} }; 44 | int[][] testOut_2 = { {1, 5} }; 45 | assert Arrays.equals(mergeIntervals(testIn_2), testOut_2); 46 | System.out.println("Explanation: Intervals [1,4] and [4,5] are considered overlapping."); 47 | 48 | 49 | System.out.println("Passed all test cases"); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /module_3/java/MergeKSorted.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Merge K sorted list 3 | * 4 | * Problem: Merge k sorted linked lists and return it as one sorted list. 5 | * Analyze and describe its complexity. 6 | * 7 | * Execution: javac MergeKSorted.java && java MergeKSorted 8 | */ 9 | import java.util.*; 10 | 11 | 12 | public class MergeKSorted { 13 | public static class ListNode { 14 | int val; 15 | ListNode next; 16 | ListNode(int x) { val = x; } 17 | } 18 | public static ListNode mergeKLists(ListNode[] lists) { 19 | if (lists==null || lists.length==0) return null; 20 | 21 | PriorityQueue queue= new PriorityQueue(lists.length, (a,b)-> a.val-b.val); 22 | 23 | ListNode dummy = new ListNode(0); 24 | ListNode tail=dummy; 25 | 26 | for (ListNode node:lists) 27 | if (node!=null) 28 | queue.add(node); 29 | 30 | while (!queue.isEmpty()){ 31 | tail.next=queue.poll(); 32 | tail=tail.next; 33 | 34 | if (tail.next!=null) 35 | queue.add(tail.next); 36 | } 37 | return dummy.next; 38 | } 39 | public static void main(String[] args) { 40 | 41 | ListNode test_1 = new ListNode(1); 42 | test_1.next = new ListNode(4); 43 | test_1.next.next = new ListNode(5); 44 | 45 | ListNode test_2 = new ListNode(1); 46 | test_2.next = new ListNode(3); 47 | test_2.next.next = new ListNode(4); 48 | 49 | ListNode test_3 = new ListNode(2); 50 | test_3.next = new ListNode(6); 51 | 52 | ListNode[] test_input = {test_1, test_2, test_3}; 53 | 54 | System.out.println(mergeKLists(test_input)); 55 | 56 | System.out.println("Passed all test cases"); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /module_3/java/Template.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: 3 | * 4 | * Problem: 5 | * 6 | * Execution: javac XX && java XX 7 | */ 8 | import java.util.*; 9 | 10 | 11 | public class Template { 12 | public static int template(String s) { 13 | } 14 | 15 | public static void main(String[] args) { 16 | assert template("abcabcbb") == 3; 17 | System.out.println("Explanation: "); 18 | 19 | System.out.println("Passed all test cases"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /module_3/python/longest_palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Longest palindrome 3 | 4 | Problem: 5 | Given a string s, find the longest palindromic substring in s. You may 6 | assume that the maximum length of s is 1000. 7 | 8 | Execution: python longest_palindrome.py 9 | """ 10 | import unittest 11 | 12 | 13 | def longest_palindrome(s: str): 14 | """Function for calculating longest palindrome.""" 15 | res = "" 16 | curr_length = 0 17 | for i in range(len(s)): 18 | if is_palindrome(s, i-curr_length-1, i): 19 | res = s[i-curr_length-1:i+1] 20 | curr_length = curr_length + 2 21 | elif is_palindrome(s, i-curr_length, i): 22 | res = s[i-curr_length:i+1] 23 | curr_length = curr_length + 1 24 | return res 25 | 26 | 27 | def is_palindrome(s: str, begin: int, end: int): 28 | """Helper function to check if string is palindrome.""" 29 | if begin < 0: 30 | return False 31 | while begin < end: 32 | if s[begin] != s[end]: 33 | return False 34 | begin += 1 35 | end -= 1 36 | return True 37 | 38 | 39 | class TestLongestPalindrome(unittest.TestCase): 40 | """Unit test for longest palindrome.""" 41 | 42 | def test_1(self): 43 | """Test for longest palindrome.""" 44 | test_palindrome = "babad" 45 | self.assertEqual(longest_palindrome(test_palindrome), "bab") 46 | print("Explanation: 'aba' is also a valid answer.") 47 | 48 | def test_2(self): 49 | """Test for longest palindrome.""" 50 | test_palindrome = "cbbd" 51 | self.assertEqual(longest_palindrome(test_palindrome), "bb") 52 | 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /module_3/python/lru_cache.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: LRU Cache 3 | 4 | Problem: 5 | Design and implement a data structure for Least Recently Used (LRU) 6 | cache. It should support the following operations: get and put. 7 | 8 | get(key) - Get the value (will always be positive) of the key if the key exists 9 | in the cache, otherwise return -1. put(key, value) - Set or insert the value 10 | if the key is not already present. When the cache reached its capacity, it 11 | should invalidate the least recently used item before inserting a new item. 12 | 13 | The cache is initialized with a positive capacity. 14 | 15 | Execution: python lru_cache.py 16 | """ 17 | from collections import OrderedDict 18 | 19 | import unittest 20 | 21 | 22 | class LRUCache(): 23 | def __init__(self, capacity: int): 24 | self._cache = OrderedDict() 25 | self._capacity = capacity 26 | 27 | def get(self, key: int) -> int: 28 | if key not in self._cache: 29 | return -1 30 | value = self._cache[key] 31 | self._cache.move_to_end(key) 32 | return value 33 | 34 | def put(self, key: int, value: int) -> None: 35 | if key in self._cache: 36 | del self._cache[key] 37 | self._cache[key] = value 38 | if len(self._cache) > self._capacity: 39 | self._cache.popitem(last=False) 40 | 41 | 42 | class TestLRUCache(unittest.TestCase): 43 | """Unit test for LRU cache.""" 44 | 45 | def test_1(self): 46 | cache = LRUCache(capacity=2) 47 | cache.put(1, 1) 48 | cache.put(2, 2) 49 | self.assertEqual(cache.get(1), 1) 50 | cache.put(3, 3) 51 | self.assertEqual(cache.get(2), -1) 52 | cache.put(4, 4) 53 | self.assertEqual(cache.get(1), -1) 54 | self.assertEqual(cache.get(3), 3) 55 | self.assertEqual(cache.get(4), 4) 56 | 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /module_3/python/max_depth_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Maximum depth of binary tree. 3 | 4 | Problem: 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root 8 | node down to the farthest leaf node. 9 | 10 | Note: A leaf is a node with no children. 11 | 12 | Execution: python max_depth_binary_tree.py 13 | """ 14 | import unittest 15 | 16 | 17 | class Node(): 18 | """Tree node class.""" 19 | def __init__(self, x): 20 | self.val = x 21 | self.left = None 22 | self.right = None 23 | 24 | class BinaryTree(): 25 | """Binary tree class.""" 26 | def __init__(self, root): 27 | self.root = Node(root) 28 | 29 | def max_depth_binary_tree(self, root): 30 | depth = 0 31 | level = [root] if root else [] 32 | while level: 33 | depth += 1 34 | queue = [] 35 | for el in level: 36 | if el.left: 37 | queue.append(el.left) 38 | if el.right: 39 | queue.append(el.right) 40 | level = queue 41 | return depth 42 | 43 | 44 | class TestMaxDepthBinaryTree(unittest.TestCase): 45 | """Unit test for max depth binary tree.""" 46 | 47 | def test_1(self): 48 | """ 49 | Given binary tree [3,9,20,null,null,15,7], 50 | 3 51 | / \ 52 | 9 20 53 | / \ 54 | 15 7 55 | """ 56 | tree = BinaryTree(3) 57 | tree.root.left = Node(9) 58 | tree.root.right = Node(20) 59 | tree.root.right.left = Node(15) 60 | tree.root.right.right = Node(7) 61 | self.assertEqual(tree.max_depth_binary_tree(tree.root), 3) 62 | 63 | 64 | if __name__ == '__main__': 65 | unittest.main() 66 | -------------------------------------------------------------------------------- /module_3/python/max_profit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Max profit 3 | 4 | Problem: 5 | Say you have an array for which the ith element is the price of a given 6 | stock on day i. 7 | 8 | If you were only permitted to complete at most one transaction (i.e., buy one 9 | and sell one share of the stock), design an algorithm to find the maximum 10 | profit. 11 | 12 | Note that you cannot sell a stock before you buy one. 13 | 14 | Execution: python max_profit.py 15 | """ 16 | import unittest 17 | from typing import List 18 | 19 | 20 | def max_profit(prices: List[int]): 21 | """Function for calculating the max profit.""" 22 | min_price = float("inf") 23 | max_profit = 0 24 | for i in range(len(prices)): 25 | if prices[i] < min_price: 26 | min_price = prices[i] 27 | elif prices[i] - min_price > max_profit: 28 | max_profit = prices[i] - min_price 29 | return max_profit 30 | 31 | 32 | class TestMaxProfit(unittest.TestCase): 33 | """Unit test for Max Profit.""" 34 | 35 | def test_1(self): 36 | test_input_1 = [7, 1, 5, 3, 6, 4] 37 | self.assertEqual(max_profit(test_input_1), 5) 38 | 39 | explanation = """ 40 | Explanation: Buy on day 2 (price = 1) and 41 | sell on day 5 (price = 6), profit = 6 - 1 = 5. 42 | """ 43 | print(explanation) 44 | 45 | def test_2(self): 46 | test_input_2 = [7, 6, 4, 3, 1] 47 | self.assertEqual(max_profit(test_input_2), 0) 48 | 49 | explanation = """ 50 | In this case, no transaction is done, i.e. max profit = 0. 51 | """ 52 | print(explanation) 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /module_3/python/maximum_subarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Maximum subarray. 3 | 4 | Problem: Given an integer array, nums, find the contiguous subarray (containing 5 | at least one number) which has the largest sum and return its sum. 6 | 7 | Execution: python maximum_subarray.py 8 | """ 9 | import unittest 10 | from typing import List 11 | 12 | 13 | def maximum_subarray(nums: List[int]): 14 | """Function for calculating the maximum subarray.""" 15 | if not nums: 16 | return 0 17 | 18 | cur_sum = max_sum = nums[0] 19 | for num in nums[1:]: 20 | cur_sum = max(num, cur_sum + num) 21 | max_sum = max(max_sum, cur_sum) 22 | return max_sum 23 | 24 | 25 | class TestMaximumSubarray(unittest.TestCase): 26 | """Unit test for calculating the maximum subarray.""" 27 | 28 | def test_1(self): 29 | test_input = [-2, 1, -3, 4, -1, 2, 1, -5, 4] 30 | self.assertEqual(maximum_subarray(test_input), 6) 31 | print("Explanation: [4, -1, 2, 1] has the largest sum = 6.") 32 | 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /module_3/python/merge_intervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Merge intervals 3 | 4 | Problem: Given a collection of intervals, merge all overlapping intervals. 5 | 6 | Execution: python merge_intervals.py 7 | """ 8 | import unittest 9 | from typing import List 10 | 11 | 12 | def merge_intervals(intervals: List[int]): 13 | """Function for merging intervals.""" 14 | intervals.sort(key=lambda interval: interval[0]) 15 | merged = [intervals[0]] 16 | for current in intervals: 17 | previous = merged[-1] 18 | if current[0] <= previous[1]: 19 | previous[1] = max(previous[1], current[1]) 20 | else: 21 | merged.append(current) 22 | return merged 23 | 24 | 25 | class TestMergeIntervals(unittest.TestCase): 26 | """Unit test for merge intervals problem.""" 27 | 28 | def test_1(self): 29 | test_input_1 = [[1,3],[2,6],[8,10],[15,18]] 30 | expected_output_1 = [[1,6],[8,10],[15,18]] 31 | self.assertEqual(merge_intervals(test_input_1), expected_output_1) 32 | print("Explanation:") 33 | print("Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].") 34 | 35 | def test_2(self): 36 | test_input_2 = [[1,4],[4,5]] 37 | expected_output_2 = [[1,5]] 38 | self.assertEqual(merge_intervals(test_input_2), expected_output_2) 39 | print("Explanation:") 40 | print("Intervals [1,4] and [4,5] are considered overlapping.") 41 | 42 | 43 | if __name__ == '__main__': 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /module_3/python/template.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: 3 | 4 | Problem: 5 | 6 | Execution: python XXX.py 7 | """ 8 | import unittest 9 | 10 | 11 | def template(s: str): 12 | """Function for .""" 13 | pass 14 | 15 | 16 | class TestXXX(unittest.TestCase): 17 | """Unit test for XXX.""" 18 | 19 | def test_1(self): 20 | """Test for .""" 21 | self.assertEqual(template("abcabcbb"), 3) 22 | print("Explanation: .") 23 | 24 | 25 | if __name__ == '__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /module_3/python/word_break.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Word break problem. 3 | 4 | Problem: 5 | Given a non-empty string s and a dictionary wordDict containing a list 6 | of non-empty words, determine if s can be segmented into a 7 | space-separated sequence of one or more dictionary words. 8 | 9 | Note: The same word in the dictionary may be reused multiple times in 10 | the segmentation. You may assume the dictionary does not contain 11 | duplicate words. 12 | 13 | Execution: python word_break.py 14 | """ 15 | import unittest 16 | from typing import List 17 | 18 | 19 | def word_break(s: str, word_dict: List[str]) -> bool: 20 | """Word break problem.""" 21 | n = len(s) 22 | dp = [False for i in range(n+1)] 23 | dp[0] = True 24 | for i in range(1, n+1): 25 | for w in word_dict: 26 | if dp[i - len(w)] and s[i - len(w):i] == w: 27 | dp[i] = True 28 | return dp[-1] 29 | 30 | 31 | class TestWordBreak(unittest.TestCase): 32 | """Unit test for word_break function.""" 33 | 34 | def test_1(self): 35 | test_input_str = "leetcode" 36 | test_input_dict = ["leet", "code"] 37 | self.assertEqual(word_break(test_input_str, test_input_dict), True) 38 | print("Explanation: Return 'true' because 'leetcode' can be segmented" 39 | "as 'leet code'.") 40 | 41 | def test_2(self): 42 | test_input_str = "applepenapple" 43 | test_input_dict = ["apple", "pen"] 44 | self.assertEqual(word_break(test_input_str, test_input_dict), True) 45 | print("Explanation: Return true because 'applepenapple' can be" 46 | "segmented as 'apple pen apple'. Note that you are allowed to" 47 | "reuse a dictionary word.") 48 | 49 | def test_3(self): 50 | test_input_str = "catsandog" 51 | test_input_dict = ["cats", "dog", "sand", "and", "cat"] 52 | self.assertEqual(word_break(test_input_str, test_input_dict), False) 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /module_4/java/FindMedian.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find median 3 | * 4 | * Problem: 5 | Median is the middle value in an ordered integer list. If the size of 6 | the list is even, there is no middle value. So the median is the mean 7 | of the two middle value. 8 | 9 | For example, [2,3,4], the median is 3 10 | 11 | [2,3], the median is (2 + 3) / 2 = 2.5 12 | 13 | Design a data structure that supports the following two operations: 14 | 15 | void addNum(int num) - Add a integer number from the data stream to the 16 | data structure. double findMedian() - Return the median of all elements so 17 | far. 18 | * 19 | * Execution: javac FindMedian.java && java FindMedian 20 | */ 21 | import java.util.*; 22 | 23 | 24 | public class FindMedian { 25 | List store; 26 | 27 | public FindMedian() { 28 | store = new ArrayList(); 29 | } 30 | 31 | public void addNum(int n) { 32 | store.add(n); 33 | } 34 | 35 | public double findMedian() { 36 | Collections.sort(store); 37 | int n = store.size(); 38 | if ((n & 1) == 1) { 39 | return store.get(n / 2); 40 | } else { 41 | return (store.get(n/2-1) + store.get(n/2))*0.5; 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | FindMedian obj = new FindMedian(); 47 | 48 | obj.addNum(1); 49 | obj.addNum(2); 50 | assert obj.findMedian() == 1.5; 51 | obj.addNum(3); 52 | assert obj.findMedian() == 2; 53 | 54 | System.out.println("Passed all test cases"); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /module_4/java/FirstMissingPositive.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: First missing positive. 3 | * 4 | * Problem: Given an unsorted integer array, find the smallest missing 5 | * positive integer. 6 | * 7 | * Execution: javac FirstMissingPositive.java && java FirstMissingPositive 8 | */ 9 | import java.util.*; 10 | 11 | 12 | public class FirstMissingPositive { 13 | 14 | public static int firstMissingPositive(int[] A) { 15 | for (int i = 0; i < A.length; i++) { 16 | if (A[i] <= 0 || A[i] > A.length) A[i] = Integer.MAX_VALUE; 17 | } 18 | 19 | for (int i = 0; i < A.length; i++) { 20 | int abs = Math.abs(A[i]); 21 | if (abs <= A.length) A[abs-1] = -Math.abs(A[abs-1]); 22 | } 23 | 24 | for (int i = 0; i < A.length; i++) { 25 | if (A[i] > 0) return i+1; 26 | } 27 | 28 | return A.length+1; 29 | } 30 | 31 | // Alternate implementation 32 | public static int firstMissingPositiveAlt(int[] A) { 33 | int i = 0; 34 | while(i < A.length){ 35 | if(A[i] == i+1 || A[i] <= 0 || A[i] > A.length) i++; 36 | else if(A[A[i]-1] != A[i]) swap(A, i, A[i]-1); 37 | else i++; 38 | } 39 | i = 0; 40 | while(i < A.length && A[i] == i+1) i++; 41 | return i+1; 42 | } 43 | 44 | private static void swap(int[] A, int i, int j){ 45 | int temp = A[i]; 46 | A[i] = A[j]; 47 | A[j] = temp; 48 | } 49 | 50 | public static void main(String[] args) { 51 | int[] test_input_1 = {1, 2, 0}; 52 | assert firstMissingPositive(test_input_1) == 3; 53 | 54 | int[] test_input_2 = {3, 4, -1, 1}; 55 | assert firstMissingPositive(test_input_2) == 2; 56 | 57 | int[] test_input_3 = {7, 8, 9, 11, 12}; 58 | assert firstMissingPositive(test_input_3) == 1; 59 | 60 | System.out.println("Passed all test cases"); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /module_4/java/HammingWeight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Write a function that takes an unsigned integer and return the 3 | * number of '1' bits it has (also known as the Hamming weight). 4 | * 5 | * Problem: Calculate Hamming Weight 6 | * 7 | * Execution: javac HammingWeight.java && java HammingWeight 8 | */ 9 | 10 | 11 | public class HammingWeight { 12 | public static int hammingWeight(int n) { 13 | int sum = 0; 14 | while (n != 0) { 15 | sum++; 16 | n &= (n - 1); 17 | } 18 | return sum; 19 | } 20 | 21 | public static void main(String[] args) { 22 | 23 | int testInput1 = Integer.parseInt("00000000000000000000000000001011"); 24 | assert hammingWeight(testInput1) == 3; 25 | System.out.println("The input binary string 00000000000000000000000000001011 has a total of three '1' bits."); 26 | 27 | int testInput2 = Integer.parseInt("00000000000000000000000010000000"); 28 | assert hammingWeight(testInput2) == 1; 29 | System.out.println("The input binary string 00000000000000000000000010000000 has a total of one '1' bit."); 30 | 31 | System.out.println("Passed all test cases"); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /module_4/java/LengthOfLongestSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Longest substring without repeating characters. 3 | * 4 | * Given a string, find the length of the longest substring without repeating characters. 5 | * 6 | * Execution: javac LengthOfLongestSubstring && java LengthOfLongestSubstring 7 | */ 8 | 9 | import java.util.HashMap; 10 | 11 | public class LengthOfLongestSubstring { 12 | public static long lengthOfLongestSubstring(String s) { 13 | int n = s.length(), ans = 0; 14 | 15 | // Current index of character. 16 | int[] index = new int[128]; 17 | 18 | // Attempt to extend the range. 19 | int i = 0; 20 | for (int j = 0; j < n; j++) { 21 | i = Math.max(index[s.charAt(j)], i); 22 | ans = Math.max(ans, j - 1 + 1); 23 | index[s.charAt(j)] = j + 1; 24 | } 25 | return ans; 26 | } 27 | 28 | // Sample test cases 29 | public static void main(String[] args) { 30 | assert lengthOfLongestSubstring("abcabcbb") == 3; 31 | System.out.println("Explanation: The answer is 'abc', with the length of 3."); 32 | 33 | assert lengthOfLongestSubstring("bbbbb") == 1; 34 | System.out.println("Explanation: The answer is 'b', with the length of 1."); 35 | 36 | assert lengthOfLongestSubstring("pwwkew") == 3; 37 | System.out.println("Explanation: The answer is 'wke', with the length 3. Note that the answer must be a substring, 'pwke' is a subsequence and not a substring."); 38 | 39 | System.out.println("Passed all test cases"); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /module_4/java/MissingNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Missing number 3 | * 4 | * Problem:Given an array containing n distinct numbers taken from 0, 1, 2, 5 | * ..., n, find the one that is missing from the array. 6 | * 7 | * Execution: javac MissingNumber.java && java MissingNumber 8 | */ 9 | import java.util.*; 10 | 11 | 12 | public class MissingNumber { 13 | public static int missingNumber(int[] nums) { 14 | Arrays.sort(nums); 15 | 16 | // Ensure that n is at the last index 17 | if (nums[nums.length-1] != nums.length) { 18 | return nums.length; 19 | } 20 | // Ensure that 0 is at the first index 21 | else if (nums[0] != 0) { 22 | return 0; 23 | } 24 | 25 | // If we get here, then the missing number is on the range (0, n) 26 | for (int i = 1; i < nums.length; i++) { 27 | int expectedNum = nums[i-1] + 1; 28 | if (nums[i] != expectedNum) { 29 | return expectedNum; 30 | } 31 | } 32 | 33 | // Array was not missing any numbers 34 | return -1; 35 | } 36 | public static void main(String[] args) { 37 | int[] test_input_1 = {3, 0, 1}; 38 | assert missingNumber(test_input_1) == 2; 39 | 40 | int[] test_input_2 = {9, 6, 4, 2, 3, 5, 7, 0, 1}; 41 | assert missingNumber(test_input_2) == 8; 42 | 43 | System.out.println("Passed all test cases"); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /module_4/java/SplitArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Split array 3 | * 4 | * Problem: 5 | * Given an array which consists of non-negative integers and an integer m, 6 | * you can split the array into m non-empty continuous subarrays. Write an 7 | * algorithm to minimize the largest sum among these m subarrays. 8 | 9 | Note: If n is the length of array, assume the following constraints are 10 | satisfied: 11 | 12 | 1 ≤ n ≤ 1000 1 ≤ m ≤ min(50, n) 13 | * 14 | * Execution: javac SplitArray.java && java SplitArray 15 | */ 16 | import java.util.*; 17 | 18 | 19 | public class SplitArray { 20 | public static int splitArray(int[] nums, int m) { 21 | int max = 0; long sum = 0; 22 | for (int num : nums) { 23 | max = Math.max(num, max); 24 | sum += num; 25 | } 26 | if (m == 1) return (int)sum; 27 | //binary search 28 | long l = max; long r = sum; 29 | while (l <= r) { 30 | long mid = (l + r)/ 2; 31 | if (valid(mid, nums, m)) { 32 | r = mid - 1; 33 | } else { 34 | l = mid + 1; 35 | } 36 | } 37 | return (int)l; 38 | } 39 | public static boolean valid(long target, int[] nums, int m) { 40 | int count = 1; 41 | long total = 0; 42 | for(int num : nums) { 43 | total += num; 44 | if (total > target) { 45 | total = num; 46 | count++; 47 | if (count > m) { 48 | return false; 49 | } 50 | } 51 | } 52 | return true; 53 | } 54 | public static void main(String[] args) { 55 | int[] nums = {7, 2, 5, 10, 8}; 56 | int m = 2; 57 | assert splitArray(nums, m) == 18; 58 | 59 | System.out.println("Passed all test cases"); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /module_4/java/Template.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: 3 | * 4 | * Problem: 5 | * 6 | * Execution: javac XX && java XX 7 | */ 8 | import java.util.*; 9 | 10 | 11 | public class Template { 12 | public static int template(String s) { 13 | } 14 | 15 | public static void main(String[] args) { 16 | assert template("abcabcbb") == 3; 17 | System.out.println("Explanation: "); 18 | 19 | System.out.println("Passed all test cases"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /module_4/java/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Three Sum 3 | * 4 | * Problem: 5 | Given an array nums of n integers, are there elements a, b, c in nums such 6 | that a + b + c = 0? Find all unique triplets in the array which gives the 7 | sum of zero. 8 | 9 | Note: 10 | 11 | The solution set must not contain duplicate triplets. 12 | * 13 | * Execution: javac ThreeSum.java && java ThreeSum 14 | */ 15 | import java.util.*; 16 | 17 | 18 | public class ThreeSum { 19 | 20 | public static List> threeSum(int[] num) { 21 | Arrays.sort(num); 22 | List> res = new LinkedList<>(); 23 | for (int i = 0; i < num.length-2; i++) { 24 | if (i == 0 || (i > 0 && num[i] != num[i-1])) { 25 | int lo = i+1, hi = num.length-1, sum = 0 - num[i]; 26 | while (lo < hi) { 27 | if (num[lo] + num[hi] == sum) { 28 | res.add(Arrays.asList(num[i], num[lo], num[hi])); 29 | while (lo < hi && num[lo] == num[lo+1]) lo++; 30 | while (lo < hi && num[hi] == num[hi-1]) hi--; 31 | lo++; hi--; 32 | } else if (num[lo] + num[hi] < sum) lo++; 33 | else hi--; 34 | } 35 | } 36 | } 37 | return res; 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] nums = {-1, 0, 1, 2, -1, -4}; 42 | 43 | /* A solution set is: 44 | [ 45 | [-1, 0, 1], 46 | [-1, -1, 2] 47 | ] 48 | */ 49 | System.out.println(threeSum(nums)); 50 | 51 | System.out.println("Passed all test cases"); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /module_4/python/find_median.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find median 3 | 4 | Problem: 5 | Median is the middle value in an ordered integer list. If the size of the 6 | list is even, there is no middle value. So the median is the mean of the 7 | two middle value. 8 | 9 | For example, [2,3,4], the median is 3 10 | 11 | [2,3], the median is (2 + 3) / 2 = 2.5 12 | 13 | Design a data structure that supports the following two operations: 14 | 15 | void addNum(int num) - Add a integer number from the data stream to the 16 | data structure. double findMedian() - Return the median of all elements so 17 | far. 18 | 19 | Execution: python find_median.py 20 | """ 21 | import unittest 22 | 23 | 24 | class FindMedian: 25 | def __init__(self) -> None: 26 | """Initialize median data structure.""" 27 | self._store = [] 28 | 29 | def add_num(self, num: int) -> None: 30 | """ Add number to median data structure.""" 31 | self._store.append(num) 32 | 33 | def find_median(self) -> float: 34 | """Find median.""" 35 | self._store.sort() 36 | n = len(self._store) 37 | if n & 1: 38 | return self._store[n//2] 39 | else: 40 | return (self._store[n//2 - 1] + self._store[n//2]) * 0.5 41 | 42 | 43 | class TestFindMedian(unittest.TestCase): 44 | """Unit test for find_median.""" 45 | 46 | def test_1(self): 47 | x = FindMedian() 48 | x.add_num(1) 49 | x.add_num(2) 50 | self.assertEqual(x.find_median(), 1.5) 51 | x.add_num(3) 52 | self.assertEqual(x.find_median(), 2) 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /module_4/python/first_missing_positive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: First missing number 3 | 4 | Problem: Given an unsorted integer array, find the smallest missing positive 5 | integer. 6 | 7 | 8 | Execution: python first_missing_positive.py 9 | """ 10 | import unittest 11 | from typing import List 12 | 13 | 14 | def first_missing_positive(nums: List[int]): 15 | for i in range(len(nums)): 16 | if nums[i] <= 0 or nums[i] > len(nums): 17 | nums[i] = float('inf') 18 | 19 | for i in range(len(nums)): 20 | absolute_value = abs(nums[i]) 21 | if absolute_value <= len(nums): 22 | nums[absolute_value-1] = -abs(nums[absolute_value-1]) 23 | 24 | for i in range(len(nums)): 25 | if nums[i] > 0: 26 | return i+1 27 | 28 | return len(nums)+1 29 | 30 | # A slightly different implementation 31 | def first_missing_positive_alt(nums: List[int]): 32 | """First missing positive position.""" 33 | nums.append(0) 34 | n = len(nums) 35 | 36 | for i in range(len(nums)): 37 | # Delete useless elements. 38 | if nums[i] < 0 or nums[i] >= n: 39 | nums[i] = 0 40 | for i in range(len(nums)): 41 | # Use the index as the hash to record frequency of each number. 42 | nums[nums[i] % n] += n 43 | for i in range(1, len(nums)): 44 | if nums[i]/n == 0: 45 | return i 46 | return n 47 | 48 | 49 | class TestFirstMissingPositive(unittest.TestCase): 50 | """Unit test for first_missing_positive.""" 51 | 52 | def test_1(self): 53 | self.assertEqual(first_missing_positive([1, 2, 0]), 3) 54 | 55 | def test_2(self): 56 | self.assertEqual(first_missing_positive([3, 4, -1, 1]), 2) 57 | 58 | def test_3(self): 59 | self.assertEqual(first_missing_positive([7, 8, 9, 11, 12]), 1) 60 | 61 | 62 | if __name__ == '__main__': 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /module_4/python/hamming_weight.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Calculate the Hamming weight. 3 | 4 | Problem: Write a function that takes an unsigned integer and return the number 5 | of '1' bits it has (also known as the Hamming weight). 6 | 7 | Execution: python hamming_weight.py 8 | """ 9 | import unittest 10 | 11 | 12 | def hamming_weight(n: int): 13 | """Function for calculating the Hamming weight.""" 14 | sum_val = 0 15 | while n != 0: 16 | sum_val += 1 17 | n &= (n - 1) 18 | return sum_val 19 | 20 | 21 | class TestHammingWeight(unittest.TestCase): 22 | """Unit test for Hamming weight.""" 23 | 24 | def test_1(self): 25 | input_val = "00000000000000000000000000001011" 26 | self.assertEqual(hamming_weight(int(input_val, 2)), 3) 27 | output = """ 28 | The input binary string 00000000000000000000000000001011 has a total of 29 | three '1' bits. 30 | """ 31 | print(f"Explanation: {output}") 32 | 33 | def test_2(self): 34 | input_val = "00000000000000000000000010000000" 35 | self.assertEqual(hamming_weight(int(input_val, 2)), 1) 36 | output = """ 37 | The input binary string 00000000000000000000000010000000has a total of 38 | one '1' bit. 39 | """ 40 | print(f"Explanation: {output}") 41 | 42 | def test_3(self): 43 | input_val = "11111111111111111111111111111101" 44 | self.assertEqual(hamming_weight(int(input_val, 2)), 31) 45 | output = """ 46 | The input binary string 11111111111111111111111111111101 has a total of 47 | thirty-one '1' bits. 48 | """ 49 | print(f"Explanation: {output}") 50 | 51 | 52 | if __name__ == '__main__': 53 | unittest.main() 54 | 55 | -------------------------------------------------------------------------------- /module_4/python/length_of_longest_substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Longest substring without repeating characters. 3 | 4 | Given a string, find the length of the longest substring without repeating characters. 5 | 6 | Execution: python length_of_longest_substring.py 7 | """ 8 | import unittest 9 | 10 | 11 | def length_of_longest_substring(s: str): 12 | """Given a string, determine the length of the longest substring.""" 13 | last, res, st = dict(), 0, 0 14 | for i, v in enumerate(s): 15 | if v not in last or last[v] < st: 16 | res = max(res, i - st + 1) 17 | else: 18 | st = last[v] + 1 19 | last[v] = i 20 | return res 21 | 22 | 23 | class TestLengthOfLongestSubstring(unittest.TestCase): 24 | """Unit tests for length_of_longest_substring.""" 25 | 26 | def test_1(self): 27 | """Test for string: abcabcbb.""" 28 | self.assertEqual(length_of_longest_substring("abcabcbb"), 3) 29 | print("Explanation: The answer is 'abc', with the length of 3.") 30 | 31 | def test_2(self): 32 | """Test for string: bbbbb.""" 33 | self.assertEqual(length_of_longest_substring("bbbbb"), 1) 34 | print("Explanation: The answer is 'b', with the length of 1.") 35 | 36 | def test_3(self): 37 | """Test for string: pwwkew.""" 38 | self.assertEqual(length_of_longest_substring("pwwkew"), 3) 39 | print("Explanation: The answer is 'wke', with the length 3.") 40 | print("Note that the answer must be a substring, 'pwke' ") 41 | print("is a subsequence and not a substring.") 42 | 43 | 44 | if __name__ == '__main__': 45 | unittest.main() 46 | -------------------------------------------------------------------------------- /module_4/python/missing_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Missing number 3 | 4 | Problem: 5 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., 6 | n, find the one that is missing from the array. 7 | 8 | 9 | Execution: python missing_number.py 10 | """ 11 | import unittest 12 | from typing import List 13 | 14 | 15 | def missing_number(nums: List[int]) -> int: 16 | """Find missing number.""" 17 | nums.sort() 18 | 19 | # Ensure that n is at the last index 20 | if nums[-1] != len(nums): 21 | return len(nums) 22 | # Ensure that 0 is at the first index 23 | elif nums[0] != 0: 24 | return 0 25 | 26 | # If we get here, then the missing number is on the range (0, n) 27 | for i in range(1, len(nums)): 28 | expected_num = nums[i-1] + 1 29 | if nums[i] != expected_num: 30 | return expected_num 31 | 32 | 33 | class TestFindMissingNumber(unittest.TestCase): 34 | """Unit test for find_missing_number.""" 35 | 36 | def test_1(self): 37 | test_1_input = [3, 0, 1] 38 | self.assertEqual(missing_number(test_1_input), 2) 39 | 40 | def test_2(self): 41 | test_2_input = [9, 6, 4, 2, 3, 5, 7, 0, 1] 42 | self.assertEqual(missing_number(test_2_input), 8) 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /module_4/python/random_node.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Linked list random node 3 | 4 | Problem: 5 | Given a singly linked list, return a random node's value from the linked 6 | list. Each node must have the same probability of being chosen. 7 | 8 | Follow up: What if the linked list is extremely large and its length is 9 | unknown to you? Could you solve this efficiently without using extra space? 10 | 11 | Execution: python random_node.py 12 | """ 13 | from random import random 14 | import unittest 15 | 16 | 17 | class ListNode: 18 | def __init__(self, x: int) -> None: 19 | self.val = x 20 | self.next = None 21 | 22 | 23 | class LinkedList(): 24 | def __init__(self, head: ListNode) -> None: 25 | self.head = head 26 | 27 | def get_random(self) -> int: 28 | cur_node = self.head 29 | counter = 1 30 | choice = -1 31 | 32 | while cur_node is not None: 33 | if random() < 1/counter: 34 | choice = cur_node.val 35 | cur_node = cur_node.next 36 | counter += 1 37 | return choice 38 | 39 | def check_random_node(self, node_val: int) -> bool: 40 | return node_val in [1, 2, 3] 41 | 42 | 43 | 44 | class TestRandomNode(unittest.TestCase): 45 | """Unit test for get_random.""" 46 | 47 | def test_1(self): 48 | head = ListNode(1) 49 | head.next = ListNode(2) 50 | head.next.next = ListNode(3) 51 | 52 | ll = LinkedList(head) 53 | self.assertEqual(ll.check_random_node(ll.get_random()), True) 54 | print("Explanation: .") 55 | 56 | 57 | if __name__ == '__main__': 58 | unittest.main() 59 | -------------------------------------------------------------------------------- /module_4/python/sort_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Sort list 3 | 4 | Problem: Sort a linked list in O(n log n) time using constant space complexity. 5 | 6 | 7 | Execution: python sort_list.py 8 | """ 9 | import unittest 10 | 11 | 12 | class ListNode: 13 | """Definition for singly-linked list.""" 14 | 15 | def __init__(self, x: int): 16 | """Set value and next for ListNode.""" 17 | self.val = x 18 | self.next = None 19 | 20 | 21 | def merge(h1: ListNode, h2: ListNode) -> ListNode: 22 | """Merge two ListNode objects.""" 23 | dummy = tail = ListNode(None) 24 | while h1 and h2: 25 | if h1.val < h2.val: 26 | tail.next, tail, h1 = h1, h1, h1.next 27 | else: 28 | tail.next, tail, h2 = h2, h2, h2.next 29 | 30 | tail.next = h1 or h2 31 | return dummy.next 32 | 33 | 34 | def sort_list(head: ListNode) -> ListNode: 35 | """Sort ListNode objects.""" 36 | if not head or not head.next: 37 | return head 38 | 39 | pre, slow, fast = None, head, head 40 | while fast and fast.next: 41 | pre, slow, fast = slow, slow.next, fast.next.next 42 | pre.next = None 43 | 44 | return merge(*map(sort_list, (head, slow))) 45 | 46 | 47 | def compare_lists(l1: ListNode, l2: ListNode) -> bool: 48 | """Compare equality between two ListNode objects.""" 49 | while l1: 50 | if l1.val != l2.val: 51 | return False 52 | l1 = l1.next 53 | l2 = l2.next 54 | return True 55 | 56 | 57 | class TestSortList(unittest.TestCase): 58 | """Unit test for sort_list.""" 59 | 60 | def test_1(self): 61 | ll = ListNode(4) 62 | ll.next = ListNode(2) 63 | ll.next.next = ListNode(1) 64 | ll.next.next.next = ListNode(3) 65 | 66 | out_ll = ListNode(1) 67 | out_ll.next = ListNode(2) 68 | out_ll.next.next = ListNode(3) 69 | out_ll.next.next.next = ListNode(4) 70 | 71 | self.assertEqual(compare_lists(sort_list(ll), out_ll), True) 72 | 73 | 74 | if __name__ == '__main__': 75 | unittest.main() 76 | -------------------------------------------------------------------------------- /module_4/python/split_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Split array 3 | 4 | Problem: 5 | Given an array which consists of non-negative integers and an integer m, 6 | you can split the array into m non-empty continuous subarrays. Write an 7 | algorithm to minimize the largest sum among these m subarrays. 8 | 9 | Note: If n is the length of array, assume the following constraints are 10 | satisfied: 11 | 12 | 1 ≤ n ≤ 1000 1 ≤ m ≤ min(50, n) 13 | 14 | Execution: python split_array.py 15 | """ 16 | import unittest 17 | from typing import List 18 | 19 | 20 | def split_array(nums: List[int], m: int) -> int: 21 | """Split array from index m.""" 22 | max_val, sum_val = 0, 0 23 | for num in nums: 24 | max_val = max(num, max_val) 25 | sum_val += num 26 | if m == 1: 27 | return sum_val 28 | 29 | # Perform binary search: 30 | left, right = max_val, sum_val 31 | while left <= right: 32 | mid = (left + right) // 2 33 | if is_valid(mid, nums, m): 34 | right = mid - 1 35 | else: 36 | left = mid + 1 37 | return left 38 | 39 | 40 | def is_valid(target: int, nums: List[int], m: int): 41 | """Check if entry is valid in array.""" 42 | count, total = 1, 0 43 | for num in nums: 44 | total += num 45 | if total > target: 46 | total = num 47 | count += 1 48 | if count > m: 49 | return False 50 | return True 51 | 52 | 53 | class TestSplitArray(unittest.TestCase): 54 | """Unit test for split_array.""" 55 | 56 | def test_1(self): 57 | """ 58 | There are four ways to split nums into two subarrays. 59 | The best way is to split it into [7,2,5] and [10,8], 60 | where the largest sum among the two subarrays is only 18. 61 | """ 62 | nums = [7, 2, 5, 10, 8] 63 | m = 2 64 | self.assertEqual(split_array(nums, m), 18) 65 | 66 | 67 | if __name__ == '__main__': 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /module_4/python/template.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: 3 | 4 | Problem: 5 | 6 | Execution: python XXX.py 7 | """ 8 | import unittest 9 | 10 | 11 | def template(s: str): 12 | """Function for .""" 13 | pass 14 | 15 | 16 | class TestXXX(unittest.TestCase): 17 | """Unit test for XXX.""" 18 | 19 | def test_1(self): 20 | """Test for .""" 21 | self.assertEqual(template("abcabcbb"), 3) 22 | print("Explanation: .") 23 | 24 | 25 | if __name__ == '__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /module_5/java/CoinChange.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Coin change 3 | * 4 | * Problem: You are given coins of different denominations and a total amount 5 | * of money amount. Write a function to compute the fewest number of coins 6 | * that you need to make up that amount. If that amount of money cannot be 7 | * made up by any combination of the coins, return -1. 8 | * 9 | * Execution: javac XX && java XX 10 | */ 11 | 12 | 13 | public class CoinChange { 14 | public static int coinChange(int[] coins, int amount) { 15 | if (amount < 1) return 0; 16 | return coinChange(coins, amount, new int[amount]); 17 | } 18 | 19 | private static int coinChange(int[] coins, int rem, int[] count) { 20 | if (rem < 0) return -1; 21 | if (rem == 0) return 0; 22 | if (count[rem - 1] != 0) return count[rem - 1]; 23 | int min = Integer.MAX_VALUE; 24 | for (int coin : coins) { 25 | int res = coinChange(coins, rem - coin, count); 26 | if (res >= 0 && res < min) 27 | min = 1 + res; 28 | } 29 | count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min; 30 | return count[rem - 1]; 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | int[] testInputCoins1 = {1, 2, 5}; 36 | int testAmount1 = 11; 37 | assert coinChange(testInputCoins1, testAmount1) == 3; 38 | System.out.println("Explanation: 11 = 5 + 5 + 1"); 39 | 40 | int[] testInputCoins2 = {2}; 41 | int testAmount2 = 3; 42 | assert coinChange(testInputCoins1, testAmount1) == -1; 43 | 44 | System.out.println("Passed all test cases"); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /module_5/java/MaxArea.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Container with Most Water 3 | * 4 | * Problem: 5 | * Given n non-negative integers a1, a2, ..., an , where each represents a 6 | * point at coordinate (i, ai). n vertical lines are drawn such that the two 7 | * endpoints of line i is at (i, ai) and (i, 0). Find two lines, which 8 | * together with x-axis forms a container, such that the container contains 9 | * the most water. 10 | 11 | Note: You may not slant the container and n is at least 2. 12 | * 13 | * Execution: javac MaxArea.java && java MaxArea 14 | */ 15 | import java.util.*; 16 | 17 | 18 | public class MaxArea { 19 | 20 | public static int maxAreaBruteForce(int[] height) { 21 | int maxarea = 0; 22 | for (int i = 0; i < height.length; i++) 23 | for (int j = i + 1; j < height.length; j++) 24 | maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i)); 25 | return maxarea; 26 | } 27 | 28 | public static int maxAreaPointer(int[] height) { 29 | int maxarea = 0, l = 0, r = height.length - 1; 30 | while (l < r) { 31 | maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l)); 32 | if (height[l] < height[r]) 33 | l++; 34 | else 35 | r--; 36 | } 37 | return maxarea; 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] test_input = {1, 8, 6, 2, 5, 4, 8, 3, 7}; 42 | assert maxAreaBruteForce(test_input) == 49; 43 | assert maxAreaPointer(test_input) == 49; 44 | 45 | System.out.println("Passed all test cases"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /module_5/java/MaxPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Max path sum. 3 | * 4 | * Problem: 5 | * Given a non-empty binary tree, find the maximum path sum. 6 | 7 | For this problem, a path is defined as any sequence of nodes from some starting 8 | node to any node in the tree along the parent-child connections. The path must 9 | contain at least one node and does not need to go through the root. 10 | * 11 | * Execution: javac MaxPathSum.java && java MaxPathSum 12 | */ 13 | import java.util.*; 14 | 15 | 16 | public class MaxPathSum { 17 | 18 | public static class TreeNode { 19 | int val; 20 | TreeNode left; 21 | TreeNode right; 22 | TreeNode(int x) { val = x; } 23 | } 24 | 25 | public static int maxPathSum(TreeNode root) { 26 | int[] max = {Integer.MIN_VALUE}; 27 | maxPathSumRecursive(root, max); 28 | return max[0]; 29 | 30 | } 31 | 32 | private static int maxPathSumRecursive(TreeNode root, int[] max) { 33 | if (root == null) { 34 | return 0; 35 | } 36 | 37 | int left = Math.max(maxPathSumRecursive(root.left, max), 0); 38 | int right = Math.max(maxPathSumRecursive(root.right, max), 0); 39 | 40 | max[0] = Math.max(max[0], root.val + left + right); 41 | 42 | return root.val + Math.max(left, right); 43 | } 44 | 45 | public static void main(String[] args) { 46 | 47 | TreeNode tree1 = new TreeNode(1); 48 | tree1.left = new TreeNode(2); 49 | tree1.right = new TreeNode(3); 50 | 51 | assert maxPathSum(tree1) == 6; 52 | 53 | TreeNode tree2 = new TreeNode(-10); 54 | tree2.left = new TreeNode(9); 55 | tree2.right = new TreeNode(20); 56 | tree2.right.left = new TreeNode(15); 57 | tree2.right.right = new TreeNode(7); 58 | 59 | assert maxPathSum(tree2) == 42; 60 | 61 | System.out.println("Passed all test cases"); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /module_5/java/MaxRectangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Max rectangle 3 | * 4 | * Problem: 5 | * Given a 2D binary matrix filled with 0's and 1's, find the largest 6 | * rectangle containing only 1's and return its area. 7 | * 8 | * Execution: javac MaxRectangle.java && java MaxRectangle 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class MaxRectangle { 14 | 15 | public static int maxRectangle(char[][] matrix) { 16 | if (matrix.length <= 0) { 17 | return 0; 18 | } 19 | int n = matrix.length; 20 | int m = matrix[0].length; 21 | int[][] dp = new int[n][m]; 22 | int maxArea = 0; 23 | 24 | for (int i = 0; i < n; i++) { 25 | for (int j = 0; j < m; j++) { 26 | if (i == 0) { 27 | dp[i][j] = matrix[i][j] == '1' ? 1 : 0; 28 | } 29 | else { 30 | dp[i][j] = matrix[i][j] == '1' ? (dp[i-1][j] + 1) : 0; 31 | } 32 | int min = dp[i][j]; 33 | 34 | for (int k = j; k >= 0; k--) { 35 | if (min == 0) { 36 | break; 37 | } 38 | if (dp[i][k] < min) { 39 | min = dp[i][k]; 40 | } 41 | maxArea = Math.max(maxArea, min * (j - k + 1)); 42 | } 43 | } 44 | } 45 | return maxArea; 46 | } 47 | 48 | public static void main(String[] args) { 49 | char[][] matrix = { {'1', '0', '1', '0', '0'}, 50 | {'1', '0', '1', '1', '1'}, 51 | {'1', '1', '1', '1', '1'}, 52 | {'1', '0', '0', '1', '0'}}; 53 | assert maxRectangle(matrix) == 6; 54 | 55 | System.out.println("Passed all test cases"); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /module_5/java/Template.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: 3 | * 4 | * Problem: 5 | * 6 | * Execution: javac XX && java XX 7 | */ 8 | import java.util.*; 9 | 10 | 11 | public class Template { 12 | public static int template(String s) { 13 | } 14 | 15 | public static void main(String[] args) { 16 | assert template("abcabcbb") == 3; 17 | System.out.println("Explanation: "); 18 | 19 | System.out.println("Passed all test cases"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /module_5/python/coin_change.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Coin change problem. 3 | 4 | Problem: You are given coins of different denominations and a total amount of 5 | money amount. Write a function to compute the fewest number of coins that you 6 | need to make up that amount. If that amount of money cannot be made up by any 7 | combination of the coins, return -1. 8 | 9 | Execution: python coin_change.py 10 | """ 11 | import unittest 12 | from typing import List 13 | 14 | 15 | def coin_change(coins: List[int], amount: int): 16 | """Function for generating coin change.""" 17 | if amount < 1: 18 | return 0 19 | return coin_change_recur(coins, amount, [0]*amount) 20 | 21 | 22 | def coin_change_recur(coins: List[int], rem: int, count: List[int]): 23 | if rem < 0: 24 | return -1 25 | if rem == 0: 26 | return 0 27 | if count[rem - 1] != 0: 28 | return count[rem - 1] 29 | min_val = float("inf") 30 | for coin in coins: 31 | res = coin_change_recur(coins, rem - coin, count) 32 | if res >= 0 and res < min_val: 33 | min_val = 1 + res 34 | if min_val == float("inf"): 35 | count[rem - 1] = -1 36 | else: 37 | count[rem - 1] = min_val 38 | return count[rem - 1] 39 | 40 | 41 | class TestCoinChange(unittest.TestCase): 42 | """Unit test for CoinChange.""" 43 | 44 | def test_1(self): 45 | self.assertEqual(coin_change(coins=[1, 2, 5], amount=11), 3) 46 | 47 | def test_2(self): 48 | self.assertEqual(coin_change(coins=[2], amount=3), -1) 49 | 50 | 51 | if __name__ == '__main__': 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /module_5/python/max_area.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Contain with Most Water 3 | 4 | Problem: 5 | Given n non-negative integers a1, a2, ..., an , where each represents a 6 | point at coordinate (i, ai). n vertical lines are drawn such that the two 7 | endpoints of line i is at (i, ai) and (i, 0). Find two lines, which 8 | together with x-axis forms a container, such that the container contains 9 | the most water. 10 | 11 | Note: You may not slant the container and n is at least 2. 12 | 13 | Execution: python max_area.py 14 | """ 15 | import unittest 16 | from typing import List 17 | 18 | 19 | def max_area(height: List[int]): 20 | max_area = 0 21 | for i in range(len(height)): 22 | for j in range(i+1, len(height)): 23 | max_area = max(max_area, min(height[i], height[j]) * (j - i)) 24 | return max_area 25 | 26 | 27 | class TestMaxArea(unittest.TestCase): 28 | """Unit test for max_area.""" 29 | 30 | def test_1(self): 31 | test_input = [1, 8, 6, 2, 5, 4, 8, 3, 7] 32 | self.assertEqual(max_area(test_input), 49) 33 | 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | 38 | -------------------------------------------------------------------------------- /module_5/python/max_path_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Max path sum 3 | 4 | Problem: 5 | Given a non-empty binary tree, find the maximum path sum. 6 | 7 | For this problem, a path is defined as any sequence of nodes from some 8 | starting node to any node in the tree along the parent-child connections. 9 | The path must contain at least one node and does not need to go through the 10 | root. 11 | 12 | Execution: python max_path_sum.py 13 | """ 14 | import unittest 15 | 16 | 17 | class TreeNode: 18 | """Definition of binary tree node.""" 19 | 20 | def __init__(self, x: int) -> None: 21 | """Set value for node and left/right nodes.""" 22 | self.val = x 23 | self.left = None 24 | self.right = None 25 | 26 | 27 | def max_path_sum(root: TreeNode) -> int: 28 | def dfs(root): 29 | if root: 30 | l, tl = dfs(root.left) 31 | r, tr = dfs(root.right) 32 | t = l + r + root.val 33 | return max(root.val, l + root.val, r+root.val), max(t, tl, tr, l, r) 34 | else: 35 | return float('-inf'),float('-inf') 36 | 37 | m, n = dfs(root) 38 | return max(m,n) 39 | 40 | 41 | class TestMaxSumPath(unittest.TestCase): 42 | """Unit test for max_path_sum.""" 43 | 44 | def test_1(self): 45 | tree = TreeNode(1) 46 | tree.left = TreeNode(2) 47 | tree.right = TreeNode(3) 48 | 49 | self.assertEqual(max_path_sum(tree), 6) 50 | 51 | def test_2(self): 52 | tree = TreeNode(-10) 53 | tree.left = TreeNode(9) 54 | tree.right = TreeNode(20) 55 | tree.right.left = TreeNode(15) 56 | tree.right.right = TreeNode(7) 57 | 58 | self.assertEqual(max_path_sum(tree), 42) 59 | 60 | 61 | if __name__ == '__main__': 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /module_5/python/template.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: 3 | 4 | Problem: 5 | 6 | Execution: python XXX.py 7 | """ 8 | import unittest 9 | 10 | 11 | def template(s: str): 12 | """Function for .""" 13 | pass 14 | 15 | 16 | class TestXXX(unittest.TestCase): 17 | """Unit test for XXX.""" 18 | 19 | def test_1(self): 20 | """Test for .""" 21 | self.assertEqual(template("abcabcbb"), 3) 22 | print("Explanation: .") 23 | 24 | 25 | if __name__ == '__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /module_6/java/Template.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: 3 | * 4 | * Problem: 5 | * 6 | * Execution: javac XX && java XX 7 | */ 8 | import java.util.*; 9 | 10 | 11 | public class Template { 12 | public static int template(String s) { 13 | } 14 | 15 | public static void main(String[] args) { 16 | assert template("abcabcbb") == 3; 17 | System.out.println("Explanation: "); 18 | 19 | System.out.println("Passed all test cases"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /module_6/python/merge_binary_trees.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Merge two binary trees 3 | 4 | Problem: 5 | Given two binary trees and imagine that when you put one of them to cover 6 | the other, some nodes of the two trees are overlapped while the others are 7 | not. 8 | 9 | You need to merge them into a new binary tree. The merge rule is that if two 10 | nodes overlap, then sum node values up as the new value of the merged node. 11 | Otherwise, the NOT null node will be used as the node of new tree. 12 | 13 | Execution: python merge_binary_trees.py 14 | """ 15 | import unittest 16 | 17 | 18 | class TreeNode: 19 | def __init__(self, x: int): 20 | self.val = x 21 | self.left = None 22 | self.right = None 23 | 24 | 25 | def merge_binary_trees(t1: TreeNode, t2: TreeNode) -> TreeNode: 26 | if not t1: 27 | return t2 28 | elif not t2: 29 | return t1 30 | else: 31 | res = TreeNode(t1.val + t2.val) 32 | res.left = merge_binary_trees(t1.left, t2.left) 33 | res.right = merge_binary_trees(t1.right, t2.right) 34 | return res 35 | 36 | 37 | class TestXXX(unittest.TestCase): 38 | """Unit test for merge_binary_trees.""" 39 | 40 | def test_1(self): 41 | tree_1 = TreeNode(1) 42 | tree_1.left = TreeNode(3) 43 | tree_1.right = TreeNode(2) 44 | tree_1.left.left = TreeNode(5) 45 | 46 | tree_2 = TreeNode(2) 47 | tree_2.left = TreeNode(1) 48 | tree_2.right = TreeNode(3) 49 | tree_2.left.right = TreeNode(4) 50 | tree_2.right.right = TreeNode(7) 51 | 52 | res_tree = merge_binary_trees(tree_1, tree_2) 53 | 54 | self.assertEqual(res_tree.val, 3) 55 | self.assertEqual(res_tree.left.val, 4) 56 | self.assertEqual(res_tree.right.val, 5) 57 | self.assertEqual(res_tree.left.left.val, 5) 58 | self.assertEqual(res_tree.left.right.val, 4) 59 | self.assertEqual(res_tree.right.right.val, 7) 60 | 61 | 62 | if __name__ == '__main__': 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /module_6/python/template.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: 3 | 4 | Problem: 5 | 6 | Execution: python XXX.py 7 | """ 8 | import unittest 9 | 10 | 11 | def template(s: str): 12 | """Function for .""" 13 | pass 14 | 15 | 16 | class TestXXX(unittest.TestCase): 17 | """Unit test for XXX.""" 18 | 19 | def test_1(self): 20 | """Test for .""" 21 | self.assertEqual(template("abcabcbb"), 3) 22 | print("Explanation: .") 23 | 24 | 25 | if __name__ == '__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/IsAnagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Is Anagram 3 | * 4 | * Problem: 5 | * Given two strings s and t , write a function to determine if t is an 6 | * anagram of s. 7 | * 8 | * Execution: javac IsAnagram.java && java IsAnagram 9 | */ 10 | 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | public class IsAnagram { 15 | public static boolean isAnagramSort(String s, String t) { 16 | if (s.length() != t.length()) { 17 | return false; 18 | } 19 | char[] str1 = s.toCharArray(); 20 | char[] str2 = t.toCharArray(); 21 | Arrays.sort(str1); 22 | Arrays.sort(str2); 23 | return Arrays.equals(str1, str2); 24 | } 25 | 26 | public static boolean isAnagramHashTable(String s, String t) { 27 | if (s.length() != t.length()) { 28 | return false; 29 | } 30 | int[] counter = new int[26]; 31 | for (int i = 0; i < s.length(); i++) { 32 | counter[s.charAt(i) - 'a']++; 33 | counter[t.charAt(i) - 'a']--; 34 | } 35 | for (int count : counter) { 36 | if (count != 0) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | 43 | public static void main(String[] args) { 44 | assert isAnagramSort("anagram", "nagaram") == true; 45 | assert isAnagramSort("rat", "car") == false; 46 | 47 | assert isAnagramHashTable("anagram", "nagaram") == true; 48 | assert isAnagramHashTable("rat", "car") == false; 49 | System.out.println("Passed all test cases"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/IsPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Is palindrome 3 | * 4 | * Problem: 5 | * Given a string, determine if it is a palindrome, considering only 6 | * alphanumeric characters and ignoring cases. 7 | * 8 | * Note: For the purpose of this problem, we define empty string as valid 9 | * palindrome. 10 | * 11 | * Execution: javac IsPalindrome.java && java IsPalindrome 12 | */ 13 | import java.util.Arrays; 14 | 15 | 16 | public class IsPalindrome { 17 | public static boolean isPalindrome(String s) { 18 | if((s == null) || (s.length() == 0)) { 19 | return true; 20 | } 21 | 22 | s = String.join("",Arrays.asList(s.split("\\W+"))); 23 | s = s.toLowerCase(); 24 | 25 | String snew = new StringBuilder(s).reverse().toString(); 26 | return s.equals(snew); 27 | } 28 | 29 | public static void main(String[] args) { 30 | assert isPalindrome("A man, a plan, a canal: Panama") == true; 31 | assert isPalindrome("race a car") == false; 32 | 33 | System.out.println("Passed all test cases"); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/LengthOfLongestSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Longest substring without repeating characters. 3 | * 4 | * Problem 5 | * Given a string, find the length of the longest substring without 6 | * repeating characters. 7 | * 8 | * Execution: javac LengthOfLongestSubstring.java && java LengthOfLongestSubstring 9 | */ 10 | 11 | import java.util.HashMap; 12 | 13 | public class LengthOfLongestSubstring { 14 | public static long lengthOfLongestSubstring(String s) { 15 | int n = s.length(), ans = 0; 16 | 17 | // Current index of character. 18 | int[] index = new int[128]; 19 | 20 | // Attempt to extend the range. 21 | int i = 0; 22 | for (int j = 0; j < n; j++) { 23 | i = Math.max(index[s.charAt(j)], i); 24 | ans = Math.max(ans, j - 1 + 1); 25 | index[s.charAt(j)] = j + 1; 26 | } 27 | return ans; 28 | } 29 | 30 | public static void main(String[] args) { 31 | assert lengthOfLongestSubstring("abcabcbb") == 3; 32 | System.out.println("Explanation: The answer is 'abc', with the length of 3."); 33 | 34 | assert lengthOfLongestSubstring("bbbbb") == 1; 35 | System.out.println("Explanation: The answer is 'b', with the length of 1."); 36 | 37 | assert lengthOfLongestSubstring("pwwkew") == 3; 38 | System.out.println("Explanation: The answer is 'wke', with the length 3. Note that the answer must be a substring, 'pwke' is a subsequence and not a substring."); 39 | 40 | System.out.println("Passed all test cases"); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/LongestSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Longest substring without repeating characters. 3 | * 4 | * Problem: 5 | * Given two strings, write a function that returns the longest common substring. 6 | * e.g. 7 | * 8 | * longestSubstring("ABAB", "BABA") = "ABA" 9 | * 10 | * Execution: javac LongestSubstring.java && java LongestSubstring 11 | */ 12 | 13 | import java.util.*; 14 | 15 | public class LongestSubstring { 16 | public static String longestSubstring(String a, String b) { 17 | String out = ""; 18 | if (a.length() == 0 || b.length() == 0) return out; 19 | 20 | int len = 0; 21 | int[][] cache = new int[a.length()][b.length()]; 22 | 23 | for (int i = 0; i < a.length(); i++) { 24 | for (int j = 0; j < b.length(); j++) { 25 | if (a.charAt(i) == b.charAt(j)) { 26 | if (i == 0 || j == 0) { 27 | cache[i][j] = 1; 28 | } else { 29 | cache[i][j] = cache[i-1][j-1] + 1; } 30 | if (cache[i][j] > len) { 31 | len = cache[i][j]; 32 | out = a.substring(i - len + 1, i+1); 33 | } 34 | } 35 | } 36 | } 37 | return out; 38 | } 39 | public static void main(String[] args) { 40 | assert longestSubstring("ABAB", "BABA") == "ABA"; 41 | 42 | System.out.println("Passed all test cases"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Remove duplicates 3 | * 4 | * Problem: 5 | * Given a sorted array nums, remove the duplicates in-place such that each 6 | * element appear only once and return the new length. 7 | * 8 | * Do not allocate extra space for another array, you must do this by modifying 9 | * the input array in-place with O(1) extra memory. * 10 | * 11 | * Execution: javac RemoveDuplicates.java && java RemoveDuplicates 12 | */ 13 | 14 | 15 | public class RemoveDuplicates { 16 | public static long removeDuplicates(int[] nums) { 17 | if (nums.length == 0) { 18 | return 0; 19 | } 20 | int i = 0; 21 | for (int j = 1; j < nums.length; j++) { 22 | if (nums[j] != nums[i]) { 23 | i++; 24 | nums[i] = nums[j]; 25 | } 26 | } 27 | return i + 1; 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] arr_1 = {1, 1, 2}; 32 | assert removeDuplicates(arr_1) == 2; 33 | 34 | int[] arr_2 = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; 35 | assert removeDuplicates(arr_2) == 5; 36 | 37 | System.out.println("Passed all test cases"); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/ReverseString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Reverse string 3 | * 4 | * Problem: 5 | * Write a function that reverses a string. The input string is given as an 6 | * array of characters char[]. 7 | * 8 | * Do not allocate extra space for another array, you must do this by 9 | * modifying the input array in-place with O(1) extra memory. 10 | * 11 | * You may assume all the characters consist of printable ascii characters. 12 | * 13 | * Execution: javac ReverseString.java && java ReverseString 14 | */ 15 | import java.util.*; 16 | 17 | 18 | public class ReverseString { 19 | public static char[] reverseString(char[] s) { 20 | int left = 0, right = s.length - 1; 21 | while (left < right) { 22 | char tmp = s[left]; 23 | s[left++] = s[right]; 24 | s[right--] = tmp; 25 | } 26 | return s; 27 | } 28 | 29 | public static void main(String[] args) { 30 | char[] test_input_1 = {'h','e','l','l','o'}; 31 | char[] expected_output_1 = {'o','l','l','e','h'}; 32 | assert reverseString(test_input_1) == expected_output_1; 33 | 34 | char[] test_input_2 = { 'H','a','n','n','a','h' }; 35 | char[] expected_output_2 = { 'h','a','n','n','a','H' }; 36 | assert reverseString(test_input_2) == expected_output_2; 37 | 38 | System.out.println("Passed all test cases"); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/SortString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Sort string 3 | * 4 | * Problem: 5 | * Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a 6 | * program to print the characters of this string in sorted order. 7 | * 8 | * Execution: javac SortString.java && java SortString 9 | */ 10 | 11 | import java.util.Arrays; 12 | 13 | public class SortString { 14 | public static String sortString(String s) { 15 | char[] arr = s.toCharArray(); 16 | Arrays.sort(arr); 17 | return String.valueOf(arr); 18 | } 19 | 20 | public static void main(String[] args) { 21 | assert sortString("bbccdefbbaa") == "aabbbbccdef"; 22 | assert sortString("cba") == "abc"; 23 | System.out.println("Passed all test cases"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/StringToBinary.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Convert string to binary sequence 3 | * 4 | * Problem: 5 | * Given a string of character the task is to convert each character of a 6 | * string into the equivalent binary number. 7 | * 8 | * Execution: javac StringToBinary.java && java StringToBinary 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class StringToBinary { 14 | static String stringToBinary(String s) { 15 | int n = s.length(); 16 | 17 | String bin = ""; 18 | for (int i = 0; i < n; i++) { 19 | // Convert each char to ASCII value. 20 | int val = Integer.valueOf(s.charAt(i)); 21 | 22 | // Convert ASCII value to binary. 23 | bin = ""; 24 | while (val > 0) { 25 | if (val % 2 == 1) { 26 | bin += '1'; 27 | } 28 | else { 29 | bin += '0'; 30 | } 31 | val /= 2; 32 | } 33 | bin = reverse(bin); 34 | System.out.print(bin + " "); 35 | } 36 | return bin; 37 | } 38 | 39 | static String reverse(String input) { 40 | char[] a = input.toCharArray(); 41 | int l, r = 0; 42 | r = a.length - 1; 43 | 44 | for (l = 0; l < r; l++, r--) { 45 | // Swap values of l and r 46 | char temp = a[l]; 47 | a[l] = a[r]; 48 | a[r] = temp; 49 | } 50 | return String.valueOf(a); 51 | } 52 | public static void main(String[] args) { 53 | String s = "BbB"; 54 | assert stringToBinary(s) == "1000010 1100010 1000010"; 55 | 56 | System.out.println("Passed all test cases"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/java/WildcardMatching.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Wildcard Matching 3 | * 4 | * Problem: 5 | * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. 6 | * 7 | * '?' Matches any single character. 8 | * '*' Matches any sequence of characters (including the empty sequence). 9 | * The matching should cover the entire input string (not partial). 10 | * 11 | * Note: 12 | * 13 | * s could be empty and contains only lowercase letters a-z. 14 | * p could be empty and contains only lowercase letters a-z, and characters like ? or *. 15 | * 16 | * Execution: javac WildcardMatching.java && java WildcardMatching 17 | */ 18 | 19 | import java.util.*; 20 | 21 | public class WildcardMatching { 22 | public static boolean wildcardMatching(String s, String p) { 23 | boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; 24 | dp[0][0] = true; 25 | for (int i = 0; i < p.length(); i++) { 26 | if(p.charAt(i) == '*' && dp[0][i]){ 27 | dp[0][i+1] = true; 28 | } 29 | } 30 | for (int i = 0; i < s.length(); i++) { 31 | for (int j = 0; j < p.length(); j++) { 32 | if(s.charAt(i) == p.charAt(j) || p.charAt(j) == '?'){ 33 | dp[i+1][j+1] = dp[i][j]; 34 | } 35 | if(p.charAt(j) == '*'){ 36 | dp[i + 1][j + 1] = dp[i][j + 1] || dp[i + 1][j]; 37 | } 38 | } 39 | } 40 | return dp[s.length()][p.length()]; 41 | } 42 | 43 | public static void main(String[] args) { 44 | assert wildcardMatching("aa", "a") == false; 45 | assert wildcardMatching("aa", "*") == true; 46 | assert wildcardMatching("cb", "?a") == false; 47 | assert wildcardMatching("adceb", "*a*b") == true; 48 | assert wildcardMatching("acdcb", "a*c?b") == false; 49 | 50 | System.out.println("Passed all test cases"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/find_anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find anagrams 3 | 4 | Problem: 5 | Given a string s and a non-empty string p, find all the start indices of 6 | p's anagrams in s. 7 | 8 | Strings consists of lowercase English letters only and the length of both 9 | strings s and p will not be larger than 20,100. 10 | 11 | The order of output does not matter. 12 | 13 | Execution: python find_anagrams.py 14 | """ 15 | from collections import Counter 16 | from typing import List 17 | import unittest 18 | 19 | 20 | def find_anagrams(s: str, p: str) -> List[int]: 21 | pattern_counter = Counter(p) 22 | running_counter = Counter() 23 | len_p = len(p) 24 | result = [] 25 | 26 | for i in range(len(s)): 27 | 28 | # If index >= length of the pattern. then decrement the count of the 29 | # (i - len_p)th character to remove it from the current (sliding) 30 | # window. 31 | if i >= len_p: 32 | running_counter[s[i - len_p]] -= 1 33 | 34 | if running_counter[s[i - len_p]] == 0: 35 | del running_counter[s[i - len_p]] 36 | 37 | # Default: just increment the count of the current character. 38 | running_counter[s[i]] += 1 39 | 40 | # At any time, if running_counter == pattern_counter then append the 41 | # result. 42 | if running_counter == pattern_counter: 43 | result.append(i - len_p + 1) 44 | 45 | return result 46 | 47 | 48 | class TestCompareVersion(unittest.TestCase): 49 | """Unit tests for compare_version.""" 50 | 51 | def test_1(self): 52 | self.assertEqual(find_anagrams("cbaebabacd", "abc"), [0, 6]) 53 | 54 | def test_2(self): 55 | self.assertEqual(find_anagrams("abab", "ab"), [0, 1, 2]) 56 | 57 | 58 | if __name__ == "__main__": 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/is_anagram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Is Anagram 3 | 4 | Problem: 5 | Given two strings s and t , write a function to determine if t is an 6 | anagram of s. 7 | 8 | Execution: python is_anagram.py 9 | """ 10 | import unittest 11 | 12 | 13 | def is_anagram_sorting(s: str, t: str) -> bool: 14 | """Check if string s is anagram of string t using sorting.""" 15 | if len(s) != len(t): 16 | return False 17 | s = sorted(s) 18 | t = sorted(t) 19 | return s == t 20 | 21 | 22 | def is_anagram_hash_table(s: str, t: str) -> bool: 23 | """Check if string s is anagram of string t using hash table.""" 24 | ht = dict() 25 | 26 | if len(s) != len(t): 27 | return False 28 | 29 | for i in s: 30 | if i in ht: 31 | ht[i] += 1 32 | else: 33 | ht[i] = 1 34 | for i in t: 35 | if i in ht: 36 | ht[i] -= 1 37 | else: 38 | ht[i] = 1 39 | for i in ht: 40 | if ht[i] != 0: 41 | return False 42 | return True 43 | 44 | 45 | class TestIsAnagram(unittest.TestCase): 46 | """Unit test for is_anagram.""" 47 | 48 | def test_1(self): 49 | s = "anagram" 50 | t = "nagaram" 51 | self.assertEqual(is_anagram_sorting(s, t), True) 52 | self.assertEqual(is_anagram_hash_table(s, t), True) 53 | 54 | def test_2(self): 55 | s = "rat" 56 | t = "car" 57 | self.assertEqual(is_anagram_sorting(s, t), False) 58 | self.assertEqual(is_anagram_hash_table(s, t), False) 59 | 60 | 61 | if __name__ == "__main__": 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/is_palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Is palindrome 3 | 4 | Problem: 5 | Given a string, determine if it is a palindrome, considering only 6 | alphanumeric characters and ignoring cases. 7 | 8 | Note: For the purpose of this problem, we define empty string as valid 9 | palindrome. 10 | 11 | Execution: python is_palindrome.py 12 | """ 13 | import string 14 | import unittest 15 | 16 | 17 | def is_palindrome(s: str) -> bool: 18 | s = s.lower().replace(" ", "").translate(str.maketrans("", 19 | "", 20 | string.punctuation)) 21 | return True if s[::-1] == s else False 22 | 23 | 24 | class TestIsPalindrome(unittest.TestCase): 25 | """Unit tests for is_palindrome.""" 26 | 27 | def test_1(self): 28 | self.assertEqual(is_palindrome("A man, a plan, a canal: Panama"), True) 29 | 30 | def test_2(self): 31 | self.assertEqual(is_palindrome("race a car"), False) 32 | 33 | 34 | if __name__ == "__main__": 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/length_of_longest_substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Longest substring without repeating characters. 3 | 4 | Problem: 5 | Given a string, find the length of the longest substring without repeating 6 | characters. 7 | 8 | Execution: python length_of_longest_substring.py 9 | """ 10 | import unittest 11 | 12 | 13 | def length_of_longest_substring(s: str) -> int: 14 | """Given a string, determine the length of the longest substring.""" 15 | last, res, st = dict(), 0, 0 16 | for i, v in enumerate(s): 17 | if v not in last or last[v] < st: 18 | res = max(res, i - st + 1) 19 | else: 20 | st = last[v] + 1 21 | last[v] = i 22 | return res 23 | 24 | 25 | class TestLengthOfLongestSubstring(unittest.TestCase): 26 | """Unit tests for length_of_longest_substring.""" 27 | 28 | def test_1(self): 29 | """Test for string: abcabcbb.""" 30 | self.assertEqual(length_of_longest_substring("abcabcbb"), 3) 31 | print("Explanation: The answer is 'abc', with the length of 3.") 32 | 33 | def test_2(self): 34 | """Test for string: bbbbb.""" 35 | self.assertEqual(length_of_longest_substring("bbbbb"), 1) 36 | print("Explanation: The answer is 'b', with the length of 1.") 37 | 38 | def test_3(self): 39 | """Test for string: pwwkew.""" 40 | self.assertEqual(length_of_longest_substring("pwwkew"), 3) 41 | print("Explanation: The answer is 'wke', with the length 3.") 42 | print("Note that the answer must be a substring, 'pwke' ") 43 | print("is a subsequence and not a substring.") 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/longest_substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Longest substring 3 | 4 | Problem: 5 | Given two strings, write a function that returns the longest common 6 | substring. e.g. 7 | 8 | ``` 9 | longestSubstring("ABAB", "BABA") = "ABA" 10 | ``` 11 | 12 | Execution: python longest_substring.py 13 | """ 14 | from collections import defaultdict 15 | import unittest 16 | 17 | 18 | def longest_substring(a: str, b: str) -> str: 19 | out = "" 20 | if len(a) == 0 or len(b) == 0: 21 | return out 22 | 23 | str_len = 0 24 | cache = defaultdict(dict) 25 | for i in range(len(a)): 26 | for j in range(len(b)): 27 | if a[i] == b[j]: 28 | if i == 0 or j == 0: 29 | cache[i][j] = 1 30 | else: 31 | cache[i][j] = cache[i - 1][j - 1] + 1 32 | if cache[i][j] > str_len: 33 | str_len = cache[i][j] 34 | out = a[i - str_len + 1 : i + 1] 35 | return out 36 | 37 | 38 | class TestLongestSubstring(unittest.TestCase): 39 | """Unit test for longest_substring.""" 40 | 41 | def test_1(self): 42 | a = "ABAB" 43 | b = "BABA" 44 | self.assertEqual(longest_substring(a, b), "ABA") 45 | 46 | 47 | if __name__ == "__main__": 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Remove duplicates 3 | 4 | Problem: 5 | Given a sorted array nums, remove the duplicates in-place such that each 6 | element appear only once and return the new length. 7 | 8 | Do not allocate extra space for another array, you must do this by modifying 9 | the input array in-place with O(1) extra memory. 10 | 11 | Execution: python remove_duplicates.py 12 | """ 13 | from typing import List 14 | import unittest 15 | 16 | 17 | def remove_duplicates(nums: List[int]) -> int: 18 | if len(nums) == 0: 19 | return 0 20 | i = 0 21 | for j in range(1, len(nums)): 22 | if nums[j] != nums[i]: 23 | i += 1 24 | nums[i] = nums[j] 25 | return i + 1 26 | 27 | 28 | class TestRemoveDuplicates(unittest.TestCase): 29 | """Unit tests for remove_duplicates.""" 30 | 31 | def test_1(self): 32 | self.assertEqual(remove_duplicates([1, 1, 2]), 2) 33 | 34 | def test_2(self): 35 | self.assertEqual(remove_duplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]), 5) 36 | 37 | 38 | if __name__ == "__main__": 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/reverse_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Reverse string 3 | 4 | Problem: 5 | Write a function that reverses a string. The input string is given as an 6 | array of characters char[]. 7 | 8 | Do not allocate extra space for another array, you must do this by modifying 9 | the input array in-place with O(1) extra memory. 10 | 11 | You may assume all the characters consist of printable ascii characters. 12 | 13 | Execution: python reverse_string.py 14 | """ 15 | from typing import List 16 | import unittest 17 | 18 | 19 | def reverse_string(s: List[str]) -> List[str]: 20 | def helper(left, right): 21 | if left < right: 22 | s[left], s[right] = s[right], s[left] 23 | helper(left + 1, right - 1) 24 | 25 | helper(0, len(s) - 1) 26 | return s 27 | 28 | 29 | class TestReverseString(unittest.TestCase): 30 | """Unit tests for reverse_string.""" 31 | 32 | def test_1(self): 33 | test_input = ["h", "e", "l", "l", "o"] 34 | expected_output = ["o", "l", "l", "e", "h"] 35 | self.assertEqual(reverse_string(test_input), expected_output) 36 | 37 | def test_2(self): 38 | test_input = ["H", "a", "n", "n", "a", "h"] 39 | expected_output = ["h", "a", "n", "n", "a", "H"] 40 | self.assertEqual(reverse_string(test_input), expected_output) 41 | 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/sort_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Sort string 3 | 4 | Problem: 5 | Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a 6 | program to print the characters of this string in sorted order. 7 | 8 | Execution: python sort_string.py 9 | """ 10 | import unittest 11 | 12 | 13 | def sort_string(s: str) -> str: 14 | return "".join(sorted(s)) 15 | 16 | 17 | class TestSortString(unittest.TestCase): 18 | """Unit test for sort_string.""" 19 | 20 | def test_1(self): 21 | s = "bbccdefbbaa" 22 | self.assertEqual(sort_string(s), "aabbbbccdef") 23 | 24 | 25 | if __name__ == "__main__": 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/string_to_binary.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Convert string into binary sequence 3 | 4 | Problem: 5 | Given a string of character the task is to convert each character of a 6 | string into the equivalent binary number. 7 | 8 | Execution: python string_to_binary.py 9 | """ 10 | import unittest 11 | 12 | 13 | def string_to_binary(s: str) -> str: 14 | bin_conv = list() 15 | for c in s: 16 | ascii_val = ord(c) 17 | binary_val = bin(ascii_val) 18 | bin_conv.append(binary_val[2:]) 19 | 20 | return " ".join(bin_conv) 21 | 22 | 23 | class TestStringToBinary(unittest.TestCase): 24 | """Unit tests for string_to_binary.""" 25 | 26 | def test_1(self): 27 | self.assertEqual(string_to_binary("BbB"), "1000010 1100010 1000010") 28 | 29 | 30 | if __name__ == "__main__": 31 | unittest.main() 32 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/substring_concat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Substring with Concatenation of All Words 3 | 4 | Problem: 5 | You are given a string, s, and a list of words, words, that are all of the 6 | same length. Find all starting indices of substring(s) in s that is a 7 | concatenation of each word in words exactly once and without any intervening 8 | characters. 9 | 10 | Execution: python substring_concat.py 11 | """ 12 | from typing import List, Optional 13 | import collections 14 | import unittest 15 | 16 | 17 | def substring_concat(s: str, words: List[str]) -> Optional[List[int]]: 18 | """"Concatenate substring.""" 19 | if not s or not words: 20 | return None 21 | word_len = len(words[0]) 22 | window_len = len(words) * word_len 23 | str_len = len(s) 24 | word_dict, ret = collections.Counter(words), [] 25 | for i in range(str_len - window_len + 1): 26 | new_dict = collections.defaultdict(int) 27 | 28 | for j in range(i, i + window_len, word_len): 29 | sub_word = s[j : j + word_len] 30 | 31 | if sub_word in word_dict: 32 | new_dict[sub_word] += 1 33 | if new_dict[sub_word] > word_dict[sub_word]: 34 | break 35 | else: 36 | break 37 | if new_dict == word_dict: 38 | ret.append(i) 39 | return ret 40 | 41 | 42 | class TestSubstringConcat(unittest.TestCase): 43 | """Unit tests for substring_concat.""" 44 | 45 | def test_1(self): 46 | s = "barfoothefoobarman" 47 | words = ["foo", "bar"] 48 | expected_res = [0, 9] 49 | self.assertEqual(substring_concat(s, words), expected_res) 50 | 51 | def test_2(self): 52 | s = "wordgoodgoodgoodbestword" 53 | words = ["word", "good", "best", "word"] 54 | expected_res = [] 55 | self.assertEqual(substring_concat(s, words), expected_res) 56 | 57 | 58 | if __name__ == "__main__": 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /quickstart_guides/arrays_strings/python/wildcard_matching.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Wildcard matching 3 | 4 | Problem: 5 | Given an input string (s) and a pattern (p), implement wildcard pattern 6 | matching with support for '?' and '*'. 7 | 8 | '?' Matches any single character. '*' Matches any sequence of characters 9 | (including the empty sequence). The matching should cover the entire input 10 | string (not partial). 11 | 12 | Note: 13 | 14 | s could be empty and contains only lowercase letters a-z. p could be empty 15 | and contains only lowercase letters a-z, and characters like ? or *. 16 | 17 | Execution: python wildcard_matching.py 18 | """ 19 | import unittest 20 | 21 | 22 | def wildcard_matching(a: str, b: str) -> bool: 23 | if len(a) == len(b) == 0: 24 | return True 25 | res = False 26 | seen = set() 27 | dfs(a, b, 0, 0, seen, res) 28 | return res 29 | 30 | 31 | def dfs(s, p, i, j, seen, res) -> None: 32 | if (i, j) in seen: 33 | return 34 | 35 | # Recursion exit condition. 36 | if j > len(p) - 1: 37 | return 38 | 39 | # Generate multiple cases. 40 | if p[j] == "*": 41 | for i in range(i, len(s)): 42 | if (i, j + 1) not in seen: 43 | dfs(s, p, i, j + 1, seen, res) 44 | seen.add((i, j + 1)) 45 | else: 46 | return 47 | 48 | elif i < len(s) and (p[j] == "?" or s[i] == p[j]): 49 | if (i + 1, j + 1) not in seen: 50 | dfs(s, p, i + 1, j + 1, seen, res) 51 | seen.add((i + 1, j + 1)) 52 | else: 53 | return 54 | 55 | 56 | class TestWildcardMatching(unittest.TestCase): 57 | """Unit test for wildcard_matching.""" 58 | 59 | def test_1(self): 60 | a = "aa" 61 | p = "a" 62 | self.assertEqual(wildcard_matching(a, p), False) 63 | 64 | def test_2(self): 65 | a = "acdcb" 66 | p = "a*c?b" 67 | self.assertEqual(wildcard_matching(a, p), False) 68 | 69 | 70 | if __name__ == "__main__": 71 | unittest.main() 72 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/HammingDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Calculate the Hamming distance. 3 | * 4 | * Problem: 5 | * The Hamming distance between two integers is the number of positions 6 | * at which the corresponding bits are different. 7 | * 8 | * Now your job is to find the total Hamming distance between all pairs of the 9 | * given numbers. 10 | * Execution: javac HammingDistance.java && java HammingDistance 11 | */ 12 | 13 | 14 | public class HammingDistance { 15 | public static int hammingDistance(int[] nums) { 16 | if (nums == null || nums.length == 0) { 17 | return 0; 18 | } 19 | 20 | int total = 0; 21 | for (int i = 0; i < 31; i++) { 22 | int bitCount = 0; 23 | for (int num: nums) { 24 | bitCount += (num >> i) & 1; 25 | } 26 | total += bitCount * (nums.length - bitCount); 27 | } 28 | return total; 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | int[] testInput = {4, 14, 2}; 34 | assert hammingDistance(testInput) == 6; 35 | System.out.println("In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6."); 36 | 37 | System.out.println("Passed all test cases"); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/HammingWeight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Hamming weight. 3 | * 4 | * Problem: 5 | * Write a function that takes an unsigned integer and return the number 6 | * of '1' bits it has (also known as the Hamming weight). 7 | * 8 | * Execution: javac HammingWeight.java && java HammingWeight 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class HammingWeight { 14 | public static int hammingWeight(int n) { 15 | int sum = 0; 16 | while (n != 0) { 17 | sum++; 18 | n &= (n - 1); 19 | } 20 | return sum; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int input_1 = Integer.parseInt("00000000000000000000000000001011", 2); 25 | int input_2 = Integer.parseInt("00000000000000000000000010000000", 2); 26 | 27 | assert hammingWeight(input_1) == 3; 28 | assert hammingWeight(input_2) == 1; 29 | 30 | System.out.println("Passed all test cases"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/IsEvenOdd.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Is even or odd. 3 | * 4 | * Problem: 5 | * Write a program to determine if a given number is even or odd. 6 | * Do not make use of the modulus operator. 7 | * 8 | * Execution: javac IsEvenOdd.java && java IsEvenOdd 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class IsEvenOdd { 14 | public static String isEvenOdd(int x) { 15 | if ((x & 1) == 0) { 16 | return "Even"; 17 | } else { 18 | return "Odd"; 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | assert isEvenOdd(26) == "Even"; 24 | assert isEvenOdd(25) == "Odd"; 25 | 26 | System.out.println("Passed all test cases"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/PowerOfFour.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Power of four. 3 | * 4 | * Problem: 5 | * Given an integer, write a function to determine if it is a power of 6 | * four. 7 | * 8 | * Execution: javac PowerOfFour.java && java PowerOfFour 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class PowerOfFour { 14 | public static boolean powerOfFour(int num) { 15 | if(num==1) return true; 16 | if(num==0) return false; 17 | while(num>4 && num%4==0){ 18 | num=num/4; 19 | } 20 | if(num==4) return true; 21 | return false; 22 | } 23 | 24 | public static void main(String[] args) { 25 | assert powerOfFour(16) == true; 26 | assert powerOfFour(5) == false; 27 | 28 | System.out.println("Passed all test cases"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Power of two. 3 | * 4 | * Problem: 5 | * Given an integer, write a function to determine if it is a power of 6 | * two. 7 | * 8 | * Execution: javac PowerOfTwo.java && java PowerOfTwo 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class PowerOfTwo { 14 | public static boolean powerOfTwo(int n) { 15 | int powerOfTwo = 2; 16 | if(n==1 || n==2) 17 | return true; 18 | 19 | // Checking for odd numbers. 20 | if(n % 2 == 1) 21 | return false; 22 | while(powerOfTwo<=n/2) { 23 | powerOfTwo=powerOfTwo*2; 24 | if(n==powerOfTwo) 25 | return true; 26 | } 27 | return false; 28 | } 29 | 30 | public static void main(String[] args) { 31 | assert powerOfTwo(1) == true; 32 | assert powerOfTwo(16) == true; 33 | assert powerOfTwo(218) == false; 34 | 35 | System.out.println("Passed all test cases"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/ReverseSigned.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Reverse signed 3 | * 4 | * Problem: 5 | * Reverse bits of a given 32 bits unsigned integer. 6 | * 7 | * Execution: javac ReverseSigned.java && java ReverseSigned 8 | */ 9 | import java.util.*; 10 | 11 | 12 | public class ReverseSigned { 13 | public static int reverseSigned(int n) { 14 | char[] chs = new char[Integer.SIZE]; 15 | for (int i = 0; i < Integer.SIZE; i++) 16 | { 17 | chs[i] = (char) (((n >> i) & 1) + '0'); 18 | } 19 | String resStr = new String(chs); 20 | 21 | // Avoid overflow. 22 | long total=0; 23 | char [] binCharArray = resStr.toCharArray(); 24 | 25 | // Convert the binary string into an int number. 26 | for (int i = 0; i < binCharArray.length; i++) { 27 | total=total+binCharArray[i]-48; 28 | if(i!=binCharArray.length-1){ 29 | total=total<<1; 30 | } 31 | } 32 | return (int) total; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int input_1 = Integer.parseInt("00000010100101000001111010011100", 2); 37 | int output_1 = Integer.parseInt("00111001011110000010100101000000", 2); 38 | 39 | assert reverseSigned(input_1) == output_1; 40 | 41 | System.out.println("Passed all test cases"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/SetNthBit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Set n^th bit 3 | * 4 | * Problem: 5 | * Write a program that takes an integer and sets the n-th bit in the 6 | * binary representation of that integer. 7 | * 8 | * For instance, the binary representation of 6 is: 9 | * 110 10 | * The least significant bit is the bit on the far right of the binary 11 | * representation and the most significant bit is the bit on the far left. 12 | * We order the bits as 13 | * 14 | * b2, b1, b0 15 | * 1 1 0 16 | * 17 | * For our function, if we set the 0th bit, we should obtain the binary 18 | * representation: 19 | * 1 1 1 20 | * 21 | * Execution: javac SetNthBit.java && java SetNthBit 22 | */ 23 | import java.util.*; 24 | 25 | 26 | public class SetNthBit { 27 | public static int setNthBit(int x, int n) { 28 | return x | (1 << n); 29 | } 30 | 31 | public static void main(String[] args) { 32 | assert setNthBit(6, 0) == 7; 33 | System.out.println("Passed all test cases"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/java/SumTwoInts.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Sum two integers. 3 | * 4 | * Problem: 5 | * Calculate the sum of two integers a and b, but you are not allowed to 6 | * use the operator + and -. 7 | * 8 | * Execution: javac SumTwoIntegers.java && java SumTwoIntegers 9 | */ 10 | import java.util.*; 11 | 12 | 13 | public class SumTwoInts { 14 | public static int sumTwoInts(int A, int B) { 15 | int carry = 0; 16 | int r = 0; 17 | 18 | for(int i = 0; i < 32; ++i) { 19 | int a = (A & 1 << i); 20 | int b = (B & 1 << i); 21 | int t = a ^ b ^ carry; 22 | 23 | r |= t; 24 | 25 | // Case when both bits 1. 26 | if((a & b) != 0) { 27 | carry = 1 << ( i + 1); 28 | // Case when a's or b's bit 1 and carry 1. 29 | } else if(carry != 0 && t == 0) { 30 | carry = 1 << ( i + 1); 31 | } else { 32 | carry = 0; 33 | } 34 | } 35 | 36 | return r; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int a_1 = 3; 41 | int b_1 = 2; 42 | 43 | int a_2 = -2; 44 | int b_2 = 3; 45 | 46 | assert sumTwoInts(a_1, b_1) == 3; 47 | assert sumTwoInts(a_2, b_2) == 1; 48 | 49 | System.out.println("Passed all test cases"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/hamming_distance.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Calculate the Hamming distance. 3 | 4 | Problem: 5 | The Hamming distance between two integers is the number of positions 6 | at which the corresponding bits are different. 7 | 8 | Now your job is to find the total Hamming distance between all pairs of the 9 | given numbers. 10 | 11 | Execution: python hamming_distance.py 12 | """ 13 | from typing import List 14 | import unittest 15 | 16 | 17 | def hamming_distance(nums: List[int]) -> int: 18 | """Function for calculating the Hamming distance.""" 19 | res = 0 20 | while nums != [0] * len(nums): 21 | c = 0 22 | for i in range(len(nums)): 23 | if nums[i] % 2 == 1: 24 | c += 1 25 | nums[i] = (nums[i] - nums[i] % 2) // 2 26 | res += c * (len(nums) - c) 27 | return res 28 | 29 | 30 | class TestHammingDistance(unittest.TestCase): 31 | """Unit test for hamming_distance.""" 32 | 33 | def test_1(self): 34 | input_list = [4, 14, 2] 35 | self.assertEqual(hamming_distance(input_list), 6) 36 | output = """ 37 | In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 38 | (just showing the four bits relevant in this case). So the answer will 39 | be: HammingDistance(4, 14) + HammingDistance(4, 2) + 40 | HammingDistance(14, 2) = 2 + 2 + 2 = 6. 41 | """ 42 | print(f"Explanation: {output}") 43 | 44 | 45 | if __name__ == "__main__": 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/hamming_weight.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Calculate the Hamming weight. 3 | 4 | Problem: 5 | Write a function that takes an unsigned integer and return the number of 6 | '1' bits it has (also known as the Hamming weight). 7 | 8 | Execution: python hamming_weight.py 9 | """ 10 | import unittest 11 | 12 | 13 | def hamming_weight(n: int) -> int: 14 | """Function for calculating the Hamming distance.""" 15 | s = 0 16 | while n != 0: 17 | s += 1 18 | n &= n - 1 19 | return s 20 | 21 | 22 | class TestHammingWeight(unittest.TestCase): 23 | """Unit test for hamming_weight.""" 24 | 25 | def test_1(self): 26 | input_list = int("00000000000000000000000000001011", 2) 27 | self.assertEqual(hamming_weight(input_list), 3) 28 | 29 | def test_2(self): 30 | input_list = int("00000000000000000000000010000000", 2) 31 | self.assertEqual(hamming_weight(input_list), 1) 32 | 33 | def test_3(self): 34 | input_list = int("11111111111111111111111111111101", 2) 35 | self.assertEqual(hamming_weight(input_list), 31) 36 | 37 | 38 | if __name__ == "__main__": 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/is_even_odd.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Is even or odd 3 | 4 | Problem: 5 | Write a program to determine if a given number is even or odd. 6 | Do not make use of the modulus operator. 7 | 8 | Execution: python is_even_odd.py 9 | """ 10 | import unittest 11 | 12 | 13 | def is_even_odd(x: int) -> str: 14 | if x & 1 == 0: 15 | return "Even" 16 | else: 17 | return "Odd" 18 | 19 | 20 | class TestIsEvenOdd(unittest.TestCase): 21 | """Unit test for is_even_odd.""" 22 | 23 | def test_1(self): 24 | self.assertEqual(is_even_odd(26), "Even") 25 | 26 | def test_2(self): 27 | self.assertEqual(is_even_odd(25), "Odd") 28 | 29 | def test_3(self): 30 | self.assertEqual(is_even_odd(-5), "Odd") 31 | 32 | def test_4(self): 33 | self.assertEqual(is_even_odd(-2), "Even") 34 | 35 | 36 | if __name__ == "__main__": 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/power_of_four.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Power of four 3 | 4 | Problem: 5 | Given an integer, write a function to determine if it is a power of four. 6 | 7 | Execution: python power_of_four.py 8 | """ 9 | from math import log 10 | import unittest 11 | 12 | 13 | def power_of_four(n: int) -> bool: 14 | return n > 0 and log(n, 4).is_integer() 15 | 16 | 17 | class TestPowerOfFourr(unittest.TestCase): 18 | """Unit test for power_of_four.""" 19 | 20 | def test_1(self): 21 | self.assertEqual(power_of_four(16), True) 22 | 23 | def test_2(self): 24 | self.assertEqual(power_of_four(5), False) 25 | 26 | def test_3(self): 27 | self.assertEqual(power_of_four(64), True) 28 | 29 | def test_4(self): 30 | self.assertEqual(power_of_four(18), False) 31 | 32 | 33 | if __name__ == "__main__": 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/power_of_two.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Power of two 3 | 4 | Problem: 5 | Given an integer, write a function to determine if it is a power of two. 6 | 7 | Execution: python power_of_two.py 8 | """ 9 | import unittest 10 | 11 | 12 | def power_of_two(n: int) -> bool: 13 | """Determine if integer is power of 2.""" 14 | if n <= 0: 15 | return False 16 | if n == 1: 17 | return True 18 | while n > 1: 19 | n /= 2 20 | return n == 1 21 | 22 | 23 | class TestPowerOfTwo(unittest.TestCase): 24 | """Unit test for power_of_two.""" 25 | 26 | def test_1(self): 27 | self.assertEqual(power_of_two(1), True) 28 | 29 | def test_2(self): 30 | self.assertEqual(power_of_two(16), True) 31 | 32 | def test_3(self): 33 | self.assertEqual(power_of_two(218), False) 34 | 35 | def test_4(self): 36 | self.assertEqual(power_of_two(64), True) 37 | 38 | 39 | if __name__ == "__main__": 40 | unittest.main() 41 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/reverse_unsigned.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Reverse bits 3 | 4 | Problem: 5 | Reverse bits of a given 32 bits unsigned integer. 6 | 7 | Execution: python reverse_unsigned.py 8 | """ 9 | import unittest 10 | 11 | 12 | def reverse_unsigned(n: int) -> int: 13 | """Reverse an unsigned integer.""" 14 | return int("{:032b}".format(n)[::-1], 2) 15 | 16 | 17 | class TestReverseUnsigned(unittest.TestCase): 18 | """Unit test for reverse_unsigned.""" 19 | 20 | def test_1(self): 21 | input_1 = int("00000010100101000001111010011100", 2) 22 | output_1 = int("00111001011110000010100101000000", 2) 23 | self.assertEqual(int(reverse_unsigned(input_1)), output_1) 24 | 25 | def test_2(self): 26 | input_1 = int("11111111111111111111111111111101", 2) 27 | output_1 = int("10111111111111111111111111111111", 2) 28 | self.assertEqual(int(reverse_unsigned(input_1)), output_1) 29 | 30 | 31 | if __name__ == "__main__": 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/set_nth_bit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Set n^th bit 3 | 4 | Problem: 5 | Write a program that takes an integer and sets the n-th bit in the binary 6 | representation of that integer 7 | 8 | For instance, the binary representation of 6 is: 9 | 10 | ``` 11 | 110 12 | ``` 13 | 14 | The least significant bit is the bit on the far right of the binary 15 | representation and the most significant bit is the bit on the far left. We 16 | order the bits as 17 | 18 | ``` 19 | b2, b1, b0 20 | 1 1 0 21 | ``` 22 | 23 | For our function, if we set the 0th bit, we should obtain the binary 24 | representation: 25 | 26 | ``` 27 | 1 1 1 28 | ``` 29 | 30 | Execution: python set_nth_bit.py 31 | """ 32 | import unittest 33 | 34 | 35 | def set_nth_bit(x: int, n: int) -> int: 36 | """Set the nth bit of an integer.""" 37 | return x | 1 << n 38 | 39 | 40 | class TestSetNthBit(unittest.TestCase): 41 | """Unit test for set_nth_bit.""" 42 | 43 | def test_1(self): 44 | self.assertEqual(set_nth_bit(6, 0), 7) 45 | 46 | 47 | if __name__ == "__main__": 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /quickstart_guides/bit_manipulation/python/sum_two_ints.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Sum of two integers 3 | 4 | Problem: 5 | Calculate the sum of two integers a and b, but you are not allowed to use 6 | the operator + and -. 7 | 8 | Execution: python sum_two_ints.py 9 | """ 10 | import unittest 11 | 12 | 13 | def sum_two_ints(a_int: int, b_int: int) -> int: 14 | """Sum two integers.""" 15 | carry = 0 16 | remainder = 0 17 | for i in range(32): 18 | a = a_int & 1 << i 19 | b = b_int & 1 << i 20 | t = a ^ b ^ carry 21 | 22 | remainder |= t 23 | 24 | # Case when both bits are 1. 25 | if (a & b) != 0: 26 | carry = 1 << (i + 1) 27 | # Case when a's or b's bit 1 and carry. 28 | elif carry != 0 and t == 0: 29 | carry = 1 << (i + 1) 30 | else: 31 | carry = 0 32 | 33 | return remainder 34 | 35 | 36 | class TestSumTwoInts(unittest.TestCase): 37 | """Unit test for sum_two_ints.""" 38 | 39 | def test_1(self): 40 | a = 1 41 | b = 2 42 | self.assertEqual(sum_two_ints(a, b), 3) 43 | 44 | def test_2(self): 45 | a = -2 46 | b = 3 47 | self.assertEqual(sum_two_ints(a, b), 1) 48 | 49 | 50 | if __name__ == "__main__": 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /quickstart_guides/graphs/python/alien_dictionary.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Alien dictionary 3 | 4 | Problem: 5 | Given a sorted dictionary (array of words) of an alien language, find 6 | order of characters in the language. 7 | 8 | Execution: python alien_dictionary.py 9 | """ 10 | from typing import List 11 | import unittest 12 | from collections import defaultdict 13 | 14 | 15 | def alien_order(words: List[str]): 16 | """Find order of characters in alien language.""" 17 | pre = defaultdict(set) 18 | suc = defaultdict(set) 19 | 20 | for pair in zip(words, words[1:]): 21 | for a, b in zip(*pair): 22 | if a != b: 23 | suc[a].add(b) 24 | pre[b].add(a) 25 | break 26 | chars = set("".join(words)) 27 | char_to_process = chars - set(pre) 28 | order = "" 29 | while char_to_process: 30 | # Receiving first node in "char_to_process" and add to string. 31 | ch = char_to_process.pop() 32 | order += ch 33 | # For each character for whom our node is successor. 34 | for b in suc[ch]: 35 | pre[b].discard(ch) 36 | # In case node does not have successors, add to queue. 37 | if not pre[b]: 38 | char_to_process.add(b) 39 | # Check if all characters from alphabet have been covered. 40 | return order * (set(order) == chars) 41 | 42 | 43 | class TestAlienDictionary(unittest.TestCase): 44 | """Unit tests for alien_dictionary.""" 45 | 46 | def test_1(self): 47 | self.assertEqual(alien_order(["wrt", "ert"]), "rwte") 48 | 49 | def test_2(self): 50 | self.assertEqual(alien_order(["wrt", "wrf", "ert"]), "wrtef") 51 | 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /quickstart_guides/graphs/python/network_delay.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Network delay time 3 | 4 | Problem: 5 | There are N network nodes, labelled 1 to N. 6 | 7 | Given times, a list of travel times as directed edges times[i] = (u, v, w), 8 | where u is the source node, v is the target node, and w is the time it takes 9 | for a signal to travel from source to target. 10 | 11 | Now, we send a signal from a certain node K. How long will it take for all 12 | nodes to receive the signal? If it is impossible, return -1. 13 | 14 | Execution: python network_delay.py 15 | """ 16 | from typing import List, Optional 17 | import unittest 18 | from collections import defaultdict 19 | 20 | 21 | def network_delay(times: List[List[int]], n_val: int, k_val: int) -> float: 22 | """Calculate the network delay.""" 23 | graph = defaultdict(list) 24 | for u, v, w in times: 25 | graph[u].append((w, v)) 26 | 27 | dist = {node: float("inf") for node in range(1, n_val + 1)} 28 | 29 | def dfs(node: int, elapsed: int) -> Optional[float]: 30 | if elapsed >= dist[node]: 31 | return 32 | dist[node] = elapsed 33 | for time, nei in sorted(graph[node]): 34 | dfs(nei, elapsed + time) 35 | 36 | dfs(k_val, 0) 37 | ans = max(dist.values()) 38 | return ans if ans < float("inf") else -1 39 | 40 | 41 | class TestNetworkDelay(unittest.TestCase): 42 | """Unit tests for network_delay.""" 43 | 44 | def test_1(self): 45 | times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]] 46 | n_val = 4 47 | k_val = 2 48 | self.assertEqual(network_delay(times, n_val, k_val), 2) 49 | 50 | 51 | if __name__ == "__main__": 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/java/IsPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Is palindrome 3 | * 4 | * Problem: 5 | * Check if linked list is a palindrome. 6 | * 7 | * Execution: javac IsPalindrome.java && java IsPalindrome 8 | */ 9 | import java.util.*; 10 | 11 | 12 | class IsPalindrome { 13 | static ListNode head; 14 | 15 | public static class ListNode { 16 | int val; 17 | ListNode next; 18 | ListNode() {} 19 | ListNode(int val) { this.val = val; } 20 | ListNode(int val, ListNode next) { this.val = val; this.next = next; } 21 | } 22 | 23 | public static boolean isPalindrome(ListNode head) { 24 | if(head!=null) { 25 | List s=new ArrayList<>(); 26 | ListNode c=head; 27 | 28 | while(c!=null){ 29 | s.add(c.val); 30 | c=c.next; 31 | } 32 | 33 | boolean isPalindrome=true; 34 | for(int i=0;i queue= new PriorityQueue(lists.length, (a,b)-> a.val-b.val); 23 | 24 | ListNode dummy = new ListNode(0); 25 | ListNode tail=dummy; 26 | 27 | for (ListNode node:lists) 28 | if (node!=null) 29 | queue.add(node); 30 | 31 | while (!queue.isEmpty()){ 32 | tail.next=queue.poll(); 33 | tail=tail.next; 34 | 35 | if (tail.next!=null) 36 | queue.add(tail.next); 37 | } 38 | return dummy.next; 39 | } 40 | public static void main(String[] args) { 41 | 42 | ListNode test_1 = new ListNode(1); 43 | test_1.next = new ListNode(4); 44 | test_1.next.next = new ListNode(5); 45 | 46 | ListNode test_2 = new ListNode(1); 47 | test_2.next = new ListNode(3); 48 | test_2.next.next = new ListNode(4); 49 | 50 | ListNode test_3 = new ListNode(2); 51 | test_3.next = new ListNode(6); 52 | 53 | ListNode[] test_input = {test_1, test_2, test_3}; 54 | 55 | System.out.println(mergeKLists(test_input)); 56 | 57 | System.out.println("Passed all test cases"); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/java/NthToLast.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Nth-to-last Linked List Element 3 | * 4 | * Problem: 5 | * Given a linked list, find the nth-to-last value in the list. 6 | * 7 | * Execution: javac NthToLast.java && java NthToLast 8 | */ 9 | 10 | public class NthToLast { 11 | // Private node class 12 | private static class Node { 13 | private int value; 14 | private Node next; 15 | 16 | private Node(int value) { 17 | this.value = value; 18 | } 19 | } 20 | 21 | public static Node nthToLast(Node node, int n) { 22 | Node curr = node; 23 | Node follower = node; 24 | 25 | // Iterate curr forward by n. If you reach the end of the list then it is 26 | // shorter than n, so you can't possible have an nth-to-last node 27 | for (int i = 0; i < n; i++) { 28 | if (curr == null) return null; 29 | curr = curr.next; 30 | } 31 | 32 | // If length is exactly n, the nth-to-last node would be null 33 | if (curr == null) return null; 34 | 35 | // Move both nodes forward in unison until curr is at the end of the list 36 | while (curr.next != null) { 37 | curr = curr.next; 38 | follower = follower.next; 39 | } 40 | 41 | return follower; 42 | } 43 | 44 | // Sample test cases 45 | public static void main(String[] args) { 46 | Node n = new Node(1); 47 | n.next = new Node(2); 48 | n.next.next = new Node(3); 49 | n.next.next.next = new Node(4); 50 | n.next.next.next.next = new Node(5); 51 | 52 | assert nthToLast(n, 0).value == 5; 53 | assert nthToLast(n, 1).value == 4; 54 | assert nthToLast(n, 2).value == 3; 55 | assert nthToLast(n, 3).value == 2; 56 | assert nthToLast(n, 4).value == 1; 57 | assert nthToLast(n, 5) == null; 58 | } 59 | } -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/java/PairsWithSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Pairs with sum 3 | * 4 | * Problem: 5 | * Given an array of integers, and a number ‘sum’, find the number of pairs of 6 | * integers in the array whose sum is equal to ‘sum’. 7 | * 8 | * Execution: javac PairsWithSum.java && java PairsWithSum 9 | */ 10 | public class PairsWithSum { 11 | 12 | public static int pairsWithSum(int[] arr, int sum) { 13 | int count = 0; 14 | 15 | // Consider all possible pairs and check their sums 16 | for (int i = 0; i < arr.length; i++) 17 | for (int j = i + 1; j < arr.length; j++) 18 | if ((arr[i] + arr[j]) == sum) 19 | count++; 20 | 21 | return count; 22 | } 23 | public static void main(String args[]) { 24 | int[] arr = { 1, 5, 7, -1, 5 }; 25 | int sum = 6; 26 | assert pairsWithSum(arr, sum) == 3; 27 | } 28 | } -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/java/RemoveSortedDuplicates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Remove sorted duplicates 3 | * 4 | * Problem: 5 | * Given a sorted linked list, delete all duplicates such that each element 6 | * appear only once. 7 | * 8 | * Execution: javac RemoveUnsortedDuplicates.java && java RemoveUnsortedDuplicates 9 | */ 10 | 11 | 12 | class RemoveSortedDuplicates { 13 | 14 | static Node head; 15 | 16 | static class Node { 17 | 18 | int data; 19 | Node next; 20 | 21 | Node(int d) { 22 | data = d; 23 | next = null; 24 | } 25 | } 26 | 27 | public static Node removeDuplicates(Node head) { 28 | Node current = head; 29 | while (current != null && current.next != null) { 30 | if (current.next.data == current.data) { 31 | current.next = current.next.next; 32 | } else { 33 | current = current.next; 34 | } 35 | } 36 | return head; 37 | } 38 | 39 | void printList(Node node) { 40 | while (node != null) { 41 | System.out.print(node.data + " "); 42 | node = node.next; 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | RemoveSortedDuplicates list = new RemoveSortedDuplicates(); 48 | list.head = new Node(1); 49 | list.head.next = new Node(1); 50 | list.head.next.next = new Node(2); 51 | 52 | System.out.println("Linked List before removing duplicates : \n "); 53 | list.printList(head); 54 | 55 | list.removeDuplicates(list.head); 56 | System.out.println(""); 57 | System.out.println("Linked List after removing duplicates : \n "); 58 | list.printList(head); 59 | } 60 | } -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/python/is_palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Linked list is palindrome 3 | 4 | Problem: 5 | Check if linked list has nodes that consist of palindrome. 6 | 7 | Execution: python is_palindrome.py 8 | """ 9 | import unittest 10 | 11 | 12 | class ListNode: 13 | """Class for Linked List node.""" 14 | 15 | def __init__(self, x: int) -> None: 16 | self.val = x 17 | self.next = None 18 | 19 | 20 | def is_palindrome(head: ListNode) -> bool: 21 | """Check if linked list is palindrome.""" 22 | vals = [] 23 | curr = head 24 | while curr: 25 | vals.append(curr.val) 26 | curr = curr.next 27 | 28 | while head: 29 | if head.val != vals.pop(): 30 | return False 31 | head = head.next 32 | return True 33 | 34 | 35 | class TestIsPalindrome(unittest.TestCase): 36 | """Unit test for is_palindrome.""" 37 | 38 | def test_1(self): 39 | list_1 = ListNode(1) 40 | list_1.next = ListNode(2) 41 | 42 | self.assertEqual(is_palindrome(list_1), False) 43 | 44 | def test_2(self): 45 | list_2 = ListNode(1) 46 | list_2.next = ListNode(2) 47 | list_2.next.next = ListNode(2) 48 | list_2.next.next.next = ListNode(1) 49 | 50 | self.assertEqual(is_palindrome(list_2), True) 51 | 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/python/nth_to_last.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Linked list nth to last 3 | 4 | Problem: 5 | Obtain the nth-to-last node. 6 | 7 | Execution: python nth_to_last.py 8 | """ 9 | import unittest 10 | 11 | 12 | class Node: 13 | def __init__(self, data: str) -> None: 14 | self.data = data 15 | self.next = None 16 | 17 | 18 | class LinkedList: 19 | """Linked list class.""" 20 | 21 | def __init__(self) -> None: 22 | self.head = None 23 | 24 | def append(self, data: str) -> None: 25 | """Append node to list.""" 26 | new_node = Node(data) 27 | 28 | if self.head is None: 29 | self.head = new_node 30 | return 31 | 32 | last_node = self.head 33 | while last_node.next: 34 | last_node = last_node.next 35 | last_node.next = new_node 36 | 37 | def len_iterative(self) -> int: 38 | """Calculate the length iteratively.""" 39 | count = 0 40 | cur_node = self.head 41 | 42 | while cur_node: 43 | count += 1 44 | cur_node = cur_node.next 45 | return count 46 | 47 | def print_nth_from_last(self, n: int) -> None: 48 | """Print nth from last node.""" 49 | # Method 1: 50 | total_len = self.len_iterative() 51 | 52 | cur = self.head 53 | while cur: 54 | if total_len == n: 55 | return cur.data 56 | total_len -= 1 57 | cur = cur.next 58 | if cur is None: 59 | return 60 | 61 | 62 | class TestNthToLast(unittest.TestCase): 63 | """Unit test for nth_to_last.""" 64 | 65 | def test_1(self): 66 | llist = LinkedList() 67 | llist.append("A") 68 | llist.append("B") 69 | llist.append("C") 70 | llist.append("D") 71 | 72 | self.assertEqual(llist.print_nth_from_last(2), "C") 73 | 74 | 75 | if __name__ == "__main__": 76 | unittest.main() 77 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/python/pairs_with_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Pairs with sum. 3 | 4 | Problem: 5 | Given an array of integers, and a number ‘sum’, find the number of pairs of 6 | integers in the array whose sum is equal to ‘sum’. 7 | 8 | Execution: python pairs_with_sum.py 9 | """ 10 | from typing import List 11 | import unittest 12 | 13 | 14 | def pairs_with_sum(arr: List[int], s: int) -> int: 15 | """ 16 | Returns number of pairs in arr[0..n-1] with sum equal to 'sum' 17 | """ 18 | # Initialize result. 19 | count = 0 20 | # Consider all possible pairs and check their sums. 21 | for i in range(len(arr)): 22 | for j in range(i + 1, len(arr)): 23 | if arr[i] + arr[j] == s: 24 | count += 1 25 | return count 26 | 27 | 28 | class TestPairsWithSum(unittest.TestCase): 29 | """Unit test for pairs_with_sum.""" 30 | 31 | def test_1(self): 32 | x = [1, 5, 7, -1, 5] 33 | self.assertEqual(pairs_with_sum(x, 6), 3) 34 | 35 | 36 | if __name__ == "__main__": 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/python/reorder_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Reorder list. 3 | 4 | Problem: 5 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: 6 | L0→Ln→L1→Ln-1→L2→Ln-2→…. 7 | 8 | You may not modify the values in the list's nodes, only nodes itself may be 9 | changed. 10 | 11 | Execution: python reorder_list.py 12 | """ 13 | import unittest 14 | 15 | 16 | class ListNode: 17 | """Basic node class for linked list.""" 18 | 19 | def __init__(self, x): 20 | self.val = x 21 | self.next = None 22 | 23 | 24 | def reorder_list(head: ListNode) -> None: 25 | """Reorder linked list.""" 26 | if head is None: 27 | return None 28 | 29 | fast = slow = head 30 | # Slow will be the middle of the list 31 | while fast and fast.next: 32 | fast = fast.next.next 33 | slow = slow.next 34 | 35 | # Reverse list elements starting from the middle. 36 | pr, cur = slow, slow.next 37 | while cur: 38 | tmp = cur.next 39 | cur.next, pr = pr, cur 40 | cur = tmp 41 | 42 | tail = pr 43 | # Walk from head and tail towards the middle of the list and merge 44 | # {0: n}, {1: (n-1)} ... { k: (n-k)} 45 | while tail != slow: 46 | tmp = tail.next 47 | tail.next = head.next 48 | head.next = tail 49 | head = tail.next 50 | tail = tmp 51 | 52 | slow.next = None 53 | 54 | 55 | class TestReverseList(unittest.TestCase): 56 | """Unit test for reverse list.""" 57 | 58 | def test_1(self): 59 | """Test for 1->2->3->4->5.""" 60 | input_1 = ListNode(1) 61 | input_1.next = ListNode(2) 62 | input_1.next.next = ListNode(3) 63 | input_1.next.next.next = ListNode(4) 64 | input_1.next.next.next.next = ListNode(5) 65 | 66 | reorder_list(input_1) 67 | 68 | 69 | if __name__ == "__main__": 70 | unittest.main() 71 | -------------------------------------------------------------------------------- /quickstart_guides/linked_lists/python/reverse_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Reverse linked list. 3 | 4 | Problem: 5 | Reverse a singly linked list. 6 | 7 | Execution: python reverse_list.py 8 | """ 9 | import unittest 10 | 11 | 12 | class ListNode: 13 | """Basic node class for linked list.""" 14 | def __init__(self, x): 15 | self.val = x 16 | self.next = None 17 | 18 | 19 | def reverse_list_iterative(head: ListNode) -> ListNode: 20 | """Function for iteratively reversing singly linked list.""" 21 | prev = None 22 | curr = head 23 | 24 | while curr: 25 | next_temp = curr.next 26 | curr.next = prev 27 | prev = curr 28 | curr = next_temp 29 | return prev 30 | 31 | 32 | def reverse_list_recursive(head: ListNode) -> ListNode: 33 | """Function for recursively reversing singly linked list.""" 34 | if head is None or head.next is None: 35 | return head 36 | p = reverse_list_recursive(head.next) 37 | head.next.next = head 38 | head.next = None 39 | return p 40 | 41 | 42 | def print_list(head: ListNode) -> list: 43 | """Print linked list elements.""" 44 | output_list = [] 45 | while head: 46 | output_list.append(head.val) 47 | head = head.next 48 | return output_list 49 | 50 | 51 | class TestReverseList(unittest.TestCase): 52 | """Unit test for reverse list.""" 53 | 54 | def test_1(self): 55 | """Test for 1->2->3->4->5.""" 56 | input_1 = ListNode(1) 57 | input_1.next = ListNode(2) 58 | input_1.next.next = ListNode(3) 59 | input_1.next.next.next = ListNode(4) 60 | input_1.next.next.next.next = ListNode(5) 61 | 62 | list_output_iterative_1 = print_list(reverse_list_iterative(input_1)) 63 | self.assertEqual(list_output_iterative_1, [5, 4, 3, 2, 1]) 64 | 65 | 66 | if __name__ == "__main__": 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Binary search 3 | * 4 | * Problem: 5 | * Binary search is a search algorithm that finds the position of a target 6 | * value within a sorted array. Binary search compares the target value to the 7 | * middle element of the array. 8 | * 9 | * If they are not equal, the half in which the target cannot lie is 10 | * eliminated and the search continues on the remaining half, again taking the 11 | * middle element to compare to the target value, and repeating this until the 12 | * target value is found. If the search ends with the remaining half being 13 | * empty, the target is not in the array. 14 | * 15 | * Execution: javac BinarySearch.java && java BinarySearch 16 | */ 17 | import java.util.Arrays; 18 | 19 | 20 | public class BinarySearch { 21 | // Returns index of x if it is present in arr[l..r], else return -1. 22 | public static int binarySearch(int arr[], int l, int r, int x) 23 | { 24 | if (r >= l) { 25 | int mid = l + (r - l) / 2; 26 | 27 | // If the element is present at the middle itself. 28 | if (arr[mid] == x) 29 | return mid; 30 | 31 | // If element is smaller than mid, then it can only be present in 32 | // left subarray. 33 | if (arr[mid] > x) 34 | return binarySearch(arr, l, mid - 1, x); 35 | 36 | // Else the element can only be present in right subarray. 37 | return binarySearch(arr, mid + 1, r, x); 38 | } 39 | 40 | // We reach here when element is not present in array. 41 | return -1; 42 | } 43 | 44 | public static void main(String[] args) { 45 | 46 | BinarySearch ob = new BinarySearch(); 47 | int arr[] = { 2, 3, 4, 10, 40 }; 48 | int n = arr.length; 49 | int x = 10; 50 | int result = ob.binarySearch(arr, 0, n - 1, x); 51 | assert result == 10; 52 | 53 | System.out.println("Passed all test cases"); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/DistinctPerms.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Distinct perms 3 | * 4 | * Problem: 5 | * 6 | * Returns true if str[curr] does not matches with any of the characters 7 | * after str[start]. 8 | * 9 | * Execution: javac DistinctPerms.java && java DistinctPerms 10 | */ 11 | import java.util.Arrays; 12 | 13 | 14 | public class DistinctPerms { 15 | 16 | // Returns true if str[curr] does not matches with any of the 17 | // characters after str[start] 18 | static boolean shouldSwap(char str[], int start, int curr) { 19 | for (int i = start; i < curr; i++) { 20 | if (str[i] == str[curr]) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | // Prints all distinct permutations in str[0..n-1] 28 | static void findPermutations(char str[], int index, int n) { 29 | if (index >= n) { 30 | System.out.println(str); 31 | return; 32 | } 33 | 34 | for (int i = index; i < n; i++) { 35 | 36 | // Proceed further for str[i] only if it 37 | // doesn't match with any of the characters 38 | // after str[index] 39 | boolean check = shouldSwap(str, index, i); 40 | if (check) { 41 | swap(str, index, i); 42 | findPermutations(str, index + 1, n); 43 | swap(str, index, i); 44 | } 45 | } 46 | } 47 | 48 | static void swap(char[] str, int i, int j) { 49 | char c = str[i]; 50 | str[i] = str[j]; 51 | str[j] = c; 52 | } 53 | 54 | // Driver code 55 | public static void main(String[] args) { 56 | 57 | char str[] = {'A', 'B', 'C', 'A'}; 58 | int n = str.length; 59 | findPermutations(str, 0, n); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/FindSubstrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find substrings 3 | * 4 | * Problem: 5 | * Given a string, we have to find out all subsequences of it. A String is a 6 | * subsequence of a given String, that is generated by deleting some 7 | * character of a given string without changing its order. 8 | * 9 | * Execution: javac FindSubstrings.java && java FindSubstrings 10 | */ 11 | import java.util.HashSet; 12 | 13 | 14 | public class FindSubstrings { 15 | // set to store all the subsequences 16 | static HashSet st = new HashSet<>(); 17 | 18 | // It computes all the subsequence of an string 19 | static void subsequence(String str) { 20 | // iterate over the entire string 21 | for (int i = 0; i < str.length(); i++) { 22 | 23 | // iterate from the end of the string 24 | // to generate substrings 25 | for (int j = str.length(); j > i; j--) { 26 | String sub_str = str.substring(i, j); 27 | 28 | if (!st.contains(sub_str)) 29 | st.add(sub_str); 30 | 31 | // drop kth character in the substring 32 | // and if its not in the set then recur 33 | for (int k = 1; k < sub_str.length() - 1; k++) { 34 | StringBuffer sb = new StringBuffer(sub_str); 35 | 36 | // drop character from the string 37 | sb.deleteCharAt(k); 38 | if (!st.contains(sb)) 39 | ; 40 | subsequence(sb.toString()); 41 | } 42 | } 43 | } 44 | } 45 | public static void main(String[] args) { 46 | String s = "aabc"; 47 | subsequence(s); 48 | System.out.println(st); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/InterleavingStrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Interleaving strings 3 | * 4 | * Problem: 5 | * Check whether a string interleaves with two other strings. 6 | * 7 | * Execution: javac InterleavingStrings.java && java InterleavingStrings 8 | */ 9 | import java.util.Arrays; 10 | 11 | 12 | public class InterleavingStrings { 13 | 14 | // Returns true if C is an interleaving of A and B, otherwise returns false. 15 | static boolean isInterleaved (String A, String B, String C) 16 | { 17 | int i = 0, j = 0, k = 0; 18 | 19 | // Iterate through all characters of C. 20 | while (k != C.length()) 21 | { 22 | // Match first character of C with first character 23 | // of A. If matches them move A to next 24 | if (i= 0) 35 | ans += countRec(n-1, sum-i); 36 | 37 | return ans; 38 | } 39 | 40 | // This is mainly a wrapper over countRec. It 41 | // explicitly handles leading digit and calls 42 | // countRec() for remaining digits. 43 | static int finalCount(int n, int sum) { 44 | // Initialize final answer 45 | int ans = 0; 46 | 47 | // Traverse through every digit from 1 to 48 | // 9 and count numbers beginning with it 49 | for (int i = 1; i <= 9; i++) 50 | if (sum-i >= 0) 51 | ans += countRec(n-1, sum-i); 52 | 53 | return ans; 54 | } 55 | 56 | public static void main (String args[]) { 57 | int n = 2, sum = 5; 58 | assert finalCount(n, sum) == 5; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/PermsOfSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Perms of set 3 | * 4 | * Problem: 5 | * 6 | * A permutation, also called an “arrangement number” or “order,” is a 7 | * rearrangement of the elements of an ordered list S into a one-to-one 8 | * correspondence with S itself. A string of length n has n! permutation. 9 | * 10 | * Execution: javac PermsOfSet.java && java PermsOfSet 11 | */ 12 | import java.util.Arrays; 13 | 14 | 15 | public class PermsOfSet { 16 | 17 | /** 18 | * permutation function 19 | * @param str string to calculate permutation for 20 | * @param l starting index 21 | * @param r end index 22 | */ 23 | private void permute(String str, int l, int r) { 24 | if (l == r) 25 | System.out.println(str); 26 | else { 27 | for (int i = l; i <= r; i++) { 28 | str = swap(str,l,i); 29 | permute(str, l+1, r); 30 | str = swap(str,l,i); 31 | } 32 | } 33 | } 34 | 35 | /** 36 | * Swap Characters at position 37 | * @param a string value 38 | * @param i position 1 39 | * @param j position 2 40 | * @return swapped string 41 | */ 42 | public String swap(String a, int i, int j) { 43 | char temp; 44 | char[] charArray = a.toCharArray(); 45 | temp = charArray[i] ; 46 | charArray[i] = charArray[j]; 47 | charArray[j] = temp; 48 | return String.valueOf(charArray); 49 | } 50 | 51 | public static void main(String[] args) { 52 | String str = "ABC"; 53 | int n = str.length(); 54 | PermsOfSet permutation = new PermsOfSet(); 55 | permutation.permute(str, 0, n-1); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/java/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Towers of Hanoi 3 | * 4 | * Problem: 5 | * Tower of Hanoi is a mathematical puzzle where we have three rods and n 6 | * disks. The objective of the puzzle is to move the entire stack to another 7 | * rod, obeying the following simple rules: 8 | * 9 | * 1) Only one disk can be moved at a time. 10 | * 2) Each move consists of taking the upper disk from one of the stacks and 11 | * placing it on top of another stack i.e. a disk can only be moved if it 12 | * is the uppermost disk on a stack. 13 | * 3) No disk may be placed on top of a smaller disk. 14 | * 15 | * Execution: javac TowerOfHanoi.java && java TowerOfHanoi 16 | */ 17 | import java.util.Arrays; 18 | 19 | 20 | public class TowerOfHanoi { 21 | public static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { 22 | if (n == 1) { 23 | System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); 24 | return; 25 | } 26 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 27 | System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); 28 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 29 | } 30 | 31 | public static void main(String[] args) { 32 | int n = 4; 33 | towerOfHanoi(n, 'A', 'C', 'B'); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/binary_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Binary search 3 | 4 | Problem: 5 | Binary search is a search algorithm that finds the position of a target 6 | value within a sorted array. Binary search compares the target value to the 7 | middle element of the array. 8 | 9 | If they are not equal, the half in which the target cannot lie is 10 | eliminated and the search continues on the remaining half, again taking the 11 | middle element to compare to the target value, and repeating this until the 12 | target value is found. If the search ends with the remaining half being 13 | empty, the target is not in the array. 14 | 15 | Execution: python binary_search.py 16 | """ 17 | from typing import Any, List 18 | import unittest 19 | 20 | 21 | def binary_search(data: List[Any], target: int, low: int, high: int) -> bool: 22 | """Recursive implementation of binary search algorithm.""" 23 | if low > high: 24 | return False 25 | else: 26 | mid = (low + high) // 2 27 | if target == data[mid]: 28 | return True 29 | elif target < data[mid]: 30 | return binary_search(data, target, low, mid - 1) 31 | else: 32 | return binary_search(data, target, mid + 1, high) 33 | 34 | 35 | class TestBinarySearch(unittest.TestCase): 36 | """Unit tests for binary_search.""" 37 | 38 | def test_1(self): 39 | data = [2, 4, 5, 7, 8, 9, 12, 37] 40 | target = 37 41 | self.assertEqual(binary_search(data, target, 0, len(data) - 1), True) 42 | 43 | def test_2(self): 44 | data = [2, 4, 5, 7, 8, 9, 12, 37] 45 | target = 40 46 | self.assertEqual(binary_search(data, target, 0, len(data) - 1), False) 47 | 48 | 49 | if __name__ == "__main__": 50 | unittest.main() 51 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/distinct_perms.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Distinct permutations of the string. 3 | 4 | Problem: 5 | Returns true if str[curr] does not matches with any of the characters 6 | after str[start]. 7 | 8 | Execution: python distinct_perms.py 9 | """ 10 | from typing import List, Optional 11 | import unittest 12 | 13 | 14 | def should_swap(input_str: List[str], start: int, curr: int) -> bool: 15 | """Determine if a swap should occur.""" 16 | for i in range(start, curr): 17 | if input_str[i] == input_str[curr]: 18 | return False 19 | return True 20 | 21 | 22 | def find_perms(input_str: List[str], index: int, n: int, perms: list) -> Optional[List[str]]: 23 | """ 24 | Prints all distinct permutations in str[0..n-1]. 25 | """ 26 | if index >= n: 27 | perms.append("".join(input_str)) 28 | return 29 | 30 | for i in range(index, n): 31 | # Proceed further for str[i] only if it doesn't match with any of the 32 | # characters after str[index]. 33 | check = should_swap(input_str, index, i) 34 | if check: 35 | input_str[index], input_str[i] = input_str[i], input_str[index] 36 | find_perms(input_str, index + 1, n, perms) 37 | input_str[index], input_str[i] = input_str[i], input_str[index] 38 | return perms 39 | 40 | 41 | class TestDistinctPerms(unittest.TestCase): 42 | """Unit tests for distinct_perms.""" 43 | 44 | def test_1(self): 45 | expected_res = [ 46 | "abca", 47 | "abac", 48 | "acba", 49 | "acab", 50 | "aacb", 51 | "aabc", 52 | "baca", 53 | "baac", 54 | "bcaa", 55 | "cbaa", 56 | "caba", 57 | "caab", 58 | ] 59 | input_str = list("abca") 60 | n = len(input_str) 61 | perms = [] 62 | res = find_perms(input_str, 0, n, perms) 63 | self.assertEqual(res, expected_res) 64 | 65 | 66 | if __name__ == "__main__": 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/find_combos.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find all combinations of a set of inputs 3 | 4 | Problem: 5 | Given an array of size n, generate and print all possible combinations of r 6 | elements in array. For example, if input array is {1, 2, 3, 4} and r is 2, 7 | then output should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}. 8 | 9 | Execution: python find_combos.py 10 | """ 11 | from typing import List 12 | 13 | 14 | def print_combos(arr: List[int], n: int, r: int): 15 | """Print combinations.""" 16 | data = [0] * r 17 | return find_combos(arr, n, r, 0, data, 0) 18 | 19 | 20 | def find_combos(arr: List[int], n: int, r: int, index: int, data: List[int], i: int): 21 | if index == r: 22 | x = [] 23 | for j in range(r): 24 | x.append(data[j]) 25 | print(x) 26 | return 27 | 28 | # When no more elements are there to put in data[]. 29 | if i >= n: 30 | return 31 | 32 | # current is included, put 33 | # next at next location 34 | data[index] = arr[i] 35 | find_combos(arr, n, r, index + 1, data, i + 1) 36 | 37 | # current is excluded, replace it 38 | # with next (Note that i+1 is passed, 39 | # but index is not changed) 40 | find_combos(arr, n, r, index, data, i + 1) 41 | 42 | 43 | if __name__ == "__main__": 44 | arr = [1, 2, 3, 4, 5] 45 | r = 3 46 | n = len(arr) 47 | print_combos(arr, n, r) 48 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/find_substrings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find substrings 3 | 4 | Problem: 5 | Given a string, we have to find out all subsequences of it. A String is a 6 | subsequence of a given String, that is generated by deleting some character 7 | of a given string without changing its order. 8 | 9 | Execution: python find_substrings.py 10 | """ 11 | from typing import List 12 | import unittest 13 | 14 | 15 | def find_substrings(test_str: str) -> List[str]: 16 | """Find substrings solution.""" 17 | return [ 18 | test_str[i:j] 19 | for i in range(len(test_str)) 20 | for j in range(i + 1, len(test_str) + 1) 21 | ] 22 | 23 | 24 | class TestFindSubstrings(unittest.TestCase): 25 | """Unit tests for interleaving_strings.""" 26 | 27 | def test_1(self): 28 | expected_out = ["B", "By", "Byt", "Byte", "y", "yt", "yte", "t", "te", "e"] 29 | self.assertEqual(find_substrings("Byte"), expected_out) 30 | 31 | 32 | if __name__ == "__main__": 33 | unittest.main() 34 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/is_palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Is palindrome 3 | 4 | Problem: 5 | Given a string, determine if it is a palindrome, considering only 6 | alphanumeric characters and ignoring cases. 7 | 8 | Note: For the purpose of this problem, we define empty string as valid 9 | palindrome. 10 | 11 | Execution: python is_palindrome.py 12 | """ 13 | import string 14 | import unittest 15 | 16 | 17 | def is_palindrome(s: str) -> bool: 18 | """Check if string is palindrome.""" 19 | s = s.lower().replace(" ", "").translate(str.maketrans("", "", string.punctuation)) 20 | return True if s[::-1] == s else False 21 | 22 | 23 | class TestIsPalindrome(unittest.TestCase): 24 | """Unit tests for is_palindrome.""" 25 | 26 | def test_1(self): 27 | self.assertEqual(is_palindrome("A man, a plan, a canal: Panama"), True) 28 | 29 | def test_2(self): 30 | self.assertEqual(is_palindrome("race a car"), False) 31 | 32 | 33 | if __name__ == "__main__": 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Merge sort. 3 | 4 | Problem: 5 | Merge sort is a divide-and-conquer algorithm based on the idea of breaking 6 | down a list into several sub-lists until each sublist consists of a single 7 | element and merging those sublists in a manner that results into a sorted 8 | list. 9 | 10 | Execution: python merge_sort.py 11 | """ 12 | from typing import Any, List 13 | import unittest 14 | 15 | 16 | def merge_sort(data: List[Any]): 17 | """Perform merge sort recursively on list.""" 18 | if len(data) > 1: 19 | mid = len(data) // 2 20 | left = data[:mid] 21 | right = data[mid:] 22 | 23 | merge_sort(left) 24 | merge_sort(right) 25 | 26 | i = j = k = 0 27 | 28 | # Copy data to temp arrays L[] and R[] 29 | while i < len(left) and j < len(right): 30 | if left[i] < right[j]: 31 | data[k] = left[i] 32 | i += 1 33 | else: 34 | data[k] = right[j] 35 | j += 1 36 | k += 1 37 | 38 | # Checking if any element was left 39 | while i < len(left): 40 | data[k] = left[i] 41 | i += 1 42 | k += 1 43 | 44 | while j < len(right): 45 | data[k] = right[j] 46 | j += 1 47 | k += 1 48 | 49 | 50 | class TestMergeSort(unittest.TestCase): 51 | """Unit tests for merge_sort.""" 52 | 53 | def test_1(self): 54 | data = [12, 11, 13, 5, 6, 7] 55 | expected_out = [5, 6, 7, 11, 12, 13] 56 | merge_sort(data) 57 | self.assertEqual(data, expected_out) 58 | 59 | 60 | if __name__ == "__main__": 61 | unittest.main() 62 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/n_digit_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: n-digit sum. 3 | 4 | Problem: 5 | Recursive function to count 'n' digit numbers with sum of digits as 'sum' 6 | This function considers leading 0's also as digits, that is why not 7 | directly called. 8 | 9 | Execution: python n_digit_sum.py 10 | """ 11 | import unittest 12 | 13 | 14 | def count_rec(n: int, sum_val: int) -> int: 15 | # Base case. 16 | if n == 0: 17 | return sum_val == 0 18 | 19 | if sum_val == 0: 20 | return 1 21 | 22 | # Initialize answer. 23 | ans = 0 24 | 25 | # Traverse through every digit and count numbers beginning with it using 26 | # recursion. 27 | for i in range(10): 28 | if sum_val - i >= 0: 29 | ans = ans + count_rec(n - 1, sum_val - i) 30 | 31 | return ans 32 | 33 | 34 | def final_count(n: int, sum_val: int) -> int: 35 | """ 36 | This is mainly a wrapper over countRec. It explicitly handles leading digit 37 | and calls countRec() for remaining digits. 38 | """ 39 | 40 | # Initialize final answer. 41 | ans = 0 42 | 43 | # Traverse through every digit from 1 to 9 and count numbers beginning with 44 | # it. 45 | for i in range(1, 10): 46 | if sum_val - i >= 0: 47 | ans = ans + count_rec(n - 1, sum_val - i) 48 | 49 | return ans 50 | 51 | 52 | class TestNDigitSum(unittest.TestCase): 53 | """Unit tests for n_digit_sum.""" 54 | 55 | def test_1(self): 56 | n = 2 57 | sum_val = 5 58 | self.assertEqual(final_count(n, sum_val), 5) 59 | 60 | 61 | if __name__ == "__main__": 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/perms_of_set.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Permutations of set. 3 | 4 | Problem: 5 | A permutation, also called an “arrangement number” or “order,” is a 6 | rearrangement of the elements of an ordered list S into a one-to-one 7 | correspondence with S itself. A string of length n has n! permutation. 8 | 9 | Execution: python perms_of_set.py 10 | """ 11 | from typing import List 12 | import unittest 13 | 14 | 15 | def permute(a: List[str], idx_1: int, idx_2: int, perms) -> List[str]: 16 | """ 17 | Function to print permutations of string. 18 | """ 19 | if idx_1 == idx_2: 20 | perms.append("".join(a)) 21 | else: 22 | for i in range(idx_1, idx_2 + 1): 23 | a[idx_1], a[i] = a[i], a[idx_1] 24 | permute(a, idx_1 + 1, idx_2, perms) 25 | 26 | # Backtrack. 27 | a[idx_1], a[i] = a[i], a[idx_1] 28 | return perms 29 | 30 | 31 | class TestPermsOfSet(unittest.TestCase): 32 | """Unit tests for perms_of_set.""" 33 | 34 | def test_1(self): 35 | expected_res = ["ABC", "ACB", "BAC", "BCA", "CBA", "CAB"] 36 | tracking_list = [] 37 | input_str = "ABC" 38 | res = permute(list(input_str), 0, len(input_str) - 1, tracking_list) 39 | 40 | self.assertEqual(res, expected_res) 41 | 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /quickstart_guides/recursion/python/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Tower of Hanoi 3 | 4 | Problem: 5 | Tower of Hanoi is a mathematical puzzle where we have three rods and n 6 | disks. The objective of the puzzle is to move the entire stack to another 7 | rod, obeying the following simple rules: 8 | 9 | 1) Only one disk can be moved at a time. 10 | 2) Each move consists of taking the upper disk from one of the stacks and 11 | placing it on top of another stack i.e. a disk can only be moved if it 12 | is the uppermost disk on a stack. 13 | 3) No disk may be placed on top of a smaller disk. 14 | 15 | Execution: python tower_of_hanoi.py 16 | """ 17 | import unittest 18 | 19 | 20 | def tower_of_hanoi(n: int, from_rod: str, to_rod: str, aux_rod: str): 21 | if n == 1: 22 | print("Move disk 1 from rod", from_rod, "to rod", to_rod) 23 | return 24 | tower_of_hanoi(n - 1, from_rod, aux_rod, to_rod) 25 | print("Move disk", n, "from rod", from_rod, "to rod", to_rod) 26 | tower_of_hanoi(n - 1, aux_rod, to_rod, from_rod) 27 | 28 | 29 | class TestTowerOfHanoi(unittest.TestCase): 30 | """Unit tests for tower_of_hanoi.""" 31 | 32 | def test_1(self): 33 | n = 4 34 | tower_of_hanoi(n, "A", "C", "B") 35 | 36 | 37 | if __name__ == "__main__": 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Binary Search 3 | * 4 | * Problem: 5 | * Implement binary search on an array. 6 | * 7 | * Execution: javac BinarySearch.java && java BinarySearch 8 | */ 9 | class BinarySearch { 10 | // Returns index of x if it is present in arr[l..r], else return -1. 11 | int binarySearch(int arr[], int l, int r, int x) 12 | { 13 | if (r >= l) { 14 | int mid = l + (r - l) / 2; 15 | 16 | // If the element is present at the middle itself. 17 | if (arr[mid] == x) 18 | return mid; 19 | 20 | // If element is smaller than mid, then it can only be present in 21 | // left subarray. 22 | if (arr[mid] > x) 23 | return binarySearch(arr, l, mid - 1, x); 24 | 25 | // Else the element can only be present in right subarray. 26 | return binarySearch(arr, mid + 1, r, x); 27 | } 28 | 29 | // We reach here when element is not present in array. 30 | return -1; 31 | } 32 | 33 | public static void main(String args[]) 34 | { 35 | BinarySearch ob = new BinarySearch(); 36 | int arr[] = { 2, 3, 4, 10, 40 }; 37 | int n = arr.length; 38 | int x = 10; 39 | int y = 50; 40 | int result_in = ob.binarySearch(arr, 0, n - 1, x); 41 | assert result_in == 10; 42 | int result_out = ob.binarySearch(arr, 0, n - 1, y); 43 | assert result_out == -1; 44 | 45 | System.out.println("Passed all test cases"); 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/java/FindFirstDuplicateEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find first duplicate entry 3 | * 4 | * Problem: 5 | * Write a function that takes an array of sorted integers and a key and 6 | * returns the index of the first occurrence of that key from the array. 7 | * Example: 8 | * idx 0 1 2 3 4 5 6 7 8 9 9 | * A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] 10 | * target = 108 11 | * Returns index 3 since 108 appears for the first time at 12 | * index 3. 13 | * 14 | * Execution: javac FindFirstDuplicateEntry.java && java FindFirstDuplicateEntry 15 | */ 16 | 17 | 18 | class FindFirstDuplicateEntry 19 | { 20 | // Main Function to find fixed index using binary search. 21 | public static int findFirstDuplicatEnry(int arr[], int target) 22 | { 23 | int low = 0; 24 | int high = arr.length - 1; 25 | 26 | while (low <= high) { 27 | int mid = (low + high) / 2; 28 | 29 | if (arr[mid] < target) { 30 | low = mid + 1; 31 | } 32 | else if (arr[mid] > target) { 33 | high = mid - 1; 34 | } 35 | else { 36 | if (mid - 1 < 0) { 37 | return mid; 38 | } 39 | if (arr[mid-1] != target) { 40 | return mid; 41 | } 42 | high = mid - 1; 43 | } 44 | } 45 | return -1; 46 | } 47 | 48 | public static void main(String[] args) 49 | { 50 | int arr[] = {-14, -10, 2, 108, 108, 243, 285, 285, 285, 401}; 51 | int target = 108; 52 | assert findFirstDuplicatEnry(arr, target) == 3; 53 | 54 | System.out.println("All tests passed."); 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/java/FindFixedPoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find fixed point 3 | * 4 | * Problem: 5 | * Given an array of n duplicates or distinct integers sorted in ascending 6 | * order, write a function that returns a Fixed Point in the array, if 7 | * there is any Fixed Point present in the array, else returns -1. Fixed 8 | * Point in an array is an index i such that arr[i] is equal to i. Note 9 | * that integers in the array can be negative. 10 | * 11 | * Execution: javac FindFixedPoint.java && java FindFixedPoint 12 | */ 13 | class FindFixedPoint 14 | { 15 | // Main Function to find fixed 16 | // index using binary search 17 | public static int findFixedPoint(int arr[], int low, 18 | int high) 19 | { 20 | if (high < low) 21 | return -1; 22 | 23 | // low + (high - low) / 2 24 | int mid = (low + high) / 2; 25 | int midValue = arr[mid]; 26 | 27 | if (mid == arr[mid]) 28 | return mid; 29 | 30 | // Search left. 31 | int leftindex = Math.min(mid - 1, midValue); 32 | int left = findFixedPoint(arr, low, leftindex); 33 | 34 | if (left >= 0) 35 | return left; 36 | 37 | // Search right. 38 | int rightindex = Math.max(mid + 1, midValue); 39 | int right = findFixedPoint(arr, rightindex, high); 40 | 41 | return right; 42 | } 43 | 44 | public static void main(String[] args) 45 | { 46 | // input 1 47 | int arr[] = {-10, -5, 2, 2, 2, 48 | 3, 4, 7, 9, 12, 13}; 49 | 50 | assert findFixedPoint(arr, 0, arr.length - 1) == 2; 51 | 52 | // input 2 53 | int arr1[] = {-10, -1, 3, 3, 10, 54 | 30, 30, 50, 100}; 55 | 56 | assert findFixedPoint(arr1, 0, arr1.length - 1) == 3; 57 | 58 | System.out.println("All tests passed."); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/java/FindLargestNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find largest number 3 | * 4 | * Problem: 5 | * Given a list of non negative integers, arrange them such that they form 6 | * the largest number. 7 | * 8 | * 9 | * Execution: javac FindLargestNumber.java && java FindLargestNumber 10 | */ 11 | import java.util.*; 12 | 13 | 14 | class FindLargestNumber { 15 | private static class LargerNumberComparator implements Comparator { 16 | @Override 17 | public int compare(String a, String b) { 18 | String order1 = a + b; 19 | String order2 = b + a; 20 | return order2.compareTo(order1); 21 | } 22 | } 23 | 24 | public static String findLargestNumber(int[] nums) { 25 | // Get input integers as strings. 26 | String[] asStrs = new String[nums.length]; 27 | for (int i = 0; i < nums.length; i++) { 28 | asStrs[i] = String.valueOf(nums[i]); 29 | } 30 | 31 | // Sort strings according to custom comparator. 32 | Arrays.sort(asStrs, new LargerNumberComparator()); 33 | 34 | // If, after being sorted, the largest number is `0`, the entire number 35 | // is zero. 36 | if (asStrs[0].equals("0")) { 37 | return "0"; 38 | } 39 | 40 | // Build largest number from sorted array. 41 | String largestNumberStr = new String(); 42 | for (String numAsStr : asStrs) { 43 | largestNumberStr += numAsStr; 44 | } 45 | 46 | return largestNumberStr; 47 | } 48 | 49 | public static void main(String[] args) 50 | { 51 | // input 1 52 | int arr_1[] = {10, 2}; 53 | 54 | assert findLargestNumber(arr_1) == "210"; 55 | 56 | // input 2 57 | int arr_2[] = {3, 30, 34, 5, 9}; 58 | 59 | assert findLargestNumber(arr_2) == "9534330"; 60 | 61 | 62 | System.out.println("All tests passed."); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/java/FindSqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find square root 3 | * 4 | * Problem: 5 | * Implement int sqrt(int x). 6 | * 7 | * Compute and return the square root of x, where x is guaranteed to be a 8 | * non-negative integer. 9 | * 10 | * Since the return type is an integer, the decimal digits are truncated and 11 | * only the integer part of the result is returned. 12 | * 13 | * Execution: javac FindSqrt.java && java FindSqrt 14 | */ 15 | class FindSqrt { 16 | public static int findSqrt(int x) 17 | { 18 | if(x == 0){ 19 | return 0; 20 | } 21 | long l = 1; 22 | long r = (long)x; 23 | long middle = 0; 24 | while(l <= r){ 25 | middle = (l + r) / 2; 26 | 27 | if(middle * middle == x) 28 | return (int)middle; 29 | else if(middle * middle < x) 30 | { 31 | l = middle + 1; 32 | } 33 | else 34 | { 35 | r = middle - 1; 36 | } 37 | } 38 | if(middle * middle > x) 39 | return (int)(middle - 1); 40 | return (int)middle; 41 | } 42 | 43 | public static void main(String args[]) 44 | { 45 | assert findSqrt(4) == 2; 46 | assert findSqrt(16) == 4; 47 | 48 | System.out.println("Passed all test cases"); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/find_first_duplicate_entry.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find first duplicate entry 3 | 4 | Problem: 5 | Write a function that takes an array of sorted integers and a key and 6 | returns the index of the first occurrence of that key from the array. 7 | Example: 8 | idx 0 1 2 3 4 5 6 7 8 9 9 | A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] 10 | target = 108 11 | Returns index 3 since 108 appears for the first time at 12 | index 3. 13 | 14 | Execution: python find_first_duplicate_entry.py 15 | """ 16 | from typing import List 17 | import unittest 18 | 19 | 20 | def find_first_duplicate_entry(input_list: List[int], target: int) -> int: 21 | low = 0 22 | high = len(input_list) - 1 23 | 24 | while low <= high: 25 | mid = (low + high) // 2 26 | 27 | if input_list[mid] < target: 28 | low = mid + 1 29 | elif input_list[mid] > target: 30 | high = mid - 1 31 | else: 32 | if mid - 1 < 0: 33 | return mid 34 | if input_list[mid - 1] != target: 35 | return mid 36 | high = mid - 1 37 | 38 | 39 | class TestFindFirstDuplicateEntry(unittest.TestCase): 40 | """Unit tests for find_first_duplicate_entry.""" 41 | 42 | def test_1(self): 43 | input_list = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] 44 | target = 108 45 | self.assertEqual(find_first_duplicate_entry(input_list, target), 3) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/find_fixed_point.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find fixed point 3 | 4 | Problem: 5 | A fixed point in an array "A" is an index "i" such that A[i] is equal to 6 | "i". Given an array of n distinct integers sorted in ascending order, 7 | write a function that returns a "fixed point" in the array. If there is not 8 | a fixed point return "None". 9 | 10 | Execution: python find_fixed_point.py 11 | """ 12 | from typing import List, Union 13 | import unittest 14 | 15 | 16 | # Time Complexity: O(log n) 17 | # Space Complexity: O(1) 18 | def find_fixed_point(input_list: List[int]) -> Union[int, None]: 19 | low = 0 20 | high = len(input_list) - 1 21 | 22 | while low <= high: 23 | mid = (low + high) // 2 24 | 25 | if input_list[mid] < mid: 26 | low = mid + 1 27 | elif input_list[mid] > mid: 28 | high = mid - 1 29 | else: 30 | return input_list[mid] 31 | return None 32 | 33 | 34 | class TestFindFixedPoint(unittest.TestCase): 35 | """Unit tests for find_fixed_point.""" 36 | 37 | def test_1(self): 38 | input_list = [-10, -5, 0, 3, 7] 39 | self.assertEqual(find_fixed_point(input_list), 3) 40 | 41 | def test_2(self): 42 | input_list = [0, 2, 5, 8, 17] 43 | self.assertEqual(find_fixed_point(input_list), 0) 44 | 45 | def test_3(self): 46 | input_list = [-10, -5, 3, 4, 7, 9] 47 | self.assertEqual(find_fixed_point(input_list), None) 48 | 49 | 50 | if __name__ == "__main__": 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/find_largest_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find largest number 3 | 4 | Problem: 5 | Given a list of non negative integers, arrange them such that they form the 6 | largest number. 7 | 8 | Execution: python find_largest_number.py 9 | """ 10 | from typing import List 11 | import unittest 12 | 13 | 14 | class LargerNumKey(str): 15 | def __lt__(x, y): 16 | return x + y > y + x 17 | 18 | 19 | def find_largest_number(nums: List[int]) -> str: 20 | largest_num = "".join(sorted(map(str, nums), key=LargerNumKey)) 21 | return "0" if largest_num[0] == "0" else largest_num 22 | 23 | 24 | class TestFindLargest(unittest.TestCase): 25 | """Unit test for find_sqrt.""" 26 | 27 | def test_1(self): 28 | self.assertEqual(find_largest_number([10, 2]), "210") 29 | 30 | def test_2(self): 31 | self.assertEqual(find_largest_number([3, 30, 34, 5, 9]), "9534330") 32 | 33 | 34 | if __name__ == "__main__": 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/find_sqrt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Square root. 3 | 4 | Problem: 5 | Implement int sqrt(int x). 6 | 7 | Compute and return the square root of x, where x is guaranteed to be a 8 | non-negative integer. 9 | 10 | Since the return type is an integer, the decimal digits are truncated and 11 | only the integer part of the result is returned. 12 | 13 | Execution: python find_sqrt.py 14 | """ 15 | import unittest 16 | 17 | 18 | def find_sqrt(x: int) -> int: 19 | guess = x 20 | epsilon = 10 ** (-4) 21 | 22 | while abs(x - guess * guess) > epsilon: 23 | guess = (guess + x / guess) / 2 24 | 25 | return int(guess) 26 | 27 | 28 | class TestFindSqrt(unittest.TestCase): 29 | """Unit test for find_sqrt.""" 30 | 31 | def test_1(self): 32 | self.assertEqual(find_sqrt(4), 2) 33 | 34 | def test_2(self): 35 | self.assertEqual(find_sqrt(16), 4) 36 | 37 | 38 | if __name__ == "__main__": 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Merge sort 3 | 4 | Problem: 5 | Implement merge sort. 6 | 7 | Execution: python merge_sort.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | def merge_sort(arr: List[int]) -> None: 14 | if len(arr) > 1: 15 | mid = len(arr) // 2 16 | left = arr[:mid] 17 | right = arr[mid:] 18 | 19 | merge_sort(left) 20 | merge_sort(right) 21 | 22 | i = j = k = 0 23 | 24 | while i < len(left) and j < len(right): 25 | if left[i] < right[j]: 26 | arr[k] = left[i] 27 | i += 1 28 | else: 29 | arr[k] = right[j] 30 | j += 1 31 | k += 1 32 | 33 | # Checking if any element was left 34 | while i < len(left): 35 | arr[k] = left[i] 36 | i += 1 37 | k += 1 38 | 39 | while j < len(right): 40 | arr[k] = right[j] 41 | j += 1 42 | k += 1 43 | 44 | 45 | class TestMergeSort(unittest.TestCase): 46 | """Unit test for MergeSort.""" 47 | 48 | def test_1(self): 49 | input_arr = [12, 11, 13, 5, 6, 7] 50 | expected_arr = [5, 6, 7, 11, 12, 13] 51 | merge_sort(input_arr) 52 | self.assertEqual(expected_arr, input_arr) 53 | 54 | def test_2(self): 55 | input_arr = [34, 2, 32, 33] 56 | expected_arr = [2, 32, 33, 34] 57 | merge_sort(input_arr) 58 | self.assertEqual(expected_arr, input_arr) 59 | 60 | 61 | if __name__ == "__main__": 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /quickstart_guides/sorting_searching/python/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Quick sort 3 | 4 | Problem: 5 | Implement quick sort algorithm. 6 | 7 | Execution: python quick_sort.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | def partition(arr: List[int], low: int, high: int) -> int: 14 | idx = low - 1 # index of smaller element 15 | pivot = arr[high] # pivot 16 | 17 | for j in range(low, high): 18 | # If current element is smaller than the pivot 19 | if arr[j] < pivot: 20 | # increment index of smaller element 21 | idx = idx + 1 22 | arr[idx], arr[j] = arr[j], arr[idx] 23 | 24 | arr[idx + 1], arr[high] = arr[high], arr[idx + 1] 25 | return idx + 1 26 | 27 | 28 | def quick_sort(arr: List[int], low: int, high: int) -> None: 29 | if low < high: 30 | # pi is partitioning index, arr[p] is now at right place. 31 | pi = partition(arr, low, high) 32 | 33 | # Separately sort elements before partition and after partition. 34 | quick_sort(arr, low, pi - 1) 35 | quick_sort(arr, pi + 1, high) 36 | 37 | 38 | class TestQuickSort(unittest.TestCase): 39 | def test_quick_sort(self): 40 | arr = [10, 7, 8, 9, 1, 5] 41 | n = len(arr) 42 | quick_sort(arr, 0, n - 1) 43 | 44 | result = [] 45 | for i in range(n): 46 | result.append(arr[i]) 47 | 48 | self.assertEqual(result, [1, 5, 7, 8, 9, 10]) 49 | 50 | 51 | if __name__ == "__main__": 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /quickstart_guides/trees/java/DiameterOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Diameter of binary tree 3 | * 4 | * Problem: 5 | * Given a binary tree, you need to compute the length of the diameter of the 6 | * tree. The diameter of a binary tree is the length of the longest path 7 | * between any two nodes in a tree. This path may or may not pass through the 8 | * root. 9 | * 10 | * 11 | * Execution: javac DiameterOfBinaryTree.java && java DiameterOfBinaryTree 12 | */ 13 | import java.util.*; 14 | 15 | 16 | class DiameterOfBinaryTree { 17 | 18 | public static class TreeNode { 19 | int val; 20 | TreeNode left; 21 | TreeNode right; 22 | TreeNode() {} 23 | TreeNode(int val) { this.val = val; } 24 | TreeNode(int val, TreeNode left, TreeNode right) { 25 | this.val = val; 26 | this.left = left; 27 | this.right = right; 28 | } 29 | } 30 | 31 | int ans; 32 | public int diameterOfBinaryTree(TreeNode root) { 33 | ans = 1; 34 | depth(root); 35 | return ans - 1; 36 | } 37 | public int depth(TreeNode node) { 38 | if (node == null) return 0; 39 | int L = depth(node.left); 40 | int R = depth(node.right); 41 | ans = Math.max(ans, L+R+1); 42 | return Math.max(L, R) + 1; 43 | } 44 | public static void main(String args[]) 45 | { 46 | DiameterOfBinaryTree d = new DiameterOfBinaryTree(); 47 | TreeNode tree = new TreeNode(1); 48 | tree.right = new TreeNode(2); 49 | tree.right.left = new TreeNode(3); 50 | 51 | assert d.depth(tree) == 3; 52 | 53 | System.out.println("Passed all test cases"); 54 | } 55 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/java/InorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: In-order traversal of binary tree 3 | * 4 | * Problem: 5 | * Given a binary tree, return the inorder traversal of its nodes' values. 6 | * 7 | * Execution: javac InorderTraversal.java && java InorderTraversal 8 | */ 9 | import java.util.*; 10 | 11 | 12 | class InorderTraversal { 13 | 14 | public static class TreeNode { 15 | int val; 16 | TreeNode left; 17 | TreeNode right; 18 | TreeNode() {} 19 | TreeNode(int val) { this.val = val; } 20 | TreeNode(int val, TreeNode left, TreeNode right) { 21 | this.val = val; 22 | this.left = left; 23 | this.right = right; 24 | } 25 | } 26 | 27 | public List < Integer > inorderTraversal(TreeNode root) { 28 | List < Integer > res = new ArrayList < > (); 29 | Stack < TreeNode > stack = new Stack < > (); 30 | TreeNode curr = root; 31 | while (curr != null || !stack.isEmpty()) { 32 | while (curr != null) { 33 | stack.push(curr); 34 | curr = curr.left; 35 | } 36 | curr = stack.pop(); 37 | res.add(curr.val); 38 | curr = curr.right; 39 | } 40 | return res; 41 | } 42 | public static void main(String args[]) 43 | { 44 | InorderTraversal it = new InorderTraversal(); 45 | TreeNode tree = new TreeNode(1); 46 | tree.right = new TreeNode(2); 47 | tree.right.left = new TreeNode(3); 48 | 49 | System.out.println(it.inorderTraversal(tree)); 50 | 51 | System.out.println("Passed all test cases"); 52 | } 53 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/java/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Invert a binary tree. 3 | * 4 | * Problem: 5 | * Invert a binary tree. 6 | * 7 | * Execution: javac InvertBinaryTree.java && java InvertBinaryTree 8 | */ 9 | import java.util.*; 10 | 11 | 12 | class InvertBinaryTree { 13 | 14 | public static class TreeNode { 15 | int val; 16 | TreeNode left; 17 | TreeNode right; 18 | TreeNode() {} 19 | TreeNode(int val) { this.val = val; } 20 | TreeNode(int val, TreeNode left, TreeNode right) { 21 | this.val = val; 22 | this.left = left; 23 | this.right = right; 24 | } 25 | } 26 | 27 | public TreeNode invertBinaryTree(TreeNode root) { 28 | if (root == null) { 29 | return null; 30 | } 31 | TreeNode right = invertBinaryTree(root.right); 32 | TreeNode left = invertBinaryTree(root.left); 33 | root.left = right; 34 | root.right = left; 35 | return root; 36 | } 37 | 38 | public static void main(String args[]) 39 | { 40 | InvertBinaryTree ibt = new InvertBinaryTree(); 41 | TreeNode tree = new TreeNode(4); 42 | tree.right = new TreeNode(7); 43 | tree.right.left = new TreeNode(6); 44 | tree.left = new TreeNode(2); 45 | tree.left.left = new TreeNode(1); 46 | tree.left.right = new TreeNode(3); 47 | tree.right.right = new TreeNode(9); 48 | 49 | System.out.println(ibt.invertBinaryTree(tree)); 50 | 51 | System.out.println("Passed all test cases"); 52 | } 53 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/java/LevelorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Level-order traversal of binary tree 3 | * 4 | * Problem: 5 | * Given a binary tree, return the level-order traversal of its nodes' values. 6 | * 7 | * Execution: javac LevelorderTraversal.java && java LevelorderTraversal 8 | */ 9 | import java.util.*; 10 | 11 | 12 | // A Binary Tree node 13 | class Node { 14 | int data; 15 | Node left, right; 16 | 17 | Node(int value) { 18 | data = value; 19 | left = right = null; 20 | } 21 | } 22 | 23 | 24 | class LevelorderTraversal { 25 | Node root; 26 | 27 | public static List> levelOrderTraversal(Node root) { 28 | List> res = new ArrayList>(); 29 | if(root == null) return res; 30 | 31 | Queue q = new LinkedList(); 32 | q.add(root); 33 | 34 | while(q.isEmpty() == false) { 35 | List currli = new ArrayList(); 36 | int qsize = q.size(); 37 | for(int i = 0; i < qsize; i++) { 38 | Node curr = q.poll(); 39 | currli.add(curr.data); 40 | if(curr.left != null) q.add(curr.left); 41 | if(curr.right != null) q.add(curr.right); 42 | } 43 | res.add(currli); 44 | } 45 | 46 | return res; 47 | } 48 | 49 | public static void main(String args[]) 50 | { 51 | LevelorderTraversal tree = new LevelorderTraversal(); 52 | tree.root = new Node(1); 53 | tree.root.left = new Node(2); 54 | tree.root.right = new Node(3); 55 | tree.root.left.left = new Node(4); 56 | tree.root.left.right = new Node(5); 57 | tree.root.right.left = new Node(6); 58 | tree.root.right.right = new Node(7); 59 | 60 | System.out.println(levelOrderTraversal(tree.root)); 61 | 62 | System.out.println("Passed all test cases"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /quickstart_guides/trees/java/MaxDepthBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Max depth binary tree 3 | * 4 | * Problem: 5 | * Given a binary tree, find height of it. Height of empty tree is 0 and 6 | * height of below tree is 3. 7 | * 8 | * Execution: javac MaxDepthBinaryTree.java && java MaxDepthBinaryTree 9 | */ 10 | 11 | 12 | class Node 13 | { 14 | int data; 15 | Node left, right; 16 | 17 | Node(int item) 18 | { 19 | data = item; 20 | left = right = null; 21 | } 22 | } 23 | 24 | class MaxDepthBinaryTree 25 | { 26 | Node root; 27 | 28 | /* Compute the "maxDepth" of a tree -- the number of 29 | nodes along the longest path from the root node 30 | down to the farthest leaf node.*/ 31 | int maxDepth(Node node) 32 | { 33 | if (node == null) 34 | return 0; 35 | else 36 | { 37 | /* compute the depth of each subtree */ 38 | int lDepth = maxDepth(node.left); 39 | int rDepth = maxDepth(node.right); 40 | 41 | /* use the larger one */ 42 | if (lDepth > rDepth) 43 | return (lDepth + 1); 44 | else 45 | return (rDepth + 1); 46 | } 47 | } 48 | 49 | /* Driver program to test above functions */ 50 | public static void main(String[] args) 51 | { 52 | BinaryTree tree = new BinaryTree(); 53 | 54 | tree.root = new Node(1); 55 | tree.root.left = new Node(2); 56 | tree.root.right = new Node(3); 57 | tree.root.left.left = new Node(4); 58 | tree.root.left.right = new Node(5); 59 | 60 | assert tree.maxDepth(tree.root) == 3; 61 | 62 | System.out.println("All tests passed."); 63 | } 64 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/java/MaxPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Max path sum 3 | * 4 | * Problem: 5 | * Given a non-empty binary tree, find the maximum path sum. 6 | * 7 | * For this problem, a path is defined as any sequence of nodes from some 8 | * starting node to any node in the tree along the parent-child connections. 9 | * The path must contain at least one node and does not need to go through the 10 | * root. 11 | * 12 | * Execution: javac MaxPathSum.java && java MaxPathSum 13 | */ 14 | import java.util.*; 15 | 16 | 17 | class MaxPathSum { 18 | 19 | public static class TreeNode { 20 | int val; 21 | TreeNode left; 22 | TreeNode right; 23 | TreeNode() {} 24 | TreeNode(int val) { this.val = val; } 25 | TreeNode(int val, TreeNode left, TreeNode right) { 26 | this.val = val; 27 | this.left = left; 28 | this.right = right; 29 | } 30 | } 31 | static int max_sum; 32 | public static int maxPathSum(TreeNode root) { 33 | max_sum = Integer.MIN_VALUE; 34 | max_gain(root); 35 | return max_sum; 36 | } 37 | 38 | public static int max_gain(TreeNode root){ 39 | if(root == null){ 40 | return 0; 41 | } 42 | 43 | int leftGain = Math.max(max_gain(root.left), 0); 44 | int rightGain = Math.max(max_gain(root.right), 0); 45 | int sum = root.val + leftGain + rightGain; 46 | max_sum = Math.max(max_sum, sum); 47 | return root.val + Math.max(leftGain, rightGain); 48 | } 49 | 50 | public static void main(String args[]) 51 | { 52 | MaxPathSum mbt = new MaxPathSum(); 53 | 54 | TreeNode tree1 = new TreeNode(1); 55 | tree1.left = new TreeNode(3); 56 | tree1.right = new TreeNode(2); 57 | tree1.left.left = new TreeNode(5); 58 | 59 | assert mbt.maxPathSum(tree1) == 1 + 2 + 3 + 5; 60 | 61 | System.out.println("Passed all test cases"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /quickstart_guides/trees/java/PreorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Pre-order traversal of binary tree 3 | * 4 | * Problem: 5 | * Given a binary tree, return the preorder traversal of its nodes' values. 6 | * 7 | * Execution: javac PreorderTraversal.java && java PreorderTraversal 8 | */ 9 | import java.util.*; 10 | 11 | 12 | class PreorderTraversal { 13 | 14 | public static class TreeNode { 15 | int val; 16 | TreeNode left; 17 | TreeNode right; 18 | TreeNode() {} 19 | TreeNode(int val) { this.val = val; } 20 | TreeNode(int val, TreeNode left, TreeNode right) { 21 | this.val = val; 22 | this.left = left; 23 | this.right = right; 24 | } 25 | } 26 | 27 | public List preorderTraversal(TreeNode root) { 28 | List list = new ArrayList<>(); 29 | return porder(root, list); 30 | } 31 | 32 | public List porder(TreeNode root, List list) { 33 | if(root == null) return list; 34 | list.add(root.val); 35 | porder(root.left, list); 36 | porder(root.right, list); 37 | return list; 38 | } 39 | 40 | public static void main(String args[]) 41 | { 42 | PreorderTraversal pt = new PreorderTraversal(); 43 | TreeNode tree = new TreeNode(1); 44 | tree.right = new TreeNode(2); 45 | tree.right.left = new TreeNode(3); 46 | 47 | System.out.println(pt.preorderTraversal(tree)); 48 | 49 | System.out.println("Passed all test cases"); 50 | } 51 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/java/TreeToList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Tree to list 3 | * 4 | * Problem: 5 | * Given a tree, write a function to convert it into a circular doubly linked 6 | * list from left to right by only modifying the existing pointers. 7 | * 8 | * Execution: javac TreeToList.java && java TreeToList 9 | */ 10 | import java.util.*; 11 | 12 | 13 | class TreeToList { 14 | 15 | public static class TreeNode { 16 | int val; 17 | TreeNode left; 18 | TreeNode right; 19 | TreeNode() {} 20 | TreeNode(int val) { this.val = val; } 21 | TreeNode(int val, TreeNode left, TreeNode right) { 22 | this.val = val; 23 | this.left = left; 24 | this.right = right; 25 | } 26 | } 27 | 28 | public void flatten(TreeNode root) { 29 | 30 | if(root == null) return; 31 | 32 | TreeNode rightTmp = null; 33 | flatten(root.left); 34 | flatten(root.right); 35 | rightTmp = root.right; 36 | 37 | if(root.left != null){ 38 | root.right = root.left; 39 | TreeNode endNode = getEndNode(root.right); 40 | endNode.right = rightTmp; 41 | root.left = null; 42 | } 43 | 44 | } 45 | 46 | TreeNode getEndNode(TreeNode node){ 47 | if(node == null) return null; 48 | 49 | while(node.right != null){ 50 | node = node.right; 51 | } 52 | return node; 53 | } 54 | 55 | public static void main(String args[]) 56 | { 57 | TreeToList d = new TreeToList(); 58 | TreeNode tree = new TreeNode(1); 59 | tree.right = new TreeNode(2); 60 | tree.right.left = new TreeNode(3); 61 | 62 | assert d.getEndNode(tree).val == 2; 63 | d.flatten(tree); 64 | assert d.getEndNode(tree).val == 3; 65 | 66 | System.out.println("Passed all test cases"); 67 | } 68 | } -------------------------------------------------------------------------------- /quickstart_guides/trees/python/diameter_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Diameter of binary tree 3 | 4 | Problem: 5 | Given a binary tree, you need to compute the length of the diameter of the 6 | tree. The diameter of a binary tree is the length of the longest path 7 | between any two nodes in a tree. This path may or may not pass through the 8 | root. 9 | 10 | Execution: python diameter_of_binary_tree.py 11 | """ 12 | import unittest 13 | 14 | 15 | class TreeNode: 16 | def __init__(self, val=0, left=None, right=None): 17 | self.val = val 18 | self.left = left 19 | self.right = right 20 | 21 | 22 | def _diam(node: TreeNode, depth: int) -> [int, int]: 23 | if node is None: 24 | return depth, 0 25 | depth += 1 26 | left_depth, left_sum = _diam(node.left, depth) 27 | right_depth, right_sum = _diam(node.right, depth) 28 | new_size = (left_depth - depth) + (right_depth - depth) 29 | return max(left_depth, right_depth), max(new_size, left_sum, right_sum) 30 | 31 | 32 | def diameter_of_binary_tree(root: TreeNode) -> int: 33 | return _diam(root, 0)[1] 34 | 35 | 36 | class TestDiameterOfBinaryTree(unittest.TestCase): 37 | """Unit tests for diameter_of_binary_tree.""" 38 | 39 | def test_1(self): 40 | tn = TreeNode(1) 41 | tn.left = TreeNode(2) 42 | tn.right = TreeNode(3) 43 | tn.left.left = TreeNode(4) 44 | tn.left.right = TreeNode(5) 45 | self.assertEqual(diameter_of_binary_tree(tn), 3) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/inorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: In-order traversal 3 | 4 | Problem: 5 | Given a binary tree, return the inorder traversal of its nodes' values. 6 | 7 | Execution: python inorder_traversal.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def inorder_traversal(root: TreeNode) -> List[int]: 21 | """Perform in-order traversal.""" 22 | 23 | def traverse(root, out, visited): 24 | if root: 25 | out = traverse(root.left, out, visited) 26 | if root not in visited: 27 | visited.append(root) 28 | out.append(root.val) 29 | out = traverse(root.right, out, visited) 30 | return out 31 | 32 | return traverse(root, [], []) 33 | 34 | 35 | class TestInorderTraversal(unittest.TestCase): 36 | """Unit tests for inorder_traversal.""" 37 | 38 | def test_1(self): 39 | tn = TreeNode(1) 40 | tn.right = TreeNode(2) 41 | tn.right.left = TreeNode(3) 42 | self.assertEqual(inorder_traversal(tn), [1, 3, 2]) 43 | 44 | 45 | if __name__ == "__main__": 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/invert_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Invert binary tree 3 | 4 | Problem: 5 | Invert a binary tree. 6 | 7 | Execution: python invert_binary_tree.py 8 | """ 9 | from typing import Optional 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def invert_binary_tree(t: TreeNode) -> Optional[TreeNode]: 21 | if t is None: 22 | return None 23 | right = invert_binary_tree(t.right) 24 | left = invert_binary_tree(t.left) 25 | 26 | t.left = right 27 | t.right = left 28 | 29 | return t 30 | 31 | 32 | class TestInvertBinaryTree(unittest.TestCase): 33 | """Unit tests for invert_binary_tree.""" 34 | 35 | def test_1(self): 36 | t1 = TreeNode(4) 37 | t1.left = TreeNode(2) 38 | t1.right = TreeNode(7) 39 | t1.left.left = TreeNode(1) 40 | t1.left.right = TreeNode(3) 41 | t1.right.left = TreeNode(6) 42 | t1.right.right = TreeNode(9) 43 | 44 | t2 = invert_binary_tree(t1) 45 | 46 | self.assertEqual(t2.val, 4) 47 | self.assertEqual(t2.left.val, 7) 48 | self.assertEqual(t2.right.val, 2) 49 | self.assertEqual(t2.left.left.val, 9) 50 | self.assertEqual(t2.left.right.val, 6) 51 | self.assertEqual(t2.right.left.val, 3) 52 | self.assertEqual(t2.right.right.val, 1) 53 | 54 | 55 | if __name__ == "__main__": 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/levelorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Levelorder traversal 3 | 4 | Problem: 5 | Given a binary tree, return the level-order traversal of its nodes' values. 6 | 7 | Execution: python levelorder_traversal.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def helper_util(lst, rst, result, level): 21 | # To add layer to the stack 22 | if len(result) < level: 23 | result.append([]) 24 | 25 | # Keep tracking the left sub tree 26 | if lst is not None: 27 | result[level - 1].extend([lst.val]) 28 | helper_util(lst.left, lst.right, result, level + 1) 29 | 30 | # Keep tracking the right sub tree 31 | if rst is not None: 32 | result[level - 1].extend([rst.val]) 33 | helper_util(rst.left, rst.right, result, level + 1) 34 | 35 | return result 36 | 37 | 38 | def levelorder_traversal(root: TreeNode) -> List[List[int]]: 39 | 40 | if root is None: 41 | return [] 42 | 43 | result = [[root.val]] 44 | lst = root.left 45 | rst = root.right 46 | 47 | result = helper_util(lst, rst, result, 2) 48 | 49 | result = [x for x in result if len(x) != 0] 50 | 51 | return result 52 | 53 | 54 | class TestLevelorderTraversal(unittest.TestCase): 55 | """Unit tests for levelorder_traversal.""" 56 | 57 | def test_1(self): 58 | tn = TreeNode(3) 59 | tn.right = TreeNode(20) 60 | tn.left = TreeNode(9) 61 | tn.right.left = TreeNode(15) 62 | tn.right.right = TreeNode(7) 63 | self.assertEqual(levelorder_traversal(tn), [[3], [9, 20], [15, 7]]) 64 | 65 | 66 | if __name__ == "__main__": 67 | unittest.main() 68 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/max_depth_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Maximum depth of binary tree 3 | 4 | Problem: 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the 8 | root node down to the farthest leaf node. 9 | 10 | Note: A leaf is a node with no children. 11 | 12 | Execution: python max_depth_binary_tree.py 13 | """ 14 | import unittest 15 | 16 | 17 | class TreeNode: 18 | def __init__(self, val=0, left=None, right=None) -> None: 19 | self.val = val 20 | self.left = left 21 | self.right = right 22 | 23 | 24 | def max_depth_binary_tree(root: TreeNode) -> int: 25 | if root is None: 26 | return 0 27 | left = max_depth_binary_tree(root.left) + 1 28 | right = max_depth_binary_tree(root.right) + 1 29 | if left > right: 30 | return left 31 | return right 32 | 33 | 34 | class TestMaxDepthBinaryTree(unittest.TestCase): 35 | """Unit tests for max_depth_binary_tree.""" 36 | 37 | def test_1(self): 38 | tn = TreeNode(3) 39 | tn.left = TreeNode(9) 40 | tn.right = TreeNode(20) 41 | tn.right.left = TreeNode(15) 42 | tn.right.right = TreeNode(7) 43 | self.assertEqual(max_depth_binary_tree(tn), 3) 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/postorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Post-order traversal 3 | 4 | Problem: 5 | Given a binary tree, return the post-order traversal of its nodes' values. 6 | 7 | Execution: python postorder_traversal.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def postorder_traversal(root: TreeNode) -> List[int]: 21 | res, stack = [], [(root, False)] 22 | while stack: 23 | node, visited = stack.pop() 24 | if node: 25 | if visited: 26 | # Add to result if visited. 27 | res.append(node.val) 28 | else: 29 | # Post-order traverse. 30 | stack.append((node, True)) 31 | stack.append((node.right, False)) 32 | stack.append((node.left, False)) 33 | return res 34 | 35 | 36 | class TestPostorderTraversal(unittest.TestCase): 37 | """Unit tests for postorder_traversal.""" 38 | 39 | def test_1(self): 40 | tn = TreeNode(1) 41 | tn.right = TreeNode(2) 42 | tn.right.left = TreeNode(3) 43 | self.assertEqual(postorder_traversal(tn), [3, 2, 1]) 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/preorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Preorder traversal 3 | 4 | Problem: 5 | Given a binary tree, return the preorder traversal of its nodes' values. 6 | 7 | Execution: python preorder_traversal.py 8 | """ 9 | from typing import List 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def preorder_traversal(root: TreeNode) -> List[int]: 21 | if not root: 22 | return [] 23 | stack = [root] 24 | visited = [] 25 | out = [] 26 | while stack: 27 | node = stack[-1] 28 | if node and node not in visited: 29 | out.append(node.val) 30 | visited.append(node) 31 | if node.left and node.left not in visited: 32 | stack.append(node.left) 33 | continue 34 | if node.right and node.right not in visited: 35 | stack.append(node.right) 36 | continue 37 | stack.pop() 38 | return out 39 | 40 | 41 | class TestPreorderTraversal(unittest.TestCase): 42 | """Unit tests for preorder_traversal.""" 43 | 44 | def test_1(self): 45 | tn = TreeNode(1) 46 | tn.right = TreeNode(2) 47 | tn.right.left = TreeNode(3) 48 | self.assertEqual(preorder_traversal(tn), [1, 2, 3]) 49 | 50 | 51 | if __name__ == "__main__": 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /quickstart_guides/trees/python/tree_to_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Tree to list 3 | 4 | Problem: 5 | Given a tree, write a function to convert it into a circular doubly linked 6 | list from left to right by only modifying the existing pointers. 7 | 8 | Execution: python tree_to_list.py 9 | """ 10 | import unittest 11 | 12 | 13 | class TreeNode: 14 | def __init__(self, val=0, left=None, right=None) -> None: 15 | self.val = val 16 | self.left = left 17 | self.right = right 18 | 19 | 20 | def flatten(root: TreeNode) -> None: 21 | """ 22 | :type root: TreeNode 23 | :rtype: None Do not return anything, modify root in-place instead. 24 | """ 25 | if not root: 26 | return 27 | stack = [] 28 | 29 | def flatten_helper(root: TreeNode) -> None: 30 | if not root: 31 | return 32 | stack.append(root) 33 | stack.append(root) 34 | if root.left: 35 | flatten_helper(root.left) 36 | if root.right: 37 | flatten_helper(root.right) 38 | 39 | flatten_helper(root) 40 | for i in range(len(stack) - 1): 41 | stack[i].left = None 42 | stack[i].right = stack[i + 1] 43 | stack[-1].left = None 44 | stack[-1].right = None 45 | 46 | 47 | class TestTreeToList(unittest.TestCase): 48 | """Unit tests for tree_to_list.""" 49 | 50 | def test_1(self): 51 | tn = TreeNode(1) 52 | tn.left = TreeNode(2) 53 | tn.right = TreeNode(3) 54 | tn.right.left = TreeNode(4) 55 | tn.right.right = TreeNode(5) 56 | 57 | flatten(tn) 58 | self.assertEqual(tn.val, 1) 59 | self.assertEqual(tn.right.val, 2) 60 | self.assertEqual(tn.right.right.val, 3) 61 | 62 | 63 | if __name__ == "__main__": 64 | unittest.main() 65 | --------------------------------------------------------------------------------