├── AdvancedDataStructures ├── binary_index_tree.py ├── segment_tree.py └── trie.py ├── Arrays ├── chocolate_distribution_problem.py ├── count_subarrays.py ├── count_swap_custom_sort.py ├── element_left_side_smaller.py ├── equilibiruim_point.py ├── find_missing_and_repeating_X.py ├── find_the_maximum.py ├── find_triplet_with_zero_sum.py ├── kadane_s_algorithm.py ├── kth_smallest_element.py ├── largest_in_k_size_window.py ├── largest_subarray_of_sizek_X.py ├── leaders_in_an_array.py ├── longest_number_formed.py ├── majority_element.py ├── maximum_of_all_subarrays_of_size_k.py ├── maximum_sum_increasing_subsequence.py ├── merge_k_sorted_array_X.py ├── merge_overlapping_intervals.py ├── missing_number_in_array.py ├── overlapping_intervals.py ├── print_all_subsets.py ├── pythagorian_triplet.py ├── reverse_array_in_groups.py ├── rotate_by_swap_bloc.py ├── smallest_distinct_window_X.py ├── smallest_positive_number.py ├── smallest_positive_number_X.py ├── sort_an_array_of_0s_1s_and_2s.py ├── subarray_with_given_sum.py └── trapping_rain_water.py ├── BackTracking ├── n_queen.py └── sudoku.py ├── BitMagic ├── all_binary_strings_without_consecutive_1.py ├── alone_in_couple.py ├── bit_difference.py ├── count_set_bits.py ├── longest_consecutive_1s.py ├── power_of_2.py ├── rotate_bits.py ├── set_kth_bit.py ├── sparse_or_not.py ├── swap_odd_even_bits.py └── toggle_bits_given_range.py ├── DivideAndConquer ├── merge_sort.py └── quick_sort.py ├── DynamicProgramming ├── box_stacking.py ├── coin_change.py ├── count_chicks_nth_day.py ├── count_number_of_hops.py ├── count_string_with_abc.py ├── count_subsequence_a^ib^jc^k.py ├── edit_distance.py ├── egg_dropping_puzzle.py ├── get_minimum_squares.py ├── longest_common_subsequence.py ├── longest_increasing_subsequence.py ├── max_sum_coin_game.py ├── minimum_number_of_jumps.py ├── minimum_sum_partition.py ├── pass_the_semester.py ├── path_in_matrix.py ├── reach_score.py ├── shortest_common_supersequence.py ├── subset_sum_problem.py ├── ways_to_sum_n.py └── zero_1_knapsack.py ├── Graph ├── bfs.py ├── circle_of_strings.py ├── detect_cycle_in_directed_graph.py ├── dfs.py ├── find_number_of_islands.py ├── find_whether_path_exists.py ├── floyd_warshall.py ├── implement_dijkstra.py ├── min_cost_path.py ├── minimum_swaps.py ├── shortest_source_to_destination.py └── topological_sort.py ├── Greedy ├── activity_selection.py ├── geek_collects_the_balls.py ├── largest_number_possible.py ├── maximum_toys.py ├── minimize_sum_of_products.py ├── minimum_number_of_coins.py ├── minimum_operations.py ├── n_meetings_in_one_room.py ├── page_faults_in_LRU.py └── shop_in_candy_store.py ├── Hashing ├── largest_subarray_with0sum.py └── swapping_pairs_make_sum_equal.py ├── Heap ├── find_median_in_stream.py ├── heap_sort.py └── kth_largest_element_in_a_stream.py ├── LinkedList ├── add_two_numbers.py ├── detect_loop.py ├── merge_two_sorted_list.py ├── nth_node_from_end.py ├── reverse_link_list_in_groups.py └── reverse_linked_list.py ├── README.md ├── Recursion ├── combination_sum_part2.py ├── flood_fill_algorithm.py ├── josephus_problem.py ├── number_of_paths.py └── water_overflow.py ├── StackAndQueues ├── GetMinElementFromStack.java ├── QueueUsingStack.java ├── StackUsingQueue.java ├── circular_tour.py ├── first_non_repeating_char.py ├── infix_to_postfix..py ├── max_rectangular_area_histogram.py └── next_larger_element.py ├── String ├── anagram.py ├── check_if_string_is_rotated_by_two_places.py ├── concatenation_of_zig_zag_string_X.py ├── count_palindrome_X.py ├── divisible_by_8_X.py ├── form_a_palindrome.py ├── immediate_largest_number.py ├── implement_atoi.py ├── implement_strstr.py ├── longest_common_substring.py ├── longest_common_substring_numbers.py ├── longest_palindrome_in_a_string.py ├── max_prifix_suffix_X.py ├── parenthesis_checker.py ├── permutations_of_a_given_string.py ├── rearrange_character.py ├── recursively_remove_all_adjacent_duplicates.py ├── remove_duplicates.py ├── reverse_words_in_a_given_string.py ├── roll_chars.py ├── sum_string_X.py └── transform_string_X.py └── Tree ├── BinarySearchTree └── array_to_BST.py ├── CheckForBalancedTree.java ├── PrintBottomView.java ├── SerializeDeserialize.java ├── binary_tree_to_dll.py ├── count_leaves_in_tree.py ├── create_tree_from_traversals.py ├── diagonal_traversal.py ├── diameter_binary_tree.py ├── height_binary_tree.py ├── is_preorder_traversal.py ├── level_order_traversal_spiral.py ├── lowest_common_ancestor.py ├── pre_to_post_order.py ├── print_leaf_nodes.py └── two_tree_identical.py /AdvancedDataStructures/binary_index_tree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class BinaryIndexTree: 5 | def __init__(self, arr): 6 | self.arr = arr 7 | self.tree = [0] * (len(arr) + 1) 8 | self.construct_tree(arr=arr) 9 | 10 | def get_range_sum(self, ql, qr): 11 | return self.sum(0, self.arr_len - 1, 0, ql, qr) 12 | 13 | def sum(self, l, r, index, ql, qr): 14 | if qr < l or ql > r: 15 | return 0 16 | if ql <= l and qr >= r: 17 | return self.tree[index] 18 | 19 | mid = (l + r) // 2 20 | 21 | return self.sum(l, mid, 2 * index + 1, ql, qr) + self.sum( 22 | mid + 1, r, 2 * index + 2, ql, qr 23 | ) 24 | 25 | def update(self, key_index, key): 26 | index = key_index + 1 27 | difference = key - self.arr[key_index] 28 | 29 | while index > 0: 30 | self.tree[index] += difference 31 | index = index & (index - 1) 32 | 33 | self.tree[index] += difference 34 | 35 | def construct_tree(self, arr): 36 | for i in range(len(arr)): 37 | index = i + 1 38 | child_sum = arr[i] 39 | while index > 0: 40 | self.tree[index] += child_sum 41 | index = index & (index - 1) 42 | 43 | self.tree[index] += child_sum 44 | 45 | 46 | class TestCase(unittest.TestCase): 47 | def test_segment_tree(self): 48 | arr = [1, 3, 5, 7, 9, 11] 49 | tree = BinaryIndexTree(arr=arr) 50 | print(tree.tree) 51 | tree.update(2, 10) 52 | print(tree.tree) 53 | 54 | print(tree.get_range_sum(0, 2)) 55 | # print(tree.get_range_sum(4, 5)) 56 | # tree.udpate(5, 19) 57 | # print(tree.get_range_sum(4, 5)) 58 | # tree.udpate(2, 10) 59 | # print(tree.get_range_sum(0, 2)) 60 | 61 | 62 | if __name__ == "__main__": 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /AdvancedDataStructures/segment_tree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class SegmentTree: 5 | def __init__(self, arr): 6 | self.arr_len = len(arr) 7 | self.tree = [None] * (2 * len(arr) + 1) 8 | self.construct_tree(arr, 0, len(arr) - 1, 0) 9 | 10 | def get_range_sum(self, ql, qr): 11 | return self.sum(0, self.arr_len - 1, 0, ql, qr) 12 | 13 | def sum(self, l, r, index, ql, qr): 14 | if qr < l or ql > r: 15 | return 0 16 | if ql <= l and qr >= r: 17 | return self.tree[index] 18 | 19 | mid = (l + r) // 2 20 | 21 | return self.sum(l, mid, 2 * index + 1, ql, qr) + self.sum( 22 | mid + 1, r, 2 * index + 2, ql, qr 23 | ) 24 | 25 | def update_key(self, key_index, key, l, r, index): 26 | if l == r and l == key_index: 27 | difference = key - self.tree[index] 28 | self.tree[index] = key 29 | return difference 30 | 31 | mid = (l + r) // 2 32 | 33 | if key_index <= mid: 34 | difference = self.update_key(key_index, key, l, mid, 2 * index + 1) 35 | else: 36 | difference = self.update_key(key_index, key, mid + 1, r, 2 * index + 2) 37 | 38 | self.tree[index] += difference 39 | return difference 40 | 41 | def udpate(self, key_index, key): 42 | self.update_key(key_index, key, 0, self.arr_len - 1, 0) 43 | 44 | def construct_tree(self, arr, l, r, index): 45 | if l == r: 46 | self.tree[index] = arr[l] 47 | return self.tree[index] 48 | 49 | mid = (l + r) // 2 50 | 51 | self.tree[index] = self.construct_tree( 52 | arr, l, mid, 2 * index + 1 53 | ) + self.construct_tree(arr, mid + 1, r, 2 * index + 2) 54 | 55 | return self.tree[index] 56 | 57 | 58 | class TestCase(unittest.TestCase): 59 | def test_segment_tree(self): 60 | arr = [1, 3, 5, 7, 9, 11] 61 | tree = SegmentTree(arr=arr) 62 | 63 | print(tree.get_range_sum(0, 2)) 64 | print(tree.get_range_sum(4, 5)) 65 | tree.udpate(5, 19) 66 | print(tree.get_range_sum(4, 5)) 67 | tree.udpate(2, 10) 68 | print(tree.get_range_sum(0, 2)) 69 | 70 | 71 | if __name__ == "__main__": 72 | unittest.main() 73 | -------------------------------------------------------------------------------- /AdvancedDataStructures/trie.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class TreeNode: 5 | def __init__(self): 6 | self.children = [None] * 26 7 | self.is_leaf = False 8 | 9 | 10 | class Trie: 11 | def __init__(self): 12 | self.root = TreeNode() 13 | 14 | def insert(self, key): 15 | current_node = self.root 16 | for char in key: 17 | if not current_node.children[self._get_char_index(char)]: 18 | current_node.children[self._get_char_index(char)] = TreeNode() 19 | current_node = current_node.children[self._get_char_index(char)] 20 | 21 | current_node.is_leaf = True 22 | 23 | def search(self, key): 24 | current_node = self.root 25 | for char in key: 26 | if not current_node.children[self._get_char_index(char)]: 27 | return False 28 | else: 29 | current_node = current_node.children[self._get_char_index(char)] 30 | 31 | if current_node.is_leaf: 32 | return True 33 | else: 34 | return False 35 | 36 | def _get_char_index(self, char): 37 | return ord(char) - ord("a") 38 | 39 | 40 | class TestCase(unittest.TestCase): 41 | def test_sample(self): 42 | keys = ["the", "a", "there", "anaswe", "any", "by", "their"] 43 | 44 | trie = Trie() 45 | for key in keys: 46 | trie.insert(key) 47 | 48 | search_keys = ["the", "a", "there", "anaswe", "any", "by", "amk"] 49 | for key in search_keys: 50 | if trie.search(key): 51 | print("Present!") 52 | else: 53 | print("Absent!") 54 | 55 | 56 | if __name__ == "__main__": 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /Arrays/chocolate_distribution_problem.py: -------------------------------------------------------------------------------- 1 | # Given an array A[] of N integers where each value represents number of chocolates in a packet. Each packet can have variable number of chocolates. There are m students, the task is to distribute chocolate packets such that : 2 | # 1. Each student gets one packet. 3 | # 2. The difference between the number of chocolates given to the students in packet with maximum chocolates and packet with minimum chocolates is minimum. 4 | 5 | 6 | 7 | # Examples 8 | 9 | # Input : A[] = {3, 4, 1, 9, 56, 7, 9, 12} 10 | # m = 5 11 | # Output: Minimum Difference is 6 12 | # We may pick 3,4,7,9,9 and the output 13 | # is 9-3 = 6 14 | 15 | 16 | # Input : A[] = {7, 3, 2, 4, 9, 12, 56} 17 | # m = 3 18 | # Output: Minimum difference is 2 19 | # We can pick 2, 3 and 4 and get the minimum 20 | # difference between maximum and minimum packet 21 | # sizes. ie 4-2 = 2 22 | 23 | 24 | # Input: 25 | # The first line of input contains an integer T, denoting the no of test cases. Then T test cases follow. Each test case consists of three lines. The first line of each test case contains an integer N denoting the no of packets. Then in the next line are N space separated values of the array A[] denoting the values of each packet. The third line of each test case contains an integer m denoting the no of students. 26 | 27 | # Output: 28 | # For each test case in a new line print the required answer . 29 | 30 | # Constraints: 31 | # 1 <=T<= 100 32 | # 1 <=N<= 100 33 | # 1 <=A[]<= 100 34 | # 1 <=m <=N 35 | 36 | # Example: 37 | # Input: 38 | # 2 39 | # 8 40 | # 3 4 1 9 56 7 9 12 41 | # 5 42 | # 7 43 | # 7 3 2 4 9 12 56 44 | # 3 45 | # Output: 46 | # 6 47 | # 2 48 | 49 | 50 | 51 | def ch_ds(arr,s,e,m,matrix): 52 | if matrix[s][e]!=-1: 53 | return matrix[s][e] 54 | if e-s+1 == m: 55 | matrix[s][e] = arr[e]-arr[s] 56 | return matrix[s][e] 57 | matrix[s][e] = min(ch_ds(arr,s,e-1,m,matrix),ch_ds(arr,s+1,e,m,matrix)) 58 | return matrix[s][e] 59 | 60 | t = int(input()) 61 | 62 | for i in range(0,t): 63 | n = int(input()) 64 | arr = [int(x) for x in input().strip().split(" ")] 65 | m = int(input()) 66 | arr = sorted(arr) 67 | matrix = [[-1]*len(arr)]*len(arr) 68 | print(ch_ds(arr,0,n-1,m,matrix)) 69 | 70 | -------------------------------------------------------------------------------- /Arrays/count_subarrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k/0 3 | 4 | Given an array of positive numbers, the task is to find the number of possible contiguous subarrays having product less than a given number K. 5 | 6 | Input: 7 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains two integers N & K and the second line contains N space separated array elements. 8 | 9 | Output: 10 | For each test case, print the count of required subarrays in new line. 11 | 12 | Constraints: 13 | 1<=T<=200 14 | 1<=N<=105 15 | 1<=K<=1015 16 | 1<=A[i]<=105 17 | 18 | Example: 19 | Input: 20 | 2 21 | 4 10 22 | 1 2 3 4 23 | 7 100 24 | 1 9 2 8 6 4 3 25 | 26 | Output: 27 | 7 28 | 16 29 | 30 | Explanation: 31 | 32 | Input : A[]={1, 2,3,4} 33 | K = 10 34 | Output : 7 35 | The contiguous subarrays are {1}, {2}, {3}, {4} 36 | {1, 2}, {1, 2, 3} and {2, 3} whose count is 7. 37 | 38 | """ 39 | 40 | 41 | def count(n): 42 | total = 0 43 | for i in range(1,n+1): 44 | total = total+(n-i+1) 45 | return total 46 | 47 | def count_subset(arr,n,k): 48 | i = 0 49 | j = 0 50 | 51 | multi = 1 52 | subset = 0 53 | sep = -1 54 | while(j= k and i<=j): 62 | multi//=arr[i] 63 | i+=1 64 | sep = j-1 65 | j+=1 66 | 67 | subset+=count(j-i)-count(sep-i+1) 68 | 69 | print(subset) 70 | 71 | def main(): 72 | t = int(input()) 73 | for i in range(t): 74 | n,k = list(map(int,input().split())) 75 | arr = list(map(int,input().split())) 76 | count_subset(arr,n,k) 77 | 78 | 79 | if __name__ == '__main__': 80 | main() -------------------------------------------------------------------------------- /Arrays/count_swap_custom_sort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def count_sort_count(arr): 5 | i = 0 6 | j = len(arr) - 1 7 | 8 | count = 0 9 | while (i < j): 10 | while arr[i] % 2 == 0: 11 | i += 1 12 | 13 | while arr[j] % 2 == 1: 14 | j -= 1 15 | 16 | i += 1 17 | j -= 1 18 | count += 1 19 | 20 | return count 21 | 22 | 23 | class TestCase(unittest.TestCase): 24 | def test_custom_sort_count(self): 25 | arr = [2, 3, 4, 5, 6, 7, 1, 5, 6] 26 | result = count_sort_count(arr) 27 | print(result) 28 | 29 | 30 | if __name__ == "__main__": 31 | unittest.main() -------------------------------------------------------------------------------- /Arrays/element_left_side_smaller.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/unsorted-array/0 3 | 4 | Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it. 5 | 6 | Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element. 7 | 8 | Input: 9 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains an Integer N denoting size of array and the second line contains N space separated array elements. 10 | 11 | Output: 12 | For each test case, in a new line print the required element. If no such element present in array then print -1. 13 | 14 | Constraints: 15 | 1<=T<=100 16 | 3<=N<=106 17 | 1<=A[i]<=106 18 | 19 | Example: 20 | Input: 21 | 3 22 | 4 23 | 4 2 5 7 24 | 3 25 | 11 9 12 26 | 6 27 | 4 3 2 7 8 9 28 | 29 | Output: 30 | 5 31 | -1 32 | 7 33 | 34 | """ 35 | def find_left_side_smaller(arr,n): 36 | if len(arr) == 0: 37 | return -1 38 | left_max = arr[0] 39 | left = [] 40 | for i in range(1,n-1): 41 | if arr[i]>=left_max: 42 | left.append(i) 43 | left_max = arr[i] 44 | 45 | right_min = arr[n-1] 46 | right = [] 47 | for i in range(1,n-1): 48 | if arr[n-1-i] <= right_min: 49 | right.append(n-1-i) 50 | right_min = arr[n-1-i] 51 | 52 | for i in left: 53 | if i in right: 54 | return arr[i] 55 | return -1 56 | 57 | def main(): 58 | t = int(input()) 59 | for i in range(t): 60 | n = int(input().strip(" ")) 61 | arr = [int(x) for x in input().strip(" ").split(" ")] 62 | print(find_left_side_smaller(arr,n)) 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /Arrays/equilibiruim_point.py: -------------------------------------------------------------------------------- 1 | # Given an array A your task is to tell at which position the equilibrium first occurs in the array. Equilibrium position in an array is a position such that the sum of elements below it is equal to the sum of elements after it. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the no of test cases then T test cases follow. First line of each test case contains an integer N denoting the size of the array. Then in the next line are N space separated values of the array A. 5 | 6 | # Output: 7 | # For each test case in a new line print the position at which the elements are at equilibrium if no equilibrium point exists print -1. 8 | 9 | # Constraints: 10 | # 1<=T<=100 11 | # 1<=N<=100 12 | 13 | # Example: 14 | # Input: 15 | # 2 16 | # 1 17 | # 1 18 | # 5 19 | # 1 3 5 2 2 20 | 21 | # Output: 22 | # 1 23 | # 3 24 | 25 | # Explanation: 26 | # 1. Since its the only element hence its the only equilibrium point 27 | # 2. For second test case equilibrium point is at position 3 as elements below it (1+3) = elements after it (2+2) 28 | 29 | 30 | def equilibrium_point(arr,n): 31 | 32 | total = 0 33 | for item in arr: 34 | total = total + item 35 | 36 | left_sum = 0 37 | right_sum = total 38 | 39 | for i in range(0,n): 40 | right_sum = right_sum - arr[i] 41 | if left_sum == right_sum: 42 | print(i+1) 43 | return 44 | left_sum = left_sum + arr[i] 45 | print(-1) 46 | return 47 | 48 | t = int(input()) 49 | 50 | for i in range(0,t): 51 | numbers = input().strip().split() 52 | n = int(numbers[0]) 53 | 54 | arr = [int(x) for x in input().strip().split(" ")] 55 | equilibrium_point(arr,n) -------------------------------------------------------------------------------- /Arrays/find_missing_and_repeating_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an unsorted array of size n. Array elements are in range from 1 to n. One number 'A' from set {1, 2, …n} is missing and one number 'B' occurs twice in array. Find these two numbers. 4 | Note: If you find multiple answers then print the Smallest number found. 5 | 6 | Input: 7 | 8 | The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. 9 | The first line of each test case contains a single integer N denoting the size of array. 10 | The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. 11 | 12 | 13 | Output: 14 | 15 | Print B, the repeating number followed by A which is missing in a single line. 16 | 17 | 18 | Constraints: 19 | 20 | 1 ≤ T ≤ 40 21 | 1 ≤ N ≤ 100 22 | 1 ≤ A[i] ≤ N 23 | 24 | 25 | Example: 26 | 27 | Input 28 | 2 29 | 2 30 | 2 2 31 | 3 32 | 1 3 3 33 | Output 34 | 2 1 35 | 3 2 36 | 37 | """ 38 | 39 | 40 | def find_missing_repeating(arr,n): 41 | 42 | 43 | 44 | def test(): 45 | 46 | 47 | def main(): 48 | 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /Arrays/find_the_maximum.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/find-the-maximum-sum/0 3 | 4 | Given an array of n elements.Find the maximum sum when the array elements will be arranged in such way. Multiply the elements of each pair and add to get maximum Sum. Sum could be larger so take mod with 10^9+7. 5 | 6 | Example1: 7 | Input: n=7 8 | -1,9,4,5,-4,-7,0 9 | Output: 77 10 | So to get the maximum sum,the arrangement will be {-7,-4},{-1,0},{9,5} and {4}.So the answer is (-7*(-4))+((-1)*0)+(9*5)+(4) ={77}. 11 | 12 | Example2: 13 | Input: n=3 14 | -1,0,1 15 | Output: 1 16 | So to get the maximum sum,the arrangement will be {-1,0} and {1}.So the answer is ((-1)*0)+(1)={1}. 17 | Input: 18 | The first line consists of an integer T i.e number of test cases. The first line of each test case consists of an integer n.The next line consists of n spaced integers(positive or negative). 19 | 20 | Output: 21 | Print the maximum sum % 10^9+7. 22 | 23 | Constraints: 24 | 1<=T<=100 25 | 1<=n,a[i]<=10000 26 | 27 | Example: 28 | Input: 29 | 2 30 | 3 31 | 8 7 9 32 | 6 33 | -1 9 4 5 -4 7 34 | 35 | Output: 36 | 79 37 | 87 38 | 39 | """ 40 | 41 | def max_sum(arr,n): 42 | arr = sorted(arr) 43 | 44 | total = 0 45 | 46 | r = n-2 47 | while(r>=0): 48 | if arr[r]>0 and arr[r+1] > 0: 49 | total+=arr[r]*arr[r+1] 50 | else: 51 | break 52 | r-=2 53 | if r == -2: 54 | return total 55 | if r == -1: 56 | return total + arr[0] 57 | 58 | l = 0 59 | # print(arr) 60 | while(l large: 90 | print(result%large) 91 | else: 92 | print(result) 93 | 94 | if __name__ == '__main__': 95 | main() -------------------------------------------------------------------------------- /Arrays/find_triplet_with_zero_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | problem statement: 3 | """ 4 | 5 | import unittest 6 | 7 | 8 | def find_triplet(arr): 9 | arr = sorted(arr) # nlogn step 10 | l = 0 11 | r = len(arr) - 1 12 | 13 | 14 | class TestCase(unittest.TestCase): 15 | def test_triplet_sum(self): 16 | dataT = [([0, -1, 2, -3, 1], (-1, 0, 1))] 17 | for test in dataT: 18 | result = find_triplet(test[0]) 19 | assert result == test[1] 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /Arrays/kadane_s_algorithm.py: -------------------------------------------------------------------------------- 1 | # Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. 5 | 6 | # Output: 7 | # Print the maximum sum of the contiguous sub-array in a separate line for each test case. 8 | 9 | # Constraints: 10 | # 1 ≤ T ≤ 200 11 | # 1 ≤ N ≤ 1000 12 | # -100 ≤ A[i] <= 100 13 | 14 | # Example: 15 | # Input 16 | # 2 17 | # 3 18 | # 1 2 3 19 | # 4 20 | # -1 -2 -3 -4 21 | # Output 22 | # 6 23 | # -1 24 | 25 | def kadane_algorithm(arr): 26 | _sum = -1000 27 | max_sum = -1000; 28 | for item in arr: 29 | _sum = max(_sum,0) + item 30 | if _sum > max_sum: 31 | max_sum = _sum 32 | return max_sum 33 | 34 | t = int(input()) 35 | 36 | for i in range(0,t): 37 | n = int(input()) 38 | # print 39 | arr = [int(x) for x in input().strip().split(" ")] 40 | print(kadane_algorithm(arr)) 41 | -------------------------------------------------------------------------------- /Arrays/kth_smallest_element.py: -------------------------------------------------------------------------------- 1 | # Given an array and a number k where k is smaller than size of array, the task is to find the k’th smallest element in the given array. It is given that all array elements are distinct. 2 | 3 | # Input: 4 | 5 | # First Line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. First line of each test case contains an integer N denoting size of the array. Second line contains N space separated integer denoting elements of the array. Third line of the test case contains an integer K. 6 | 7 | # Output: 8 | 9 | # Corresponding to each test case, print the desired output in a new line. 10 | 11 | # Constraints: 12 | 13 | # 1<=T<=200 14 | # 1<=N<=1000 15 | # K 16 | 17 | # Expected Time Complexity: O(n) 18 | 19 | # Example: 20 | 21 | # INPUT 22 | # 2 23 | # 6 24 | # 7 10 4 3 20 15 25 | # 3 26 | # 5 27 | # 7 10 4 20 15 28 | # 4 29 | 30 | # Output: 31 | 32 | # 7 33 | # 15 34 | 35 | def left(i): 36 | return 2*i+1 37 | def right(i): 38 | return 2*i+2 39 | def heapify(arr,i): 40 | n = len(arr) 41 | small_index = i 42 | if left(i) < n and arr[left(i)] < arr[small_index]: 43 | small_index = left(i) 44 | if right(i) < n and arr[right(i)] < arr[small_index]: 45 | small_index = right(i) 46 | # if small index is different then swap 47 | if small_index != i: 48 | arr[small_index],arr[i] = arr[i],arr[small_index] 49 | return heapify(arr,small_index) 50 | return arr 51 | 52 | def make_heap(arr,n): 53 | index = int(n/2) 54 | while(index > -1): 55 | arr = heapify(arr,index) 56 | index = index - 1 57 | return arr 58 | 59 | def kth_smallest_element(arr,n,k): 60 | arr = make_heap(arr,n) 61 | while(k>1 and n>1): 62 | arr[0],arr[n-1] = arr[n-1],arr[0] 63 | del(arr[n-1]) 64 | arr = heapify(arr,0) 65 | k = k-1 66 | n = n-1 67 | return arr[0] 68 | 69 | 70 | t = int(input()) 71 | 72 | for i in range(0,t): 73 | n = int(input()) 74 | arr = [int(x) for x in input().strip().split(" ")] 75 | k = int(input()) 76 | print(kth_smallest_element(arr,n,k)) -------------------------------------------------------------------------------- /Arrays/largest_in_k_size_window.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from collections import deque 3 | 4 | 5 | def largest_k_window(arr, k): 6 | q = deque() 7 | 8 | result = [] 9 | 10 | for i in range(len(arr)): 11 | if len(q) == 0: 12 | q.append(i) 13 | continue 14 | 15 | while len(q) != 0 and arr[i] > arr[q[-1]]: 16 | q.pop() 17 | q.append(i) 18 | 19 | if i - k == q[0]: 20 | q.popleft() 21 | 22 | if i >= k - 1: 23 | result.append(arr[q[0]]) 24 | return result 25 | 26 | 27 | class TestCase(unittest.TestCase): 28 | def test_largest_in_k_window(self): 29 | dataT = [ 30 | ([8, 5, 10, 7, 9, 4, 15, 12, 90, 13], 4), 31 | ([12, 1, 78, 90, 57, 89, 56], 3), 32 | ([1, 2, 3, 1, 4, 5, 2, 3, 6], 3), 33 | ] 34 | 35 | for item in dataT: 36 | result = largest_k_window(item[0], item[1]) 37 | print(result) 38 | 39 | 40 | if __name__ == "__main__": 41 | unittest.main() 42 | -------------------------------------------------------------------------------- /Arrays/largest_subarray_of_sizek_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/largest-sum-subarray-of-size-at-least-k/0 3 | 4 | Given an array and a number k, find the largest sum of the subarray containing at least k numbers. It may be assumed that the size of array is at-least k. 5 | 6 | Input:​ 7 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. Then the following line contains n space separated integers. The last line of the input contains the number k. 8 | 9 | Output: 10 | Print the value of the largest sum of the subarray containing at least k numbers. 11 | 12 | Constraints: 13 | 1<=T<=10^5 14 | 1<=n<=10^5 15 | 1<=a[i]<=10^5 16 | 1<=k<=n 17 | 18 | Example: 19 | Input: 20 | 2 21 | 4 22 | -4 -2 1 -3 23 | 2 24 | 6 25 | 1 1 1 1 1 1 26 | 2 27 | 28 | Output: 29 | -1 30 | 6 31 | 32 | """ 33 | 34 | 35 | def largest_subarray(arr,n,k): 36 | i = 0 37 | j = 0 38 | 39 | arr_sum = 0 40 | max_sum = min(arr) 41 | while(i max_sum): 43 | arr_sum+=arr[j] 44 | j+=1 45 | continue 46 | 47 | if max_sum < arr_sum: 48 | max_sum = arr_sum 49 | 50 | arr_sum = arr_sum-arr[i] 51 | i+=1 52 | 53 | 54 | if arr_sum > max_sum: 55 | max_sum =arr_sum 56 | 57 | return max_sum 58 | 59 | 60 | def test(): 61 | a = [-4, -2, 1, -3] 62 | print(largest_subarray(a,4,2)) 63 | a = [1]*6 64 | print(largest_subarray(a,6,2)) 65 | 66 | if __name__ == '__main__': 67 | # main() 68 | test() 69 | -------------------------------------------------------------------------------- /Arrays/leaders_in_an_array.py: -------------------------------------------------------------------------------- 1 | # Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. The rightmost element is always a leader. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. 5 | # The first line of each test case contains a single integer N denoting the size of array. 6 | # The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. 7 | 8 | # Output: 9 | # Print all the leaders. 10 | 11 | # Constraints: 12 | # 1 <= T <= 100 13 | # 1 <= N <= 100 14 | # 0 <= A[i]<=100 15 | 16 | # Example: 17 | # Input: 18 | # 2 19 | # 6 20 | # 16 17 4 3 5 2 21 | # 5 22 | # 1 2 3 4 0 23 | # Output: 24 | # 17 5 2 25 | # 4 0 26 | 27 | def leaders_in_an_array(arr,n): 28 | reverse_arr = arr[::-1] 29 | 30 | result = [] 31 | max_sofar = -1 32 | for item in reverse_arr: 33 | if item > max_sofar : 34 | result.append(item) 35 | max_sofar = item 36 | for item in result[::-1]: 37 | print(item, end=" ") 38 | print() 39 | 40 | t = int(input()) 41 | 42 | for i in range(0,t): 43 | numbers = input().strip().split() 44 | n = int(numbers[0]) 45 | 46 | arr = [int(x) for x in input().strip().split(" ")] 47 | leaders_in_an_array(arr,n) -------------------------------------------------------------------------------- /Arrays/longest_number_formed.py: -------------------------------------------------------------------------------- 1 | # Given a list of non negative integers, arrange them in such a manner that they form the largest number possible. 2 | 3 | # The result is going to be very large, hence return the result in the form of a string. 4 | 5 | # Input: 6 | 7 | # The first line of input consists number of the test cases. The description of T test cases is as follows: 8 | 9 | # The first line of each test case contains the size of the array, and the second line has the elements of the array. 10 | 11 | 12 | # Output: 13 | 14 | # In each separate line print the largest number formed by arranging the elements of the array in the form of a string. 15 | 16 | 17 | # Constraints: 18 | 19 | # 1 ≤ T ≤ 70 20 | # 1 ≤ N ≤ 100 21 | # 0 ≤ A[i] ≤ 1000 22 | 23 | 24 | # Example: 25 | 26 | # Input: 27 | 28 | # 2 29 | # 5 30 | # 3 30 34 5 9 31 | # 4 32 | # 54 546 548 60 33 | 34 | # Output: 35 | 36 | # 9534330 37 | # 6054854654 38 | 39 | import functools 40 | 41 | def compare(a,b): 42 | ab = int(str(a)+str(b)) 43 | ba = int(str(b)+str(a)) 44 | return ba-ab 45 | 46 | def largestNumber(A): 47 | sorted_a = sorted(A,key=functools.cmp_to_key(compare)) 48 | return int("".join([str(i) for i in sorted_a])) 49 | 50 | t = int(input()) 51 | 52 | for i in range(0,t): 53 | n = int(input()) 54 | arr = [int(x) for x in input().strip().split(" ")] 55 | print(largestNumber(arr)) -------------------------------------------------------------------------------- /Arrays/majority_element.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # Check if an array has a majority element 4 | # Given an array, the task is to find if the input array contains a majority element or not. An element is 5 | 6 | # Examples: 7 | 8 | # Input : arr[] = {2, 3, 9, 2, 2} 9 | # Output : Yes 10 | # A majority element 2 is present in arr[] 11 | 12 | # Input : arr[] = {1, 8, 9, 2, 5} 13 | # Output : No 14 | 15 | 16 | def majority_algorithm(arr): 17 | maj_index = 0 18 | count = 1 19 | 20 | for index in range(1, len(arr)): 21 | if arr[index] == arr[maj_index]: 22 | count += 1 23 | else: 24 | count -= 1 25 | 26 | if count == 0: 27 | maj_index = index 28 | count = 1 29 | 30 | # check if maj_index has is element with more than n/2 count 31 | 32 | count = 0 33 | 34 | for item in arr: 35 | if arr[maj_index] == item: 36 | count += 1 37 | 38 | if count > len(arr) // 2: 39 | return arr[maj_index] 40 | else: 41 | return "No" 42 | 43 | 44 | class Test(unittest.TestCase): 45 | def test_majority_algorithm(self): 46 | data = [([2, 3, 9, 2, 2], 2), ([1, 8, 9, 2, 5], "No")] 47 | for test in data: 48 | self.assertEqual(majority_algorithm(test[0]), test[1]) 49 | 50 | 51 | if __name__ == "__main__": 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /Arrays/maximum_of_all_subarrays_of_size_k.py: -------------------------------------------------------------------------------- 1 | # Given an array and an integer k, find the maximum for each and every contiguous subarray of size k. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. 5 | # The first line of each test case contains a single integer 'N' denoting the size of array and the size of subarray 'k'. 6 | # The second line contains 'N' space-separated integers A1, A2, ..., AN denoting the elements of the array. 7 | 8 | # Output: 9 | # Print the maximum for every subarray of size k. 10 | 11 | # Constraints: 12 | # 1 ≤ T ≤ 200 13 | # 1 ≤ N ≤ 100 14 | # 1 ≤ k ≤ N 15 | # 0 ≤A[i]<1000 16 | 17 | # Example: 18 | 19 | # Input: 20 | # 2 21 | # 9 3 22 | # 1 2 3 1 4 5 2 3 6 23 | # 10 4 24 | # 8 5 10 7 9 4 15 12 90 13 25 | 26 | # Output: 27 | # 3 3 4 5 5 5 6 28 | # 10 10 10 15 15 90 90 29 | 30 | def max_index_arr(arr,s,e): 31 | max_i = s 32 | for i in range(s,e+1): 33 | if arr[i]>arr[max_i]: 34 | max_i = i 35 | return max_i 36 | 37 | 38 | def maximum_of_subarray(arr,n,k): 39 | 40 | if k>=n: 41 | print(arr[max_index_arr(arr,0,n-1)]) 42 | return 43 | 44 | result = [] 45 | max_index = max_index_arr(arr,0,k-2) 46 | for i in range(k-1,n): 47 | if i-k == max_index or arr[max_index] < arr[i]: 48 | max_index = max_index_arr(arr,max_index+1,i) 49 | result.append(arr[max_index]) 50 | 51 | for item in result: 52 | print(item,end=" ") 53 | print() 54 | return 55 | 56 | t = int(input()) 57 | 58 | for i in range(0,t): 59 | numbers = input().strip().split() 60 | n = int(numbers[0]) 61 | k = int(numbers[1]) 62 | arr = [int(x) for x in input().strip().split(" ")] 63 | maximum_of_subarray(arr,n,k) -------------------------------------------------------------------------------- /Arrays/maximum_sum_increasing_subsequence.py: -------------------------------------------------------------------------------- 1 | # Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. 6 | # The first line of each test case is N,N is the size of array. 7 | # The second line of each test case contains N input A[]. 8 | 9 | # Output: 10 | 11 | # Print the sum of maximum sum sequence of the given array. 12 | 13 | # Constraints: 14 | 15 | # 1 ≤ T ≤ 100 16 | # 1 ≤ N ≤ 100 17 | # 1 ≤ A[] ≤ 1000 18 | 19 | # Example: 20 | 21 | # Input: 22 | # 2 23 | # 7 24 | # 1 101 2 3 100 4 5 25 | # 4 26 | # 10 5 4 3 27 | 28 | # Output: 29 | # 106 30 | # 10 31 | 32 | # Explanation: 33 | # For input: 34 | # 7 35 | # 1 101 2 3 100 4 5 36 | # All the increasing subsequences : (1,101); (1,2,3,100); (1,2,3,4,5), out of this (1,2,3,100) has maximum sum,i.e., 106. Hence the output is stated as 106. 37 | 38 | def maximum_sum_subsequence(arr,n): 39 | 40 | subsequence_sum = [0]*len(arr) 41 | for i in range(0,n): 42 | if i == 0 : 43 | subsequence_sum[i] = arr[i] 44 | continue 45 | j = i-1 46 | subsequence_sum[i] = arr[i] 47 | while(j>-1): 48 | if arr[j]subsequence_sum[i]: 49 | subsequence_sum[i] = subsequence_sum[j]+arr[i] 50 | j = j-1 51 | return max(subsequence_sum) 52 | 53 | 54 | t = int(input()) 55 | 56 | for i in range(0,t): 57 | n = int(input()) 58 | arr = [int(x) for x in input().strip().split(" ")] 59 | print(maximum_sum_subsequence(arr,n)) -------------------------------------------------------------------------------- /Arrays/merge_k_sorted_array_X.py: -------------------------------------------------------------------------------- 1 | def parent(i): 2 | return int((i-1)/2) 3 | def left(i): 4 | return 2*i + 1 5 | def right(i): 6 | return 2*i + 2 7 | 8 | 9 | def heapify(arr,n,i): 10 | small = i 11 | 12 | if left(i) < n and arr[left(i)] < arr[i]: 13 | small = left(i) 14 | 15 | if right(i) < n and arr[right(i)] < arr[small]: 16 | small = right(i) 17 | 18 | # swap two elements 19 | if small != i: 20 | arr[small],arr[i] = arr[i],arr[small] 21 | heapify(arr,n,small) 22 | 23 | 24 | def extract_min(arr): 25 | print(arr) 26 | n = len(arr)s 27 | item = arr[0] 28 | arr[0],arr[n-1] = arr[n-1],arr[0] 29 | arr.pop() 30 | heapify(arr,n-1,0) 31 | return item -------------------------------------------------------------------------------- /Arrays/merge_overlapping_intervals.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def sort_key(interval): 5 | return interval[0] 6 | 7 | 8 | def merge(arr): 9 | arr = sorted(arr, key=sort_key) 10 | 11 | result = [] 12 | 13 | last_start = None 14 | last_finish = None 15 | for start, finish in arr: 16 | if not last_start: 17 | last_start, last_finish = start, finish 18 | continue 19 | 20 | if start <= last_finish: 21 | last_finish = max(finish, last_finish) 22 | else: 23 | result.append((last_start, last_finish)) 24 | last_start, last_finish = start, finish 25 | 26 | result.append((last_start, last_finish)) 27 | 28 | return result 29 | 30 | 31 | class TestCase(unittest.TestCase): 32 | def test_merge(self): 33 | dataT = [[(6, 8), (1, 9), (2, 4), (4, 7)], [(1, 3), (2, 4), (5, 7), (6, 8)]] 34 | 35 | for test in dataT: 36 | result = merge(test) 37 | print(result) 38 | 39 | 40 | if __name__ == "__main__": 41 | unittest.main() 42 | -------------------------------------------------------------------------------- /Arrays/missing_number_in_array.py: -------------------------------------------------------------------------------- 1 | # Given an array of size n-1 and given that there are numbers from 1 to n with one missing, the missing number is to be found. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. 6 | # The first line of each test case is N. 7 | # The second line of each test case contains N-1 input C[i],numbers in array. 8 | 9 | # Output: 10 | 11 | # Print the missing number in array. 12 | 13 | # Constraints: 14 | 15 | # 1 ≤ T ≤ 200 16 | # 1 ≤ N ≤ 1000 17 | # 1 ≤ C[i] ≤ 1000 18 | 19 | # Example: 20 | 21 | # Input 22 | # 2 23 | # 5 24 | # 1 2 3 5 25 | # 10 26 | # 1 2 3 4 5 6 7 8 10 27 | 28 | # Output 29 | # 4 30 | # 9 31 | 32 | def missing_number_in_array(arr,n): 33 | n_xor = 0 34 | 35 | for i in range(1,n+1): 36 | n_xor = n_xor^i 37 | 38 | for item in arr: 39 | n_xor = n_xor^item 40 | return n_xor 41 | 42 | t = int(input()) 43 | 44 | for i in range(0,t): 45 | n = int(input()) 46 | 47 | arr = [int(x) for x in input().strip().split(" ")] 48 | print(missing_number_in_array(arr,n)) 49 | -------------------------------------------------------------------------------- /Arrays/overlapping_intervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a collection of Intervals,merge all the overlapping Intervals. 3 | For example: 4 | 5 | Given [1,3], [2,6], [8,10], [15,18], 6 | 7 | return [1,6], [8,10], [15,18]. 8 | 9 | Make sure the returned intervals are sorted. 10 | 11 | 12 | 13 | Input: 14 | 15 | The first line contains an integer T, depicting total number of test cases. 16 | Then following T lines contains an integer N depicting the number of Intervals and next line followed by the intervals starting and ending positions 'x' and 'y' respectively. 17 | 18 | 19 | Output: 20 | 21 | Print the intervals after overlapping in sorted manner. There should be a newline at the end of output of every test case. 22 | 23 | Constraints: 24 | 25 | 1 ≤ T ≤ 50 26 | 1 ≤ N ≤ 100 27 | 0 ≤ x ≤ y ≤ 100 28 | 29 | 30 | Example: 31 | 32 | Input 33 | 2 34 | 4 35 | 1 3 2 4 6 8 9 10 36 | 4 37 | 6 8 1 9 2 4 4 7 38 | 39 | Output 40 | 1 4 6 8 9 10 41 | 1 9 42 | 43 | """ 44 | 45 | def merge_overlapping_interval(arr,n): 46 | arr = sorted(arr) 47 | 48 | prev = None 49 | result = [] 50 | for item in arr: 51 | if prev == None: 52 | prev = item 53 | continue 54 | 55 | if item[0] <= prev[1]: 56 | prev = (prev[0],max(prev[1],item[1])) 57 | else: 58 | result.append(prev) 59 | prev = item 60 | result.append(prev) 61 | return result 62 | 63 | def test(): 64 | n = 4 65 | arr = [(1,1),(2,2),(6,8),(9,10)] 66 | print(merge_overlapping_interval(arr,n)) 67 | arr = [(6,8),(1,9),(2,4),(4,7)] 68 | print(merge_overlapping_interval(arr,n)) 69 | 70 | def print_interval(arr): 71 | for item in arr: 72 | print(item[0],item[1],end=" ") 73 | print() 74 | 75 | def main(): 76 | t = int(input()) 77 | for i in range(t): 78 | n = int(input()) 79 | a = list(map(int,input().split())) 80 | arr = [] 81 | for j in range(n): 82 | arr.append((a[2*j],a[2*j+1])) 83 | print_interval(merge_overlapping_interval(arr,n)) 84 | 85 | if __name__ == '__main__': 86 | main() 87 | -------------------------------------------------------------------------------- /Arrays/print_all_subsets.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from copy import copy 3 | 4 | 5 | def subsets(arr): 6 | if len(arr) == 0: 7 | return [[]] 8 | 9 | item = arr[0] 10 | sets = subsets(arr[1:]) 11 | item_sets = [] 12 | 13 | for s in sets: 14 | new_set = s[:] 15 | new_set.append(item) 16 | item_sets.append(new_set) 17 | return sets + item_sets 18 | 19 | 20 | class TestCase(unittest.TestCase): 21 | def test_subsets(self): 22 | dataT = [[1, 2, 3]] 23 | 24 | for data in dataT: 25 | result = subsets(data) 26 | print(result) 27 | 28 | 29 | if __name__ == "__main__": 30 | unittest.main() 31 | -------------------------------------------------------------------------------- /Arrays/pythagorian_triplet.py: -------------------------------------------------------------------------------- 1 | # Pythagorean Triplet 2 | # Submissions: 13057   Accuracy: 33.36%   Difficulty: Easy 3 | 4 | # Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. 5 | 6 | # Input: 7 | # The first line contains 'T' denoting the number of testcases. Then follows description of testcases. 8 | # Each case begins with a single positive integer N denoting the size of array. 9 | # The second line contains the N space separated positive integers denoting the elements of array A. 10 | 11 | # Output: 12 | # For each testcase, print "Yes" or "No" whtether it is Pythagorean Triplet or not. 13 | 14 | # Constraints: 15 | # 1<=T<=50 16 | # 1<=N<=100 17 | # 1<=A[i]<=100 18 | 19 | # Example: 20 | # Input: 21 | # 1 22 | # 5 23 | # 3 2 4 6 5 24 | # Output: 25 | # Yes 26 | 27 | 28 | def trapping_rain_water(arr,n): 29 | 30 | for i in range(0,n): 31 | arr[i] = arr[i]*arr[i] 32 | 33 | arr = sorted(arr) 34 | 35 | for i in range(0,n): 36 | for j in range(i+1,n): 37 | if arr[i]+arr[j] in arr: 38 | print("Yes") 39 | return 40 | print("No") 41 | 42 | t = int(input()) 43 | 44 | for i in range(0,t): 45 | n = int(input()) 46 | arr = [int(x) for x in input().strip().split(" ")] 47 | trapping_rain_water(arr,n) -------------------------------------------------------------------------------- /Arrays/reverse_array_in_groups.py: -------------------------------------------------------------------------------- 1 | # Given an array, reverse every sub-array formed by consecutive k elements. 2 | 3 | # Input: 4 | 5 | # The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two lines. The first line of each test case consists of an integer N, where N is the size of array.The second line of each test case contains N space separated integers denoting array elements.The third line of each test case consists of an integer K. 6 | 7 | # Output: 8 | # Corresponding to each test case, in a new line, print the modified array. 9 | 10 | # Constraints: 11 | 12 | # 1 ≤ T ≤ 100 13 | # 1 ≤ N ≤ 500 14 | # 1 ≤ A[i] ≤ 500 15 | 16 | # Example: 17 | 18 | # Input 19 | # 1 20 | # 5 21 | # 1 2 3 4 5 22 | # 3 23 | 24 | # Output 25 | # 3 2 1 5 4 26 | 27 | def max_index_arr(arr,s,e): 28 | max_i = s 29 | for i in range(s,e+1): 30 | if arr[i]>arr[max_i]: 31 | max_i = i 32 | return max_i 33 | 34 | 35 | def reverse_in_group(arr,n,k): 36 | start = 0 37 | while(start0): 71 | item = extract_min(arr) 72 | if item < 0: 73 | continue 74 | if item != 1: 75 | return 1 76 | if prev == None or prev+1 == item: 77 | prev = item 78 | continue 79 | else: 80 | return prev+1 81 | return prev + 1 82 | 83 | def main(): 84 | t = int(input()) 85 | for i in range(t): 86 | n = int(input()) 87 | arr = list(map(int,input().split())) 88 | print(smallest_positive(arr,n)) 89 | 90 | 91 | if __name__ == '__main__': 92 | main() 93 | -------------------------------------------------------------------------------- /Arrays/smallest_positive_number_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/smallest-positive-missing-number/0 3 | 4 | You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. 5 | 6 | Input: 7 | First line consists of T test cases. First line of every test case consists of N, denoting the number of elements in array. Second line of every test case consists of elements in array. 8 | 9 | Output: 10 | Single line output, print the smallest positive number missing. 11 | 12 | Constraints: 13 | 1<=T<=100 14 | 1<=N<=100 15 | 16 | Example: 17 | Input: 18 | 2 19 | 5 20 | 1 2 3 4 5 21 | 5 22 | 0 -10 1 -20 23 | Output: 24 | 6 25 | 2 26 | 27 | """ 28 | 29 | def parent(i): 30 | return int((i-1)/2) 31 | def left(i): 32 | return 2*i + 1 33 | def right(i): 34 | return 2*i + 2 35 | 36 | 37 | def heapify(arr,n,i): 38 | small = i 39 | 40 | if left(i) < n and arr[left(i)] < arr[i]: 41 | small = left(i) 42 | 43 | if right(i) < n and arr[right(i)] < arr[small]: 44 | small = right(i) 45 | 46 | # swap two elements 47 | if small != i: 48 | arr[small],arr[i] = arr[i],arr[small] 49 | heapify(arr,n,small) 50 | 51 | 52 | def extract_min(arr): 53 | print(arr) 54 | n = len(arr)s 55 | item = arr[0] 56 | arr[0],arr[n-1] = arr[n-1],arr[0] 57 | arr.pop() 58 | heapify(arr,n-1,0) 59 | return item 60 | 61 | def smallest_positive(arr,n): 62 | 63 | # for i in range(n): 64 | # if arr[i] < 0: 65 | # arr[i] = 100000000 66 | 67 | for i in range(int(n/2),-1,-1): 68 | heapify(arr,n,i) 69 | prev = None 70 | while(len(arr)>0): 71 | item = extract_min(arr) 72 | if item < 0: 73 | continue 74 | if item != 1: 75 | return 1 76 | if prev == None or prev+1 == item: 77 | prev = item 78 | continue 79 | else: 80 | return prev+1 81 | return prev + 1 82 | 83 | def main(): 84 | t = int(input()) 85 | for i in range(t): 86 | n = int(input()) 87 | arr = list(map(int,input().split())) 88 | print(smallest_positive(arr,n)) 89 | 90 | 91 | if __name__ == '__main__': 92 | main() 93 | -------------------------------------------------------------------------------- /Arrays/sort_an_array_of_0s_1s_and_2s.py: -------------------------------------------------------------------------------- 1 | # Write a program to sort an array of 0's,1's and 2's in ascending order. 2 | 3 | # Input: 4 | # The first line contains an integer 'T' denoting the total number of test cases. In each test cases, First line is number of elements in array 'N' and second its values. 5 | 6 | # Output: 7 | # Print the sorted array of 0's, 1's and 2's. 8 | 9 | # Constraints: 10 | 11 | # 1 <= T <= 100 12 | # 1 <= N <= 100 13 | # 0 <= arr[i] <= 2 14 | 15 | # Example: 16 | 17 | # Input : 18 | 19 | # 2 20 | # 5 21 | # 0 2 1 2 0 22 | # 3 23 | # 0 1 0 24 | 25 | 26 | # Output: 27 | 28 | # 0 0 1 2 2 29 | # 0 0 1 30 | 31 | 32 | def sort_array(arr,n): 33 | count_arr = [0,0,0] 34 | for item in arr: 35 | count_arr[item] = count_arr[item] + 1 36 | return [0]*count_arr[0]+[1]*count_arr[1]+[2]*count_arr[2] 37 | 38 | t = int(input()) 39 | 40 | for i in range(0,t): 41 | numbers = input().strip().split() 42 | n = int(numbers[0]) 43 | 44 | arr = [int(x) for x in input().strip().split(" ")] 45 | result = sort_array(arr,n) 46 | for r in result: 47 | print(r," ",end="") 48 | print("\n") 49 | -------------------------------------------------------------------------------- /Arrays/subarray_with_given_sum.py: -------------------------------------------------------------------------------- 1 | # Given an unsorted array of non-negative integers, find a continuous sub-array which adds to a given number. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements. 6 | 7 | # Output: 8 | 9 | # Corresponding to each test case, in a new line, print the starting and ending positions of first such occuring subarray if sum equals to subarray, else print -1. 10 | 11 | # Note: Position of 1st element of the array should be considered as 1. 12 | 13 | # Expected Time Complexity: O(n) 14 | 15 | # Constraints: 16 | # 1 ≤ T ≤ 100 17 | # 1 ≤ N ≤ 100 18 | # 1 ≤ an array element ≤ 200 19 | 20 | # Example: 21 | 22 | # Input: 23 | # 2 24 | # 5 12 25 | # 1 2 3 7 5 26 | # 10 15 27 | # 1 2 3 4 5 6 7 8 9 10 28 | 29 | # Output: 30 | # 2 4 31 | # 1 5 32 | 33 | # Explanation : 34 | # In first test case, sum of elements from 2nd position to 4th position is 12 35 | # In second test case, sum of elements from 1st position to 5th position is 15 36 | 37 | def subarray_with_given_sum(arr,n,s): 38 | start = 0 39 | current_sum = 0 40 | for i in range(0,n): 41 | current_sum = current_sum + arr[i] 42 | while(current_sum > s): 43 | current_sum = current_sum -arr[start] 44 | start = start + 1 45 | if current_sum == s: 46 | print(start+1,i+1) 47 | return 48 | print(-1) 49 | return 50 | 51 | t = int(input()) 52 | 53 | for i in range(0,t): 54 | numbers = input().strip().split() 55 | n = int(numbers[0]) 56 | s = int(numbers[1]) 57 | 58 | arr = [int(x) for x in input().strip().split(" ")] 59 | subarray_with_given_sum(arr,n,s) 60 | 61 | -------------------------------------------------------------------------------- /BitMagic/all_binary_strings_without_consecutive_1.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def next_string(string, i, n): 5 | if i == n: 6 | return [string] 7 | 8 | if len(string) == 0 or string[-1] == "" or string[-1] == "0": 9 | return next_string(string + "0", i + 1, n) + next_string( 10 | string + "1", i + 1, n) 11 | else: 12 | return next_string(string + "0", i + 1, n) 13 | 14 | 15 | class TestCase(unittest.TestCase): 16 | def test_print_strings(self): 17 | dataT = [3, 4, 5] 18 | 19 | for item in dataT: 20 | results = next_string("", 0, item) 21 | print(results) 22 | 23 | 24 | if __name__ == "__main__": 25 | unittest.main() -------------------------------------------------------------------------------- /BitMagic/alone_in_couple.py: -------------------------------------------------------------------------------- 1 | def alone_in_couple(arr,n): 2 | xor = 0 3 | for item in arr: 4 | xor = xor^item 5 | return xor 6 | t = int(input()) 7 | for i in range(0,t): 8 | n = int(input()) 9 | arr = [int(i) for i in input().strip().split(" ")]; 10 | alone_in_couple(arr,n) -------------------------------------------------------------------------------- /BitMagic/bit_difference.py: -------------------------------------------------------------------------------- 1 | # You are given two numbers A and B. Write a program to count number of bits needed to be flipped to convert A to B. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. 6 | # The first line of each test case is a and b. 7 | 8 | # Output: 9 | 10 | # Print the number of bits needed to be flipped. 11 | 12 | # Constraints: 13 | 14 | # 1 ≤ T ≤ 100 15 | # 1 ≤ a,b ≤ 1000 16 | 17 | # Example: 18 | 19 | # Example: 20 | # Input 21 | # 1 22 | # 10 20 23 | 24 | # Output 25 | # 4 26 | 27 | 28 | # Explanation: 29 | 30 | # A = 1001001 31 | # B = 0010101 32 | # No of bits need to flipped = set bit count i.e. 4You are given two numbers A and B. Write a program to count number of bits needed to be flipped to convert A to B. 33 | 34 | # Input: 35 | 36 | # The first line of input contains an integer T denoting the number of test cases. 37 | # The first line of each test case is a and b. 38 | 39 | # Output: 40 | 41 | # Print the number of bits needed to be flipped. 42 | 43 | # Constraints: 44 | 45 | # 1 ≤ T ≤ 100 46 | # 1 ≤ a,b ≤ 1000 47 | 48 | # Example: 49 | 50 | # Example: 51 | # Input 52 | # 1 53 | # 10 20 54 | 55 | # Output 56 | # 4 57 | 58 | 59 | # Explanation: 60 | 61 | # A = 1001001 62 | # B = 0010101 63 | # No of bits need to flipped = set bit count i.e. 4 64 | 65 | 66 | def bit_difference(a,b): 67 | xor = a^b 68 | # count the set bits 69 | count = 0 70 | while(xor>0): 71 | if xor&1 == 1: 72 | count = count + 1 73 | xor = xor>>1 74 | return count 75 | 76 | #input 77 | 78 | t = int(input()) 79 | for i in range(0,t): 80 | numbers = input() 81 | a = int(numbers.split()[0]) 82 | b = int(numbers.split()[1]) 83 | print(bit_difference(a,b)) -------------------------------------------------------------------------------- /BitMagic/count_set_bits.py: -------------------------------------------------------------------------------- 1 | # Find the sum of all bits from numbers 1 to N. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. 6 | # The first line of each test case is N. 7 | 8 | # Output: 9 | 10 | # Print the sum of all bits. 11 | 12 | # Constraints: 13 | 14 | # 1 ≤ T ≤ 100 15 | # 1 ≤ N ≤ 1000 16 | 17 | # Example: 18 | 19 | # Input: 20 | # 2 21 | # 4 22 | # 17 23 | 24 | # Output: 25 | # 5 26 | # 35 27 | 28 | # Explanation: 29 | # An easy way to look at it is to consider the number, n = 4: 30 | # 0 0 0 = 0 31 | # 0 0 1 = 1 32 | # 0 1 0 = 1 33 | # 0 1 1 = 2 34 | # 1 0 0 = 1 35 | # Therefore , the total number of bits is 5 36 | 37 | def count_bits(n): 38 | s = 0 39 | while(n>0): 40 | s = s + n & 1 41 | n = n>>1 42 | return s 43 | 44 | t = int(input()) 45 | for i in range(0,t): 46 | numbers = input() 47 | n = int(numbers) 48 | print(count_bits(n)) -------------------------------------------------------------------------------- /BitMagic/longest_consecutive_1s.py: -------------------------------------------------------------------------------- 1 | # Given a number N, Your task is to find the length of the longest consecutive 1's in its binary representation. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N. 5 | 6 | # Output: 7 | # For each test case in a new line print the length of the longest consecutive 1's in N's binary representation. 8 | 9 | # Constraints: 10 | # 1<=T<100 11 | # 1<=N<=1000 12 | 13 | # Example: 14 | # Input 15 | # 2 16 | # 14 17 | # 222 18 | # Output 19 | # 3 20 | # 4 21 | 22 | #input 23 | 24 | def longest_consecutive1(n): 25 | current_length = 0 26 | max_length = 0 27 | while(n>0): 28 | if n&1 !=0: 29 | current_length = current_length + 1 30 | else: 31 | current_length = 0 32 | 33 | if current_length > max_length: 34 | max_length = current_length 35 | n = n>>1 36 | print(max_length) 37 | 38 | t = int(input()) 39 | for i in range(0,t): 40 | numbers = input() 41 | n = int(numbers) 42 | longest_consecutive1(n) -------------------------------------------------------------------------------- /BitMagic/power_of_2.py: -------------------------------------------------------------------------------- 1 | # Given a positive integer N, check if N is a power of 2. 2 | 3 | # Input: 4 | # The first line contains 'T' denoting the number of test cases. Then follows description of test cases. 5 | # Each test case contains a single positive integer N. 6 | 7 | 8 | # Output: 9 | # Print "YES" if it is a power of 2 else "NO". (Without the double quotes) 10 | 11 | 12 | # Constraints: 13 | # 1<=T<=100 14 | # 0<=N<=10^18 15 | 16 | # Example: 17 | # Input : 18 | # 2 19 | # 1 20 | # 98 21 | 22 | # Output : 23 | # YES 24 | # ​NO 25 | 26 | def power_of_2(n): 27 | if n & (n-1) == 0: 28 | print("YES") 29 | else: 30 | print("NO") 31 | 32 | 33 | #input 34 | 35 | t = int(input()) 36 | for i in range(0,t): 37 | numbers = input() 38 | n = int(numbers.split()[0]) 39 | power_of_2(n) -------------------------------------------------------------------------------- /BitMagic/rotate_bits.py: -------------------------------------------------------------------------------- 1 | # Given an integer N and an integer D, you are required to write a program to rotate the binary representation of the integer N by D digits to the left as well as right and print the results in decimal values after each of the rotation. 2 | 3 | # Note: Integer N is stored using 16 bits. i.e. 12 will be stored as 0000.....001100. 4 | 5 | # Input: 6 | # First line of input contains a single integer T which denotes the number of test cases. Each test case contains two space separated integers N and D where N denotes the number to be rotated and D denotes the number of digits by which the number is required to be rotated. 7 | 8 | # Output: 9 | # For first line of each test case prints the value of number N after rotating it to left by D digits and second line prints the value of number N after rotating it to the right by D digits. 10 | 11 | # Constraints: 12 | # 1<=T<=100 13 | # 1<=N<=1000 14 | # 1<=D<=100 15 | 16 | # Example: 17 | # Input: 18 | # 2 19 | # 229 3 20 | # 28 2 21 | # Output: 22 | # 47 23 | # 188 24 | # 19 25 | # 7 26 | 27 | def rotate_bits(n,d): 28 | binary_n = bin(n).split('b')[1] 29 | roated_num = binary_n[d:]+binary_n[:d] 30 | print(int(roated_num,2)) 31 | l = len(binary_n) - d 32 | roated_num = binary_n[l:]+binary_n[:l] 33 | print(int(roated_num,2)) 34 | 35 | #input 36 | 37 | t = int(input()) 38 | for i in range(0,t): 39 | numbers = input() 40 | n = int(numbers.split()[0]) 41 | d = int(numbers.split()[1]) 42 | rotate_bits(n,d) 43 | -------------------------------------------------------------------------------- /BitMagic/set_kth_bit.py: -------------------------------------------------------------------------------- 1 | # Given a number N and a value K. From the right, set the Kth bit in the binary representation of N. The position of LSB(or last bit) is 0, second last bit is 1 and so on. Also, 0 <= K < X, where X is the number of bits in the binary representation of N. 2 | 3 | # Input: 4 | # First line of input contains a single integer T which denotes the number of test cases. T test cases follows. First line of each test case contains two space separated integers N and K. 5 | 6 | # Output: 7 | # For each test case, print the new number after setting the Kth bit of N. 8 | 9 | # Constraints: 10 | # 1<=T<=100 11 | # 1<=N<=1000 12 | 13 | 14 | # Example: 15 | # Input: 16 | # 2 17 | # 10 2 18 | # 15 3 19 | # Output: 20 | # 14 21 | # 15 22 | 23 | def setkth_bit(n,k): 24 | mask = 1<>1 == 0: 27 | print(1) 28 | else: 29 | print(0) 30 | 31 | t = int(input()) 32 | for i in range(0,t): 33 | numbers = input() 34 | n = int(numbers) 35 | is_sparse(n) -------------------------------------------------------------------------------- /BitMagic/swap_odd_even_bits.py: -------------------------------------------------------------------------------- 1 | # Given an unsigned integer N, swap all odd bits with even bits. For example, if the given number is 23 ( 0 0 0 1 0 1 1 1 ), it should be converted to 43 ( 0 0 1 0 1 0 1 1 ). Here every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side. 2 | 3 | # Input: 4 | 5 | # The first line of input contains an integer T denoting the number of test cases. 6 | # Then T test cases follow. The first line of each test case contains an integer N. 7 | 8 | # Output: 9 | 10 | # Corresponding to each test case, print in a new line, the converted number . 11 | 12 | # Constraints: 13 | 14 | # 1 ≤ T ≤ 100 15 | # 1 ≤ N ≤ 100 16 | 17 | # Example: 18 | 19 | # Input 20 | # 2 21 | # 23 22 | # 2 23 | 24 | # Output 25 | # 43 26 | # 1 27 | 28 | def swap_bits(n): 29 | mask = 1 30 | 31 | while(mask>1 43 | else: 44 | odd_mask = n & mask>>1 45 | even_mask = n & mask 46 | even_mask = even_mask>>1 47 | odd_mask = odd_mask<<1 48 | print(even_mask|odd_mask) 49 | 50 | 51 | t = int(input()) 52 | for i in range(0,t): 53 | numbers = input() 54 | n = int(numbers) 55 | swap_bits(n) 56 | -------------------------------------------------------------------------------- /BitMagic/toggle_bits_given_range.py: -------------------------------------------------------------------------------- 1 | # Given a non-negative number N and two values L and R. The problem is to toggle the bits in the range L to R in the binary representation of N, i.e, to toggle bits from the rightmost Lth bit to the rightmost Rth bit. A toggle operation flips a bit 0 to 1 and a bit 1 to 0. 2 | 3 | # Input: 4 | # First line of input contains a single integer T which denotes the number of test cases. Then T test cases follows. First line of each test case contains three space separated integers N, L and R. 5 | 6 | # Output: 7 | # For each test case , print the number obtained by toggling bits from the rightmost Lth bit to the rightmost Rth bit in binary representation of N. 8 | 9 | # Constraints: 10 | # 1<=T<=100 11 | # 1<=N<=1000 12 | # 1<=L<=R 13 | # L<=R<= Number of bits(N) 14 | 15 | # Example: 16 | # Input: 17 | # 2 18 | # 17 2 3 19 | # 50 2 5 20 | # Output: 21 | # 23 22 | # 44 23 | 24 | 25 | def toggle_bits(n,l,r): 26 | mask = ((1< r: 51 | arr[k] = temp[p] 52 | p = p + 1 53 | continue 54 | 55 | if p > mid: 56 | arr[k] = temp[q] 57 | q = q + 1 58 | 59 | 60 | 61 | def merge_sort(arr,p,r): 62 | if (p>=r): 63 | return 64 | mid = int((p+r)/2) 65 | merge_sort(arr,p,mid) 66 | merge_sort(arr,mid+1,r) 67 | merge(arr,p,mid,r) 68 | 69 | t = int(input()) 70 | 71 | for i in range(0,t): 72 | n = int(input()) 73 | arr = [int(x) for x in input().strip().split()] 74 | merge_sort(arr,0,n-1) 75 | print(" ".join([str(x) for x in arr])) -------------------------------------------------------------------------------- /DivideAndConquer/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | The task is to complete partition() function which is used to implement Quick Sort. 3 | 4 | Input: 5 | First line of the input denotes number of test cases 'T'. First line of the test case is the size of array and second line consists of array elements. 6 | 7 | 8 | Output: 9 | Sorted array in increasing order is displayed to the user. 10 | 11 | 12 | Constraints: 13 | 1 <=T<= 50 14 | 1 <=N<= 1000 15 | 1 <=arr[i]<= 1000 16 | 17 | 18 | Example: 19 | 20 | Input: 21 | 2 22 | 5 23 | 4 1 3 9 7 24 | 10 25 | 10 9 8 7 6 5 4 3 2 1 26 | 27 | Output: 28 | 1 3 4 7 9 29 | 1 2 3 4 5 6 7 8 9 10 30 | """ 31 | 32 | def partition(arr,p,r): 33 | pivot = arr[r] 34 | 35 | for i in range(p,r): 36 | if arr[i]pivot): 41 | j = j+1 42 | arr[i],arr[j] = arr[j],arr[i] 43 | if j == r: 44 | return i 45 | return r 46 | 47 | 48 | def qsort(arr,p,r): 49 | if p >= r: 50 | return 51 | 52 | q = partition(arr,p,r) 53 | qsort(arr,p,q-1) 54 | qsort(arr,q+1,r) 55 | 56 | t = int(input()) 57 | 58 | for i in range(0,t): 59 | n = int(input()) 60 | arr = [int(x) for x in input().strip().split()] 61 | qsort(arr,0,n-1) 62 | print(" ".join([str(x) for x in arr])) -------------------------------------------------------------------------------- /DynamicProgramming/box_stacking.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/box-stacking/1 3 | You are given a set of N types of rectangular 3-D boxes, where the ith box has height h, width w and length l. You task is to create a stack of boxes 4 | which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly 5 | larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base.It is also allowable to 6 | use multiple instances of the same type of box. You task is to complete the function maxHeight which returns the height of the highest possible stack 7 | so formed. 8 | Input: 9 | The first line of input contains an integer T denoting the no of test cases then T test cases follow . Each test case contains an integer N denoting 10 | the total no of boxes available. In the next line are 3*N space separated values denoting the height width and length of the N boxes. 11 | Output: 12 | For each test case in a new line output will be the highest possible stack height which could be formed. 13 | Constraints: 14 | 1<=T<=100 15 | 1<=N<=100 16 | 1<=l,w,h<=100 17 | Example (To be used for expected output) : 18 | Input: 19 | 2 20 | 4 21 | 4 6 7 1 2 3 4 5 6 10 12 32 22 | 3 23 | 1 2 3 4 5 6 3 4 1 24 | Output 25 | 60 26 | 15 27 | """ 28 | 29 | def max_height_boxes(boxes,x,y,rem): 30 | if rem[x][y] != -1: 31 | return rem[x][y] 32 | 33 | max_height = 0 34 | for i in range(0,len(boxes)): 35 | box = boxes[i] 36 | x_height = 0 37 | y_height = 0 38 | z_height = 0 39 | 40 | if box[0] < x and box[1] < y or box[0] < y and box[1] < x: 41 | x_height = box[2] + max_height_boxes(boxes,box[0],box[1],rem) 42 | 43 | if box[0] < x and box[2] < y or box[0] < y and box[2] < x: 44 | y_height = box[1] + max_height_boxes(boxes,box[0],box[2],rem) 45 | 46 | if box[1] < x and box[2] < y or box[1] < y and box[2] < x: 47 | z_height = box[0] + max_height_boxes(boxes,box[1],box[2],rem) 48 | 49 | max_height = max(max_height,x_height,y_height,z_height) 50 | rem[x][y] = max_height 51 | return max_height 52 | 53 | 54 | def main(): 55 | t = int(input()) 56 | for i in range(0,t): 57 | n = int(input()) 58 | arr = [int(x) for x in input().strip(" ").split(" ")] 59 | boxes = [] 60 | for j in range(0,n): 61 | boxes.append((arr[3*j],arr[3*j+1],arr[3*j+2])) 62 | rem = [] 63 | for j in range(0,101): 64 | rem.append([-1]*(101)) 65 | print(max_height_boxes(boxes,100,100,rem)) 66 | 67 | 68 | if __name__ == '__main__': 69 | main() 70 | 71 | -------------------------------------------------------------------------------- /DynamicProgramming/coin_change.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/coin-change/0 3 | 4 | Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins. The order of coins doesn’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5. 5 | 6 | Input: 7 | 8 | The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'M' denoting the size of array. The second line contains M space-separated integers A1, A2, ..., AN denoting the elements of the array. The third line contains an integer 'N' denoting the cents. 9 | 10 | Output: 11 | 12 | Print number of possible ways to make change for N cents. 13 | 14 | Constraints: 15 | 16 | 1 ≤ T ≤ 50 17 | 1 ≤ N ≤ 300 18 | 1 1 ≤ A[i] ≤ 300 19 | 20 | Example: 21 | 22 | Input: 23 | 24 | 2 25 | 3 26 | 1 2 3 27 | 4 28 | 4 29 | 2 5 3 6 30 | 10 31 | 32 | Output: 33 | 34 | 4 35 | 5 36 | 37 | """ 38 | 39 | 40 | def coin_change(arr, m, r, rem): 41 | if r < 0: 42 | return 0 43 | if m < 0: 44 | return 0 45 | if m == 0: 46 | return 1 47 | if rem[m][r]: 48 | return rem[m][r] 49 | 50 | rem[m][r] = coin_change(arr, m - arr[r], r, rem) + coin_change(arr, m, r - 1, rem) 51 | return rem[m][r] 52 | 53 | 54 | def main(): 55 | t = int(input()) 56 | for i in range(0, t): 57 | n = int(input().strip(" ")) 58 | arr = [int(x) for x in input().strip(" ").split(" ")] 59 | m = int(input()) 60 | rem = [] 61 | for i in range(0, m + 1): 62 | rem.append([None] * n) 63 | result = coin_change(arr, m, n - 1, rem) 64 | print(result) 65 | 66 | 67 | if __name__ == "__main__": 68 | main() 69 | -------------------------------------------------------------------------------- /DynamicProgramming/count_chicks_nth_day.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | https://practice.geeksforgeeks.org/problems/chicks-in-a-zoo/0 5 | 6 | Initially the zoo have a single chick. A chick gives birth to 2 chicks everyday and the life expectancy of a chick is 6 days. Zoo officials want to buy food for chicks so they want to know the number of chicks on a nth day. Help the officials for this task. 7 | 8 | Input: 9 | First line of Input contains the number of test cases. Single line of each test case contains the number of days (n). 10 | 11 | Output: 12 | Print the required output. 13 | 14 | Constraints: 15 | 1<=T<=35 16 | 1<=N<=35 17 | 18 | Example: 19 | Sample Input: 20 | 2 21 | 3 22 | 7 23 | Sample Output: 24 | 25 | 9 26 | 726 27 | """ 28 | 29 | 30 | def count(mem, n): 31 | if n <= 0: 32 | return 0 33 | if n == 1: 34 | return 1 35 | if mem[n]: 36 | return mem[n] 37 | 38 | mem[n] = 3 * (count_chick(mem, n - 1) - int(2 * count_chick(mem, n - 6) / 3)) 39 | return mem[n] 40 | 41 | 42 | def count_chick(n): 43 | mem = [None] * (max(n, 7) + 1) 44 | mem[1] = 1 45 | mem[2] = 3 46 | mem[3] = 9 47 | mem[4] = 27 48 | mem[5] = 81 49 | mem[6] = 243 50 | mem[7] = 726 51 | 52 | return count(mem, n) 53 | 54 | 55 | class Test(unittest.TestCase): 56 | dataT = [(3, 9), (7, 726)] 57 | 58 | def test_count_subsequence(self): 59 | # true check 60 | for test_case in self.dataT: 61 | # print(test_string[0], str(test_string[1])) 62 | # print(test_string) 63 | actual = count_chick(test_case[0]) 64 | self.assertEqual(actual, test_case[1]) 65 | 66 | 67 | def main(): 68 | t = int(input().strip()) 69 | for test in range(t): 70 | n = int(input().strip()) 71 | actual = count_chick(n) 72 | print(actual) 73 | 74 | 75 | if __name__ == "__main__": 76 | unittest.main() 77 | # main() 78 | -------------------------------------------------------------------------------- /DynamicProgramming/count_number_of_hops.py: -------------------------------------------------------------------------------- 1 | """ 2 | url:https://practice.geeksforgeeks.org/problems/count-number-of-hops/0 3 | 4 | Frog steps either 1, 2 or 3 steps to go to top. In how many ways it reaches the top? 5 | 6 | Input: 7 | 8 | The first line of input contains an integer T denoting the number of test cases. 9 | The first line of each test case is N. Where is the number of steps it has to hop. 10 | 11 | Output: 12 | 13 | Print the number of ways. 14 | 15 | Constraints: 16 | 17 | 1 ≤ T ≤ 50 18 | 1 ≤ N ≤ 50 19 | 20 | Example: 21 | 22 | Input: 23 | 2 24 | 1 25 | 5 26 | 27 | Output: 28 | 1 29 | 13 30 | 31 | """ 32 | 33 | def number_of_hops(n,rem): 34 | if n<0: 35 | return 0 36 | if n==0: 37 | return 1 38 | 39 | if rem[n]!= -1: 40 | return rem[n] 41 | 42 | steps = [1,2,3] 43 | hops = 0 44 | for step in steps: 45 | hops = hops + number_of_hops(n-step,rem) 46 | rem[n] = hops 47 | return hops 48 | 49 | def main(): 50 | t = int(input()) 51 | for i in range(0,t): 52 | n = int(input()) 53 | rem = [-1]*(n+1) 54 | print(number_of_hops(n,rem)) 55 | if __name__ == '__main__': 56 | main() 57 | -------------------------------------------------------------------------------- /DynamicProgramming/count_string_with_abc.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | https://practice.geeksforgeeks.org/problems/count-of-strings-that-can-be-formed-using-a-b-and-c-under-given-constraints/0 5 | """ 6 | 7 | 8 | def count_strings(n): 9 | # Can be solved using purely permutation and combination technique 10 | return int( 11 | 1 + 2 * n + n * (n - 1) + (n * (n - 1)) / 2 + (n * (n - 1) * (n - 2)) / 2 12 | ) 13 | 14 | 15 | class Test(unittest.TestCase): 16 | dataT = [(1, 3), (3, 19)] 17 | 18 | def test_count_subsequence(self): 19 | # true check 20 | for test_case in self.dataT: 21 | # print(test_string[0], str(test_string[1])) 22 | # print(test_string) 23 | # mem = [None] * (test_case[1] + 1) 24 | actual = count_strings(test_case[0]) 25 | self.assertEqual(actual, test_case[1]) 26 | 27 | 28 | # def main(): 29 | # t = int(input()) 30 | # for test in range(t): 31 | # m, n = [int(item) for item in input().strip().split(" ")] 32 | # arr = [int(item) for item in input().strip().split(" ")] 33 | # mem = [None] * (n + 1) 34 | # actual = iter_count(arr, n) % (10 ^ 9 + 7) 35 | # print(actual) 36 | 37 | 38 | if __name__ == "__main__": 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /DynamicProgramming/count_subsequence_a^ib^jc^k.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, the task is to count number of subsequences of the form aibjck, where i >= 1, j >=1 and k >= 1. 3 | 4 | Note: Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different. 5 | 6 | 7 | Examples: 8 | 9 | Input : abbc 10 | Output : 3 11 | Subsequences are abc, abc and abbc 12 | 13 | Input : abcabc 14 | Output : 7 15 | Subsequences are abc, abc, abbc, aabc 16 | abcc, abc and abc 17 | 18 | 19 | Input: 20 | The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains a string s. 21 | 22 | Output: 23 | For each test case in a new line print the required output. 24 | 25 | """ 26 | import unittest 27 | 28 | 29 | def count_subsequence(prev, string): 30 | if len(string) == 0: 31 | if prev == "c": 32 | return 1 33 | else: 34 | return 0 35 | if prev == "": 36 | if string[0] == "a": 37 | return count_subsequence("", string[1:]) + count_subsequence( 38 | string[0], string[1:] 39 | ) 40 | else: 41 | return count_subsequence("", string[1:]) 42 | 43 | if prev == "a": 44 | if string[0] == "a": 45 | return 2 * count_subsequence(prev, string[1:]) 46 | elif string[0] == "b": 47 | return count_subsequence(prev, string[1:]) + count_subsequence( 48 | string[0], string[1:] 49 | ) 50 | else: 51 | return count_subsequence(prev, string[1:]) 52 | 53 | if prev == "b": 54 | if string[0] == "b": 55 | return 2 * count_subsequence(prev, string[1:]) 56 | elif string[0] == "c": 57 | return count_subsequence(prev, string[1:]) + count_subsequence( 58 | string[0], string[1:] 59 | ) 60 | else: 61 | return count_subsequence(prev, string[1:]) 62 | 63 | if prev == "c": 64 | if string[0] == "c": 65 | return 2 * count_subsequence(prev, string[1:]) 66 | else: 67 | return count_subsequence(prev, string[1:]) 68 | 69 | 70 | def count(string): 71 | return count_subsequence("", string) 72 | 73 | 74 | def main(): 75 | t = int(input()) 76 | for _ in range(t): 77 | string = input() 78 | print(count(string)) 79 | 80 | 81 | class Test(unittest.TestCase): 82 | dataT = [("abc", 1), ("abbc", 3), ("abcabc", 7)] 83 | 84 | def test_count_subsequence(self): 85 | # true check 86 | for test_string in self.dataT: 87 | # print(test_string[0], str(test_string[1])) 88 | # print(test_string) 89 | actual = count(test_string[0]) 90 | self.assertEqual(actual, test_string[1]) 91 | 92 | 93 | if __name__ == "__main__": 94 | unittest.main() 95 | # main() 96 | -------------------------------------------------------------------------------- /DynamicProgramming/edit_distance.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/edit-distance/0 3 | 4 | Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1′ into ‘str2′. 5 | 6 | Insert 7 | Remove 8 | Replace 9 | All of the above operations are of cost=1. 10 | Both the strings are of lowercase. 11 | 12 | Input: 13 | The First line of the input contains an integer T denoting the number of test cases. Then T test cases follow. Each tese case consists of two lines. The first line of each test case consists of two space separated integers P and Q denoting the length of the strings str1 and str2 respectively. The second line of each test case coantains two space separated strings str1 and str2 in order. 14 | 15 | 16 | Output: 17 | Corresponding to each test case, pirnt in a new line, the minimum number of operations required. 18 | 19 | Constraints: 20 | 1<=T<=50 21 | 1<= Length(str1) <= 100 22 | 1<= Length(str2) <= 100 23 | 24 | 25 | Example: 26 | Input: 27 | 1 28 | 4 5 29 | geek gesek 30 | 31 | Output: 32 | 1 33 | 34 | """ 35 | 36 | def lcs(str1,str2,i,j,matrix): 37 | if i < 0: 38 | return j+1 39 | if j < 0: 40 | return i+1 41 | if matrix[i][j] != -1: 42 | return matrix[i][j] 43 | 44 | if str1[i] == str2[j]: 45 | matrix[i][j] = lcs(str1,str2,i-1,j-1,matrix) 46 | return matrix[i][j] 47 | matrix[i][j] = 1 + min(lcs(str1,str2,i-1,j,matrix),lcs(str1,str2,i,j-1,matrix),lcs(str1,str2,i-1,j-1,matrix)) 48 | return matrix[i][j] 49 | 50 | def main(): 51 | t = int(input()) 52 | 53 | for i in range(0,t): 54 | numbers = input().replace(" "," ").strip(" ").split(" ") 55 | n1 = int(numbers[0]) 56 | n2 = int(numbers[1]) 57 | strings = input().strip(" ").split(" ") 58 | str1 = strings[0] 59 | str2 = strings[1] 60 | matrix = [] 61 | for i in range(0,n1): 62 | row = [-1]*n2 63 | matrix.append(row) 64 | print(lcs(str1,str2,n1-1,n2-1,matrix)) 65 | 66 | if __name__ == '__main__': 67 | main() -------------------------------------------------------------------------------- /DynamicProgramming/egg_dropping_puzzle.py: -------------------------------------------------------------------------------- 1 | """ 2 | url:https://practice.geeksforgeeks.org/problems/egg-dropping-puzzle/0 3 | 4 | Suppose you have N eggs and you want to determine from which floor in a K-floor building you can drop an egg such that it doesn't break. You have to 5 | determine the minimum number of attempts you need in order find the critical floor in the worst case while using the best strategy.There are few 6 | rules given below. 7 | * An egg that survives a fall can be used again. 8 | * A broken egg must be discarded. 9 | * The effect of a fall is the same for all eggs. 10 | * If the egg doesn't break at a certain floor, it will not break at any floor below. 11 | * If the eggs breaks at a certain floor, it will break at any floor above. 12 | 13 | For more description on this problem see wiki page 14 | 15 | Input: 16 | The first line of input is T denoting the number of testcases.Then each of the T lines contains two positive integer N and K where 'N' is the number 17 | of eggs and 'K' is number of floor in building. 18 | 19 | Output: 20 | For each test case, print a single line containing one integer the minimum number of attempt you need in order find the critical floor. 21 | 22 | Constraints: 23 | 1<=T<=30 24 | 1<=N<=10 25 | 1<=K<=50 26 | 27 | Example: 28 | Input: 29 | 1 30 | 2 10 31 | 32 | Output: 33 | 4 34 | """ 35 | 36 | def egg_puzzle(n,k,rem): 37 | if k < 1: 38 | return 0 39 | if n < 1: 40 | return 1000 41 | if n == 1: 42 | rem[n][k] = k 43 | return rem[n][k] 44 | 45 | min_attempts = 100 46 | for i in range(1,k+1): 47 | min_attempts = min(min_attempts, max(egg_puzzle(n-1,i-1,rem), egg_puzzle(n,k-i,rem))) 48 | 49 | rem[n][k] = 1 + min_attempts 50 | return rem[n][k] 51 | 52 | def main(): 53 | t = int(input()) 54 | for i in range(0,t): 55 | n_k = input().strip(" ").split(" ") 56 | n = int(n_k[0]) 57 | k = int(n_k[1]) 58 | rem = [] 59 | for j in range(0,n+1): 60 | rem.append([-1]*(k+1)) 61 | print(egg_puzzle(n,k,rem)) 62 | print(rem) 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /DynamicProgramming/get_minimum_squares.py: -------------------------------------------------------------------------------- 1 | import math 2 | import unittest 3 | 4 | """ 5 | https://practice.geeksforgeeks.org/problems/get-minimum-squares/0 6 | """ 7 | 8 | 9 | def get_minimum_squares(rem, n): 10 | if n < 0: 11 | return 100000 12 | 13 | if n == 0 or n == 1: 14 | return n 15 | 16 | if rem[n]: 17 | return rem[n] 18 | 19 | result = 100000 20 | for i in range(math.floor(math.sqrt(n)), 0, -1): 21 | result = min(result, get_minimum_squares(rem, n - i * i)) 22 | 23 | rem[n] = result 24 | 25 | return result 26 | 27 | 28 | def min_squares(n): 29 | rem = [None] * (n + 1) 30 | return get_minimum_squares(rem, n) 31 | 32 | 33 | class TestCase(unittest.TestCase): 34 | def test_get_minimum_squares(self): 35 | dataT = [(100, 1), (6, 3), (25, 1)] 36 | for test_case in dataT: 37 | actual = min_squares(test_case[0]) 38 | self.assertEqual(actual, test_case[1]) 39 | 40 | 41 | def main(): 42 | t = int(input()) 43 | for _ in range(t): 44 | n = int(input()) 45 | print(min_squares(n)) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | 51 | -------------------------------------------------------------------------------- /DynamicProgramming/longest_common_subsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/longest-common-subsequence/0 3 | 4 | Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase. 5 | 6 | Input: 7 | First line of the input contains no of test cases T,the T test cases follow. 8 | Each test case consist of 2 space separated integers A and B denoting the size of string str1 and str2 respectively 9 | The next two lines contains the 2 string str1 and str2 . 10 | 11 | 12 | Output: 13 | For each test case print the length of longest common subsequence of the two strings . 14 | 15 | 16 | Constraints: 17 | 1<=T<=200 18 | 1<=size(str1),size(str2)<=100 19 | 20 | 21 | Example: 22 | Input: 23 | 2 24 | 6 6 25 | ABCDGH 26 | AEDFHR 27 | 3 2 28 | ABC 29 | AC 30 | 31 | Output: 32 | 3 33 | 2 34 | 35 | 36 | """ 37 | 38 | def lcs(str1,str2,i,j,matrix): 39 | if i<0 or j < 0: 40 | return 0 41 | if matrix[i][j] != -1: 42 | return matrix[i][j] 43 | 44 | if str1[i] == str2[j]: 45 | matrix[i][j] = 1 + lcs(str1,str2,i-1,j-1,matrix) 46 | return matrix[i][j] 47 | matrix[i][j] = max(lcs(str1,str2,i-1,j,matrix),lcs(str1,str2,i,j-1,matrix)) 48 | return matrix[i][j] 49 | 50 | def main(): 51 | t = int(input()) 52 | 53 | for i in range(0,t): 54 | numbers = input().replace(" "," ").strip(" ").split(" ") 55 | n1 = int(numbers[0]) 56 | n2 = int(numbers[1]) 57 | str1 = input() 58 | str2 = input() 59 | matrix = [] 60 | for i in range(0,n1): 61 | row = [-1]*n2 62 | matrix.append(row) 63 | print(lcs(str1,str2,n1-1,n2-1,matrix)) 64 | 65 | if __name__ == '__main__': 66 | main() 67 | -------------------------------------------------------------------------------- /DynamicProgramming/longest_increasing_subsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence/0 3 | Given a sequence, find the length of the longest increasing subsequence from a given sequence . 4 | The longest increasing subsequence means to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest 5 | to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique. 6 | 7 | Note: Duplicate numbers are not counted as increasing subsequence. 8 | 9 | For example: 10 | length of LIS for 11 | { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS is {10, 22, 33, 50, 60, 80}. 12 | 13 | 14 | 15 | Input: 16 | 17 | The first line contains an integer T, depicting total number of test cases. 18 | Then following T lines contains an integer N depicting the size of array and next line followed by the value of array. 19 | 20 | 21 | Output: 22 | 23 | Print the Max length of the subsequence in a separate line. 24 | 25 | 26 | Constraints: 27 | 28 | 1 ≤ T ≤ 100 29 | 1 ≤ N ≤ 1000 30 | 0 ≤ A[i] ≤ 300 31 | 32 | Example: 33 | 34 | Input 35 | 1 36 | 16 37 | 0 8 4 12 2 10 6 14 1 9 5 13 3 11 t 7 15 38 | Output 39 | 6 40 | 41 | """ 42 | import re 43 | def longest_increasing_subsequence(arr,n): 44 | subsequence_length = [1]*len(arr) 45 | for i in range(0,n): 46 | j = i-1 47 | while(j>-1): 48 | if arr[j]subsequence_length[i]: 49 | subsequence_length[i] = subsequence_length[j]+1 50 | j = j-1 51 | return max(subsequence_length) 52 | 53 | def main(): 54 | t = int(input()) 55 | for i in range(0,t): 56 | n = int(input().strip(" ")) 57 | arr_str = re.sub(r' +',' ',input()).split(" ") 58 | arr = [] 59 | for item in arr_str: 60 | try: 61 | arr.append(int(item)) 62 | except: 63 | pass 64 | print(longest_increasing_subsequence(arr,n)) 65 | if __name__ == '__main__': 66 | main() 67 | -------------------------------------------------------------------------------- /DynamicProgramming/max_sum_coin_game.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def max_sum(arr, i, j): 5 | if i == j: 6 | return arr[i] 7 | 8 | if i + 1 == j: 9 | return max(arr[i], arr[j]) 10 | 11 | return max( 12 | arr[i] + min(max_sum(arr, i + 2, j), max_sum(arr, i + 1, j - 1)), 13 | arr[j] + min(max_sum(arr, i, j - 2), max_sum(arr, i + 1, j - 1)), 14 | ) 15 | 16 | 17 | class TestCase(unittest.TestCase): 18 | def test_game(self): 19 | dataT = [([8, 15, 3, 7], 22), ([2, 2, 2, 2], 4), ([20, 30, 2, 2, 2, 10], 42)] 20 | 21 | for item in dataT: 22 | result = max_sum(item[0], 0, len(item[0]) - 1) 23 | self.assertEqual(result, item[1]) 24 | 25 | 26 | if __name__ == "__main__": 27 | unittest.main() 28 | -------------------------------------------------------------------------------- /DynamicProgramming/minimum_number_of_jumps.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : 3 | 4 | Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element. 5 | 6 | Input: 7 | The first line contains an integer T, depicting total number of test cases. 8 | Then following T lines contains a number n denoting the size of the array. 9 | Next line contains the sequence of integers a1, a2, ..., an. 10 | 11 | Output: 12 | Each seperate line showing the minimum number of jumps. If answer is not possible print -1. 13 | 14 | Constraints: 15 | 1 ≤ T ≤ 40 16 | 1 ≤ N ≤ 100 17 | 0<=a[N]<=100 18 | 19 | Example: 20 | 21 | Input: 22 | 23 | 1 24 | 11 25 | 1 3 5 8 9 2 6 7 6 8 9 26 | 27 | """ 28 | 29 | def minimum_jumps(arr,i,rem): 30 | if i < 0: 31 | return 1000 32 | if i == 0: 33 | return 0 34 | if rem[i] != -1: 35 | return rem[i] 36 | 37 | min_jumps = 1000 38 | j = i-1 39 | while(j>=0): 40 | if arr[j] >= i-j: 41 | min_jumps = min(min_jumps, 1 + minimum_jumps(arr,j,rem)) 42 | j = j - 1 43 | rem[i] = min_jumps 44 | return rem[i] 45 | 46 | def main(): 47 | t = int(input()) 48 | for i in range(0,t): 49 | n = int(input().strip(" ")) 50 | arr = [int(x) for x in input().strip(" ").split(" ")] 51 | rem = [-1] * n 52 | result = minimum_jumps(arr,n-1,rem) 53 | if result == 1000: 54 | print(-1) 55 | else: 56 | print(result) 57 | 58 | if __name__ == '__main__': 59 | main() -------------------------------------------------------------------------------- /DynamicProgramming/minimum_sum_partition.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0 3 | Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. 4 | 5 | Input: 6 | The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'N' denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. 7 | 8 | 9 | Output: 10 | In each seperate line print minimum absolute difference. 11 | 12 | 13 | Constraints: 14 | 1<=T<=30 15 | 1<=N<=50 16 | 1<=A[I]<=50 17 | 18 | 19 | Example: 20 | Input: 21 | 2 22 | 4 23 | 1 6 5 11 24 | 4 25 | 36 7 46 40 26 | 27 | Output : 28 | 1 29 | 23 30 | 31 | Explaination : 32 | Subset1 = {1, 5, 6}, sum of Subset1 = 12 33 | Subset2 = {11}, sum of Subset2 = 11 34 | """ 35 | 36 | def subset(arr,r,s_sum,rem): 37 | if s_sum == 0: 38 | return True 39 | if r<0 or s_sum <0 : 40 | return False 41 | 42 | if rem[s_sum][r]!=-1: 43 | return rem[s_sum][r] 44 | 45 | rem[s_sum][r] = subset(arr,r-1,s_sum-arr[r],rem) or subset(arr,r-1,s_sum,rem) 46 | return rem[s_sum][r] 47 | 48 | 49 | def subset_sum(arr,n): 50 | arr_sum = sum(arr) 51 | a_sum = int(arr_sum/2) 52 | b_sum = arr_sum - a_sum 53 | 54 | rem = [] 55 | for i in range(0,arr_sum): 56 | rem.append([-1]*(n)) 57 | 58 | while(a_sum>0 and b_sum < arr_sum): 59 | if subset(arr,n-1,a_sum,rem) and subset(arr,n-1,b_sum,rem): 60 | return b_sum - a_sum 61 | else: 62 | a_sum = a_sum - 1 63 | b_sum = b_sum + 1 64 | return b_sum - a_sum 65 | 66 | def main(): 67 | t = int(input()) 68 | for i in range(0,t): 69 | n = int(input()) 70 | arr = [int(x) for x in input().strip(" ").split(" ")] 71 | print(subset_sum(arr,n)) 72 | 73 | if __name__ == '__main__': 74 | main() -------------------------------------------------------------------------------- /DynamicProgramming/pass_the_semester.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/pass-the-semester/0 3 | """ 4 | 5 | INFINITE = 100000 6 | 7 | 8 | def pass_semester(rem, array, time): 9 | if len(array) == 0: 10 | return INFINITE 11 | 12 | if marks <= 0: 13 | return 0 14 | if rem[marks] != None: 15 | return rem[marks] 16 | 17 | result = 10000 18 | 19 | for item in array: 20 | next_arr = array[:] 21 | next_arr.remove(item) 22 | result = min(result, item[0] + pass_semester(rem, next_arr, marks - item[1])) 23 | 24 | rem[marks] = result 25 | return rem[marks] 26 | 27 | 28 | if __name__ == "__main__": 29 | for _ in range(int(input())): 30 | array_length, time, marks = list(map(int, input().split(" "))) 31 | array = [] 32 | for i in range(array_length): 33 | array.append(tuple(map(int, input().split(" ")))) 34 | rem = [None] * (marks + 1) 35 | result = pass_semester(rem, array, marks) 36 | if result <= time: 37 | print(f"YES {result}") 38 | else: 39 | print("NO") 40 | -------------------------------------------------------------------------------- /DynamicProgramming/path_in_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/path-in-matrix/0 3 | 4 | Given a N X N matrix Matrix[N][N] of positive integers. There are only three possible moves from a cell Matrix[r][c]. 5 | 6 | 1. Matrix[r+1][c] 7 | 8 | 2. Matrix[r+1][c-1] 9 | 10 | 3. Matrix[r+1][c+1] 11 | 12 | Starting from any column in row 0, return the largest sum of any of the paths up to row N-1. 13 | 14 | Input: 15 | The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. 16 | The first line of each test case contains a single integer N denoting the order of matrix. Next line contains N*N integers denoting the elements of the matrix in row-major form. 17 | 18 | Output: 19 | Output the largest sum of any of the paths starting from any cell of row 0 to any cell of row N-1. Print the output of each test case in a new line. 20 | 21 | Constraints: 22 | 1<=T<=20 23 | 2<=N<=20 24 | 1<=Matrix[i][j]<=1000 (for all 1<=i<=N && 1<=j<=N) 25 | 26 | Example: 27 | 28 | Input: 29 | 1 30 | 2 31 | 348 391 618 193 32 | 33 | Output: 34 | 1009 35 | """ 36 | 37 | def path_in_matrix(matrix,n,i,j): 38 | if i>= n or j>= n: 39 | return -1000 40 | if i == n-1: 41 | return matrix[i][j] 42 | 43 | return matrix[i][j] + max(path_in_matrix(matrix,n,i+1,j-1),path_in_matrix(matrix,n,i+1,j),path_in_matrix(matrix,n,i+1,j+1)) 44 | 45 | 46 | def main(): 47 | t = int(input()) 48 | for i in range(0,t): 49 | n = int(input()) 50 | arr = [int(x) for x in input().strip(" ").split(" ")] 51 | matrix = [] 52 | for i in range(0,n): 53 | index = n * i 54 | row = [arr[index + x] for x in range(0,n)] 55 | matrix.append(row) 56 | # print(matrix) 57 | max_path = 0 58 | for k in range(0,len(matrix)): 59 | max_path = max(max_path,path_in_matrix(matrix,n,0,k)) 60 | print(max_path) 61 | 62 | if __name__ == '__main__': 63 | main() 64 | -------------------------------------------------------------------------------- /DynamicProgramming/reach_score.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | https://practice.geeksforgeeks.org/problems/reach-a-given-score/0 5 | """ 6 | 7 | 8 | def reach_score(rem, arr, n): 9 | if n == 0: 10 | return 1 11 | 12 | if n < 0 or len(arr) == 0: 13 | return 0 14 | 15 | if rem[n]: 16 | return rem[n] 17 | 18 | return reach_score(rem, arr[:-1], n) + reach_score(rem, arr, n - arr[-1]) 19 | 20 | 21 | def reach(n): 22 | arr = [3, 5, 10] 23 | rem = [None] * (n + 1) 24 | return reach_score(rem, arr, n) 25 | 26 | 27 | def main(): 28 | t = int(input()) 29 | for _ in range(t): 30 | n = int(input()) 31 | print(reach(n)) 32 | 33 | 34 | class TestCase(unittest.TestCase): 35 | def test_reach_score(self): 36 | dataT = [(8, 1), (20, 4), (13, 2)] 37 | 38 | for test_case in dataT: 39 | actual = reach(test_case[0]) 40 | self.assertEqual(actual, test_case[1]) 41 | 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /DynamicProgramming/shortest_common_supersequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | url:https://practice.geeksforgeeks.org/problems/shortest-common-supersequence/0 3 | Given two strings str1 and str2, find the shortest common shortest common subsequence of the two strings. 4 | 5 | Input: 6 | The first line of input contains an integer T denoting the number of test cases.Each test case contains two space separated strings. 7 | 8 | Output: 9 | Output the length of the shortest common supersequence. 10 | 11 | Constraints: 12 | 1<=T<=100 13 | 14 | Example: 15 | Input: 16 | 2 17 | abcd xycd 18 | efgh jghi 19 | Output: 20 | 6 21 | 6 22 | """ 23 | def lcs(str1,str2,i,j,matrix): 24 | if i<0 or j < 0: 25 | return 0 26 | if matrix[i][j] != -1: 27 | return matrix[i][j] 28 | 29 | if str1[i] == str2[j]: 30 | matrix[i][j] = 1 + lcs(str1,str2,i-1,j-1,matrix) 31 | return matrix[i][j] 32 | matrix[i][j] = max(lcs(str1,str2,i-1,j,matrix),lcs(str1,str2,i,j-1,matrix)) 33 | return matrix[i][j] 34 | 35 | def main(): 36 | t = int(input()) 37 | for i in range(0,t): 38 | strings = input().strip(" ").split(" ") 39 | str1 = strings[0] 40 | str2 = strings[1] 41 | matrix = [] 42 | for i in range(0,len(str1)): 43 | row = [-1]*len(str2) 44 | matrix.append(row) 45 | print(len(str1)+len(str2)-lcs(str1,str2,len(str1)-1,len(str2)-1,matrix)) 46 | 47 | if __name__ == '__main__': 48 | main() 49 | 50 | -------------------------------------------------------------------------------- /DynamicProgramming/subset_sum_problem.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/subset-sum-problem/0 3 | Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not. 4 | 5 | Input:The first line contains an integer 'T' denoting the total number of test cases. Each test case constitutes of two lines. First line contains 'N', representing the number of elements in the set and the second line contains the elements of the set. 6 | Output: Print YES if the given set can be partioned into two subsets such that the sum of elements in both subsets is equal, else print NO. 7 | Constraints: 8 | 9 | 1 <= T<= 100 10 | 1 <= N<= 100 11 | 0 <= arr[i]<= 1000 12 | 13 | 14 | Example: 15 | 16 | Input: 17 | 2 18 | 4 19 | 1 5 11 5 20 | 3 21 | 1 3 5 22 | 23 | Output: 24 | 25 | YES 26 | NO 27 | 28 | """ 29 | def subtract(arr1,arr2): 30 | result = [] 31 | for item in arr1: 32 | if item not in arr2: 33 | result.append(item) 34 | return result 35 | 36 | def subset(arr,r,sub,s_sum,rem): 37 | if s_sum == 0: 38 | return sub 39 | if r<0 or s_sum <0 : 40 | return[] 41 | 42 | if rem[s_sum][r]!=-1: 43 | return rem[s_sum][r] 44 | 45 | result = subset(arr,r-1,sub+[arr[r]],s_sum-arr[r],rem) 46 | if len(result)==0: 47 | rem[s_sum][r] = subset(arr,r-1,sub,s_sum,rem) 48 | return rem[s_sum][r] 49 | else: 50 | rem[s_sum][r] = result 51 | return result 52 | 53 | def subset_sum(arr,n): 54 | if sum(arr)%2 !=0: 55 | return 'NO' 56 | s_sum = int(sum(arr)/2) 57 | sub = [] 58 | rem = [] 59 | for i in range(0,s_sum+1): 60 | rem.append([-1]*(n)) 61 | result1 = subset(arr,n-1,sub,s_sum,rem) 62 | if len(result1) == 0: 63 | return 'NO' 64 | 65 | arr.remove(result1[0]) 66 | sub = [] 67 | rem = [] 68 | for i in range(0,s_sum+1): 69 | rem.append([-1]*(len(arr))) 70 | result2 = subset(arr,len(arr)-1,sub,s_sum,rem) 71 | if len(result2) == 0: 72 | return 'NO' 73 | else: 74 | return 'YES' 75 | 76 | def main(): 77 | t = int(input()) 78 | for i in range(0,t): 79 | n = int(input()) 80 | arr = [int(x) for x in input().strip(" ").split(" ")] 81 | print(subset_sum(arr,n)) 82 | 83 | if __name__ == '__main__': 84 | main() -------------------------------------------------------------------------------- /DynamicProgramming/ways_to_sum_n.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | """ 4 | https://practice.geeksforgeeks.org/problems/ways-to-sum-to-n/0 5 | """ 6 | 7 | 8 | def rec_count(mem, arr, n): 9 | if n < 0: 10 | return 0 11 | if n == 0: 12 | return 1 13 | if mem[n]: 14 | return mem[n] 15 | 16 | result = 0 17 | for item in arr: 18 | if item != 0: 19 | result += rec_count(mem, arr, n - item) 20 | mem[n] = result 21 | 22 | return mem[n] 23 | 24 | 25 | def iter_count(arr, n): 26 | count = [0] * (n + 1) 27 | count[0] = 1 28 | 29 | for j in range(n + 1): 30 | for item in arr: 31 | if j >= item: 32 | count[j] += count[j - item] 33 | 34 | return count[n] 35 | 36 | 37 | class Test(unittest.TestCase): 38 | dataT = [([1, 5, 6], 7, 6)] 39 | 40 | def test_count_subsequence(self): 41 | # true check 42 | for test_case in self.dataT: 43 | # print(test_string[0], str(test_string[1])) 44 | # print(test_string) 45 | mem = [None] * (test_case[1] + 1) 46 | actual = count(mem, test_case[0], test_case[1]) 47 | print(mem) 48 | self.assertEqual(actual, test_case[2]) 49 | 50 | 51 | def main(): 52 | t = int(input()) 53 | for test in range(t): 54 | m, n = [int(item) for item in input().strip().split(" ")] 55 | arr = [int(item) for item in input().strip().split(" ")] 56 | mem = [None] * (n + 1) 57 | actual = iter_count(arr, n) % (10 ^ 9 + 7) 58 | print(actual) 59 | 60 | 61 | if __name__ == "__main__": 62 | main() 63 | -------------------------------------------------------------------------------- /DynamicProgramming/zero_1_knapsack.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem/0 3 | 4 | You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item, In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property). 5 | 6 | 7 | Input: 8 | 9 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of four lines. The first line consists of N the number of items. The second line consists of W, the maximum capacity of the knapsack. In the next line are N space separated positive integers denoting the values of the N items and in the fourth line are N space separated positive integers denoting the weights of the corresponding items. 10 | 11 | 12 | Output: 13 | 14 | Print the maximum possible value you can get with the given conditions that you can obtain for each test case in a new line. 15 | 16 | 17 | Constraints: 18 | 19 | 1≤T≤100 20 | 21 | 1≤N≤100 22 | 23 | 1≤W≤100 24 | 25 | 1≤wt[i]≤100 26 | 27 | 1≤v[i]≤100 28 | 29 | 30 | Example: 31 | 32 | Input: 33 | 1 34 | 3 35 | 4 36 | 1 2 3 37 | 4 5 1 38 | Output: 39 | 3 40 | """ 41 | 42 | def zero_1_knapsack(weight,values,w,r,rem): 43 | if w < 0: 44 | return -10000 45 | if w == 0 or r < 0: 46 | return 0 47 | if rem[w][r] !=-1: 48 | return rem[w][r] 49 | 50 | rem[w][r] = max(values[r]+zero_1_knapsack(weight,values,w-weight[r],r-1,rem),zero_1_knapsack(weight,values,w,r-1,rem)) 51 | return rem[w][r] 52 | 53 | 54 | 55 | def main(): 56 | t = int(input()) 57 | for i in range(0,t): 58 | n = int(input()) 59 | w = int(input()) 60 | values = [int(x) for x in input().strip(" ").split(" ")] 61 | weight = [int(x) for x in input().strip(" ").split(" ")] 62 | rem = [] 63 | for i in range(0,w+1): 64 | rem.append([-1]*len(weight)) 65 | print(zero_1_knapsack(weight,values,w,len(weight)-1,rem)) 66 | 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /Graph/bfs.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/x-total-shapes/0 3 | 4 | Given N * M string array of O's and X's 5 | Return the number of 'X' total shapes. 'X' shape consists of one or more adjacent X's (diagonals not included). 6 | 7 | Example (1): 8 | 9 | OOOXOOO 10 | OXXXXXO 11 | OXOOOXO 12 | 13 | answer is 1 , shapes are : 14 | (i) X 15 | X X X X 16 | X X 17 | 18 | 19 | Example (2): 20 | 21 | XXX 22 | OOO 23 | XXX 24 | 25 | answer is 2, shapes are 26 | (i) XXX 27 | 28 | (ii) XXX 29 | 30 | Input: 31 | The first line of input takes the number of test cases, T. 32 | Then T test cases follow. Each of the T test cases takes 2 input lines. 33 | The first line of each test case have two integers N and M.The second line of N space separated strings follow which indicate the elements in the array. 34 | 35 | Output: 36 | 37 | Print number of shapes. 38 | 39 | Constraints: 40 | 41 | 1<=T<=100 42 | 43 | 1<=N,M<=50 44 | 45 | Example: 46 | 47 | Input: 48 | 2 49 | 4 7 50 | OOOOXXO OXOXOOX XXXXOXO OXXXOOO 51 | 10 3 52 | XXO OOX OXO OOO XOX XOX OXO XXO XXX OOO 53 | 54 | Output: 55 | 4 56 | 6 57 | 58 | """ 59 | 60 | def max(matrix,n,m): 61 | max_item = 0 62 | for i in range(n): 63 | for j in range(m): 64 | if max_item = n or j < 0 or j>=m : 71 | return 72 | if matrix[i][j] == '0': 73 | matrix[i][j] = 0 74 | return 75 | if matrix[i][j] == 'X': 76 | matrix[i][j] = count 77 | bfs(i-1,j,n,m,matrix,count) 78 | bfs(i+1,j,n,m,matrix,count) 79 | bfs(i,j-1,n,m,matrix,count) 80 | bfs(i,j+1,n,m,matrix,count) 81 | 82 | 83 | def x_total_shapes(matrix,n,m): 84 | count = 0 85 | for i in range(n): 86 | for j in range(m): 87 | if matrix[i][j] == 'X': 88 | count = count + 1 89 | bfs(i,j,n,m,matrix,count) 90 | if matrix[i][j] == 'O': 91 | matrix[i][j] = 0 92 | print(max(matrix,n,m)) 93 | 94 | def main(): 95 | t = int(input()) 96 | for i in range(t): 97 | numbers = input().strip(" ").split(" ") 98 | n = int(numbers[0]) 99 | m = int(numbers[1]) 100 | matrix_str = input().strip(" ").split(" ") 101 | matrix = [] 102 | for item in matrix_str: 103 | matrix.append(list(item)) 104 | x_total_shapes(matrix,n,m) 105 | 106 | if __name__ == '__main__': 107 | main() 108 | -------------------------------------------------------------------------------- /Graph/circle_of_strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/circle-of-strings/0 3 | 4 | Given an array of strings A[ ], determine if the strings can be chained together to form a circle. A 5 | string X can be chained together with another string Y if the last character of X is same as first 6 | character of Y. If every string of the array can be chained, it will form a circle. 7 | 8 | For eg for the array arr[] = {"for", "geek", "rig", "kaf"} the answer will be Yes as the given strings can be chained as "for", "rig", "geek" and "kaf" 9 | 10 | 11 | Input 12 | The first line of input contains an integer T denoting the number of test cases. Then T test cases 13 | follow. 14 | The first line of each test case contains a positive integer N, denoting the size of the array. 15 | The second line of each test case contains a N space seprated strings, denoting the elements of the 16 | array A[ ]. 17 | 18 | 19 | Output 20 | If chain can be formed, then print 1, else print 0. 21 | 22 | 23 | Constraints 24 | 1 <= T <= 100 25 | 0 < N <= 30 26 | 0 < A[i] <= 10 27 | 28 | 29 | Examples 30 | 31 | Input 32 | 2 33 | 3 34 | abc bcd cdf 35 | 4 36 | ab bc cd da 37 | 38 | 39 | Output 40 | 0 41 | 1 42 | 43 | 2 44 | 3 45 | ceee eeece ddbc 46 | 5 47 | dedce cdcae debdc d abde 48 | 49 | """ 50 | 51 | from collections import defaultdict 52 | 53 | def check_cycle(graph,visited,start_v,current_v): 54 | if len(visited) > len(graph): 55 | return False 56 | visited.append(current_v) 57 | for item in graph[current_v]: 58 | if start_v == item and len(visited) == len(graph): 59 | return True 60 | if item not in visited and check_cycle(graph,visited,start_v,item): 61 | return True 62 | visited.remove(current_v) 63 | return False 64 | 65 | def isCyclic(n, graph): 66 | keys = list(graph.keys()) 67 | visited = [] 68 | if check_cycle(graph,visited,keys[0],keys[0]): 69 | return True 70 | return False 71 | 72 | def convert_to_graph(strings): 73 | graph = defaultdict(list) 74 | for string in strings: 75 | graph[string[0]].append(string[-1]) 76 | return graph 77 | 78 | def main(): 79 | t = int(input()) 80 | for i in range(t): 81 | n = int(input()) 82 | strings = input().strip(" ").split(" ") 83 | graph = convert_to_graph(strings) 84 | if isCyclic(n,graph): 85 | print(1) 86 | else: 87 | print(0) 88 | 89 | if __name__ == '__main__': 90 | main() 91 | -------------------------------------------------------------------------------- /Graph/detect_cycle_in_directed_graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1 3 | 4 | Given a directed graph your task is to complete the method isCycle to detect if there is a cycle in the graph or not. You should not read any input from stdin/console. 5 | There are multiple test cases. For each test case, this method will be called individually. 6 | 7 | 8 | Input (only to be used for Expected Output): 9 | The first line of the input contains an integer 'T' denoting the number of test cases. Then 'T' test cases follow. Each test case consists of two lines. 10 | Description of test cases is as follows: 11 | The First line of each test case contains two integers 'N' and 'M' which denotes the no of vertices and no of edges respectively. 12 | The Second line of each test case contains 'M' space separated pairs u and v denoting that there is an unidirected edge from u to v . 13 | 14 | Output: 15 | The method should return true if there is a cycle else it should return false. 16 | 17 | Constraints: 18 | 1 <=T<= 100 19 | 1<=N,M<=100 20 | 0 <=u,v<= N-1 21 | 22 | Example: 23 | Input: 24 | 2 25 | 2 2 26 | 0 1 0 0 27 | 4 3 28 | 0 1 1 2 2 3 29 | 30 | Output: 31 | 1 32 | 0 33 | 34 | """ 35 | from collections import defaultdict 36 | # Driver Program 37 | def creategraph(e,n, arr, graph): 38 | i = 0 39 | while i < 2 * e: 40 | graph[arr[i]].append(arr[i + 1]) 41 | # graph[arr[i + 1]].append(arr[i]) 42 | i += 2 43 | 44 | def main(): 45 | t = int(input()) 46 | for i in range(t): 47 | n,e = list(map(int, input().strip().split())) 48 | arr = list(map(int, input().strip().split())) 49 | graph = defaultdict(list) 50 | creategraph(e,n, arr, graph) 51 | if isCyclic(n, graph): 52 | print(1) 53 | else: 54 | print(0) 55 | # Contributed By: Harshit Sidhwa 56 | 57 | ''' Please note that it's Function problem i.e. 58 | you need to write your solution in the form of Function(s) only. 59 | Driver Code to call/invoke your function is mentioned above. ''' 60 | 61 | # Your task is to complete this function 62 | # Function should return True/False or 1/0 63 | # Graph(graph) is a defaultict of type List 64 | # n is no of Vertices 65 | 66 | def check_cycle(graph,visited,s): 67 | if visited[s] == True: 68 | return True 69 | visited[s] = True 70 | for item in graph[s]: 71 | if check_cycle(graph,visited,item): 72 | return True 73 | visited[s] = False 74 | return False 75 | 76 | def isCyclic(n, graph): 77 | for i in range(n): 78 | visited = [False]*(n) 79 | if check_cycle(graph,visited,i): 80 | return True 81 | return False 82 | if __name__ == '__main__': 83 | main() 84 | -------------------------------------------------------------------------------- /Graph/dfs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function to print the depth first traversal for a undirected graph from a given source s. 3 | 4 | Input: 5 | The task is to complete the function DFS which takes 3 arguments an integer denoting the starting node (s) of the dfs travel , a graph (g) and an 6 | array of visited nodes (vis) which are initially all set to false . 7 | There are multiple test cases. For each test case, this method will be called individually. 8 | Output: 9 | The function should print the depth first traversal for the graph from the given source. 10 | 11 | Note : The expected output button always produces DFS starting from node 1. 12 | Constraints: 13 | 1 <=T<= 100 14 | 1 <=Number of edges<= 100 15 | Example: 16 | Input: 17 | 1 18 | 4 19 | 1 2 1 3 1 4 3 5 20 | 21 | Output: 22 | 1 2 3 5 4 //dfs from node 1 23 | 24 | There is one test cases. First line of each test case represent an integer N denoting no of edges and then in the next line N pairs of values a and 25 | b are fed which denotes there is an edge from a to b . 26 | 27 | """ 28 | from collections import defaultdict 29 | 30 | # Driver Program 31 | def creategraph(n, arr, graph): 32 | i = 0 33 | while i<2*n: 34 | graph[arr[i]].append(arr[i+1]) 35 | graph[arr[i+1]].append(arr[i]) 36 | i+=2 37 | 38 | 39 | ''' Please note that it's Function problem i.e. 40 | you need to write your solution in the form of Function(s) only. 41 | Driver Code to call/invoke your function is mentioned above. ''' 42 | 43 | # Your task is to complete this function 44 | # Function should print DFS Traversal 45 | # Graph(graph) is a defaultict of type List 46 | # Starting vertex (s) is 1 47 | # Need not print new Line 48 | # n is no of edges 49 | # visit is a boolean array initialized to False 50 | def dfs(n, visit, graph, s): 51 | print(s,end=" ") 52 | visit[s] = True 53 | 54 | for item in graph[s]: 55 | if visit[item] == False: 56 | dfs(n,visit,graph,item) 57 | else: 58 | continue 59 | 60 | 61 | 62 | if __name__=='__main__': 63 | t = int(input()) 64 | for i in range(t): 65 | n = int(input()) 66 | arr = list(map(int, input().strip().split())) 67 | graph = defaultdict(list) 68 | creategraph(n, arr, graph) 69 | visit = [False]*(max(arr)+1) 70 | dfs(n, visit, graph, 1) 71 | print('') 72 | # Contributed By: Harshit Sidhwa 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Graph/find_whether_path_exists.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/find-whether-path-exist/0 3 | 4 | Given a N X N matrix (M) filled with 1 , 0 , 2 , 3 . Your task is to find whether there is a path possible from source to destination, while traversing through blank cells only. You can traverse up, down, right and left. 5 | 6 | A value of cell 1 means Source. 7 | A value of cell 2 means Destination. 8 | A value of cell 3 means Blank cell. 9 | A value of cell 0 means Blank Wall. 10 | Note : there is only single source and single destination. 11 | 12 | 13 | Examples: 14 | 15 | Input : M[3][3] = {{ 0 , 3 , 2 }, 16 | { 3 , 3 , 0 }, 17 | { 1 , 3 , 0 }}; 18 | Output : Yes 19 | 20 | Input : M[4][4] = {{ 0 , 3 , 1 , 0 }, 21 | { 3 , 0 , 3 , 3 }, 22 | { 2 , 3 , 0 , 3 }, 23 | { 0 , 3 , 3 , 3 }}; 24 | Output : Yes 25 | 26 | 27 | Input: 28 | The first line of input is an integer T denoting the no of test cases. Then T test cases follow. Each test case consists of 2 lines . The first line of each test case contains an integer N denoting the size of the square matrix . Then in the next line are N*N space separated values of the matrix (M) . 29 | 30 | Output: 31 | For each test case in a new line print 1 if the path exist from source to destination else print 0. 32 | 33 | Constraints: 34 | 1<=T<=20 35 | 1<=N<=20 36 | 37 | Example: 38 | Input: 39 | 2 40 | 4 41 | 3 0 0 0 0 3 3 0 0 1 0 3 0 2 3 3 42 | 3 43 | 0 3 2 3 0 0 1 0 0 44 | Output: 45 | 1 46 | 0 47 | 48 | """ 49 | 50 | def is_destination(n,i,j,matrix): 51 | if i<0 or j<0 or i>=n or j>=n: 52 | return False 53 | if matrix[i][j] == 2: 54 | return True 55 | if matrix[i][j] == 3 or matrix[i][j] == 1: 56 | matrix[i][j] = 4 57 | return is_destination(n,i+1,j,matrix) or is_destination(n,i,j+1,matrix) or is_destination(n,i-1,j,matrix) or is_destination(n,i,j-1,matrix) 58 | return False 59 | 60 | def find_if_path_exists(n,matrix): 61 | for i in range(n): 62 | for j in range(n): 63 | if matrix[i][j] == 1: 64 | if is_destination(n,i,j,matrix): 65 | return 1 66 | return 0 67 | 68 | def main(): 69 | t = int(input()) 70 | for i in range(t): 71 | n = int(input()) 72 | matrix_arr = [int(x) for x in input().strip(" ").split(" ")] 73 | matrix = [] 74 | for j in range(n): 75 | matrix.append(matrix_arr[j*n:(j+1)*n]) 76 | print(find_if_path_exists(n,matrix)) 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /Graph/floyd_warshall.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/implementing-floyd-warshall/0 3 | 4 | The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. 5 | 6 | Input: 7 | The first line of input contains an integer T denoting the no of test cases . Then T test cases follow . The first line of each test case contains an integer V denoting the size of the adjacency matrix and in the next line are V*V space separated values of the matrix (graph) . 8 | 9 | Output: 10 | For each test case output will be V*V space separated integers where the i-jth integer denote the shortest distance of ith vertex from jth vertex. 11 | 12 | Constraints: 13 | 1<=T<=20 14 | 1<=V<=20 15 | -1000<=graph[][]<=1000 16 | 17 | Example: 18 | Input 19 | 2 20 | 2 21 | 0 25 25 0 22 | 3 23 | 0 1 43 1 0 6 43 6 0 24 | 25 | Output 26 | 0 25 25 0 27 | 0 1 7 1 0 6 7 6 0 28 | 29 | 0 876 767 905 728 0 325 376 482 428 0 411 352 17 342 0 30 | 0 496 774 11 0 785 529 518 0 31 | 32 | 0 876 767 905 728 0 325 376 482 428 0 411 352 17 342 0 33 | 0 496 774 11 0 785 529 518 0 34 | 35 | """ 36 | 37 | def print_matrix(distance,v): 38 | for i in range(v): 39 | for j in range(v): 40 | print(distance[i][j],end=" ") 41 | print() 42 | 43 | def floyd_warshall(n,matrix): 44 | 45 | distance = [] 46 | for i in range(n): 47 | distance.append([10000]*n) 48 | 49 | for i in range(n): 50 | for j in range(n): 51 | # if matrix[i][j] != 0: 52 | distance[i][j] = matrix[i][j] 53 | if i==j: 54 | distance[i][j] = 0 55 | # else: 56 | # distance[i][j] 57 | 58 | 59 | for k in range(n): 60 | for i in range(n): 61 | for j in range(n): 62 | if distance[i][k]+distance[k][j] < distance[i][j]: 63 | distance[i][j] = distance[i][k]+distance[k][j] 64 | 65 | print_matrix(distance,n) 66 | 67 | def main(): 68 | t = int(input()) 69 | for i in range(t): 70 | n = int(input()) 71 | matrix_arr = [int(x) for x in input().strip(" ").split(" ")] 72 | matrix = [] 73 | for j in range(n): 74 | matrix.append(matrix_arr[j*n:(j+1)*n]) 75 | floyd_warshall(n,matrix) 76 | 77 | if __name__ == '__main__': 78 | main() 79 | -------------------------------------------------------------------------------- /Graph/minimum_swaps.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/minimum-swaps/1 3 | 4 | Given an array of N distinct elementsA[ ], find the minimum number of swaps required to sort the array. 5 | Your are required to complete the function which returns an integer denoting the minimum number of swaps, 6 | required to sort the array. 7 | 8 | Examples: 9 | 10 | Input : {4, 3, 2, 1} 11 | Output : 2 12 | Explanation : Swap index 0 with 3 and 1 with 2 to 13 | form the sorted array {1, 2, 3, 4}. 14 | 15 | Input : {1, 5, 4, 3, 2} 16 | Output : 2 17 | 18 | Input: 19 | The first line of input contains an integer T denoting the no of test cases . 20 | Then T test cases follow . Each test case contains an integer N denoting the no of element of 21 | the array A[ ]. In the next line are N space separated values of the array A[ ] . 22 | 23 | Output: 24 | For each test case in a new line output will be an integer denoting minimum umber of swaps that 25 | are required to sort the array. 26 | 27 | Constraints: 28 | 1<=T<=100 29 | 1<=N<=100 30 | 1<=A[] <=1000 31 | 32 | Example(To be used only for expected output): 33 | Input: 34 | 2 35 | 4 36 | 4 3 2 1 37 | 5 38 | 1 5 4 3 2 39 | Output: 40 | 2 41 | 2 42 | 43 | """ 44 | 45 | from collections import defaultdict 46 | 47 | def main(): 48 | t = int(input()) 49 | for i in range(t): 50 | n = int(input()) 51 | arr = list(map(int, input().strip().split())) 52 | minSwaps(arr, n) 53 | # Contributed by: Harshit Sidhwa 54 | 55 | 56 | ''' Please note that it's Function problem i.e. 57 | you need to write your solution in the form of Function(s) only. 58 | Driver Code to call/invoke your function is mentioned above. ''' 59 | 60 | # Your task is to complete this function 61 | # function should return an integer denoting the minimum number of swap's 62 | 63 | 64 | def count_swaps(graph,visited,current, count): 65 | if current in visited: 66 | return count-1 67 | else: 68 | visited.append(current) 69 | return count_swaps(graph,visited,graph[current],count + 1) 70 | 71 | def create_graph(arr,n): 72 | graph = {} 73 | visited = [] 74 | sorted_arr = sorted(arr) 75 | for i in range(n): 76 | if arr[i] != sorted_arr[i]: 77 | graph[arr[i]] = sorted_arr[i] 78 | else: 79 | visited.append(arr[i]) 80 | print(graph) 81 | return graph,visited 82 | 83 | 84 | def minSwaps(arr, n): 85 | graph,visited = create_graph(arr,n) 86 | swaps = 0 87 | for item in arr: 88 | if item not in visited: 89 | swaps = swaps + count_swaps(graph,visited,item,0) 90 | print(swaps) 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /Graph/shortest_source_to_destination.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/shortest-source-to-destination-path/0 3 | 4 | Given a boolean 2D matrix (0-based index), find whether there is path from (0,0) to (x,y) and 5 | if there is one path, print the minimum no of steps needed to reach it, else print -1 if the 6 | destination is not reachable. You may move in only four direction ie up, down, left and right. 7 | The path can only be created out of a cell if its value is 1. 8 | 9 | Input: 10 | The first line of input contains an integer T denoting the no of test cases. 11 | Then T test cases follow. Each test case contains two lines . The first line of each test 12 | case contains two integers n and m denoting the size of the matrix. Then in the next line 13 | are n*m space separated values of the matrix. The following line after it contains two integers 14 | x and y denoting the index of the destination. 15 | 16 | Output: 17 | For each test case print in a new line the min no of steps needed to reach the destination. 18 | 19 | Constraints: 20 | 1<=T<=100 21 | 1<=n,m<=20 22 | 23 | Example: 24 | Input: 25 | 2 26 | 3 4 27 | 1 0 0 0 1 1 0 1 0 1 1 1 28 | 2 3 29 | 3 4 30 | 1 1 1 1 0 0 0 1 0 0 0 1 31 | 0 3 32 | Output: 33 | 5 34 | 3 35 | 36 | """ 37 | 38 | def next_step(matrix,i,j,x,y,n,m): 39 | if i <0 or j<0 or i>=n or j >= m: 40 | return 100 41 | if matrix[i][j] == 0: 42 | return 100 43 | if i == x and j == y: 44 | return 0 45 | matrix[i][j] = 0 46 | return 1 + min(next_step(matrix,i+1,j,x,y,n,m),next_step(matrix,i,j+1,x,y,n,m),next_step(matrix,i-1,j,x,y,n,m),next_step(matrix,i,j-1,x,y,n,m)) 47 | 48 | def shortest_path(x,y,n,m,matrix): 49 | result = next_step(matrix,0,0,x,y,n,m) 50 | if result >=100: 51 | print(-1) 52 | else: 53 | print(result) 54 | 55 | def main(): 56 | t = int(input()) 57 | for i in range(t): 58 | numbers = input().strip(" ").split(" ") 59 | n = int(numbers[0]) 60 | m = int(numbers[1]) 61 | matrix_arr = [int(x) for x in input().strip(" ").split(" ")] 62 | matrix = [] 63 | 64 | for j in range(n): 65 | matrix.append(matrix_arr[j*m:(j+1)*m]) 66 | x_y = input().strip(" ").split(" ") 67 | x = int(x_y[0]) 68 | y = int(x_y[1]) 69 | shortest_path(x,y,n,m,matrix) 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /Greedy/activity_selection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given N activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that 3 | a person can only work on a single activity at a time. 4 | Note : The start time and end time of two activities may coincide. 5 | 6 | Input: 7 | The first line contains T denoting the number of testcases. Then follows description of testcases. First line is N number of activities then second 8 | line contains N numbers which are starting time of activies.Third line contains N finishing time of activities. 9 | 10 | Output: 11 | For each test case, output a single number denoting maximum activites which can be performed in new line. 12 | 13 | Constraints: 14 | 1<=T<=50 15 | 1<=N<=1000 16 | 1<=A[i]<=100 17 | 18 | Example: 19 | Input: 20 | 1 21 | 6 22 | 1 3 0 5 8 5 23 | 2 4 6 7 9 9 24 | 25 | Output: 26 | 4 27 | """ 28 | 29 | def activity_selection(arr,n): 30 | arr = sorted(arr,key=lambda item:item[1]) 31 | total_activity = 0 32 | prev_time = -1 33 | for element in arr: 34 | if element[0] >= prev_time: 35 | total_activity = total_activity + 1 36 | prev_time = element[1] 37 | return total_activity 38 | 39 | 40 | def main(): 41 | t = int(input().strip()) 42 | for i in range(0,t): 43 | n = int(input().strip()) 44 | s_arr = [int(x) for x in input().strip().split(" ")] 45 | e_arr = [int(x) for x in input().strip().split(" ")] 46 | arr = [] 47 | for j in range(0,n): 48 | arr.append((s_arr[j],e_arr[j])) 49 | print(activity_selection(arr,n)) 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /Greedy/geek_collects_the_balls.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The buckets n both roads are kept in 4 | such a way that they are sorted according to the number of balls in them. Geek starts from the end of the road which has the bucket with a lower 5 | number of balls(i.e. if buckets are sorted in increasing order, then geek will start from the left side of the road). 6 | The geek can change the road only at the point of intersection(which means, buckets with the same number of balls on two roads). Now you need to help 7 | Geek to collect the maximum number of balls. 8 | 9 | Input: 10 | The first line of input contains T denoting the number of test cases. The first line of each test case contains two integers N and M, denoting the 11 | number of buckets on road1 and road2 respectively. 2nd line of each test case contains N integers, number of balls in buckets on the first road. 12 | 3rd line of each test case contains M integers, number of balls in buckets on the second road. 13 | 14 | Output: 15 | For each test case output a single line containing the maximum possible balls that Geek can collect. 16 | 17 | Constraints: 18 | 1<= T <= 1000 19 | 1<= N <= 10^3 20 | 1<= M <=10^3 21 | 0<= A[i],B[i]<=10^6 22 | 23 | Example: 24 | Input: 25 | 1 26 | 5 5 27 | 1 4 5 6 8 28 | 2 3 4 6 9 29 | 30 | Output: 31 | 29 32 | """ 33 | def lastIndexOf(arr,item): 34 | return len(arr) - 1 - arr[::-1].index(item) 35 | 36 | def intersection(arr1,arr2): 37 | return [x for x in arr1 if x in arr2] 38 | 39 | def collect_balls(arr1,arr2,n): 40 | common_arr = intersection(arr1,arr2) 41 | sum_arr = 0 42 | while(len(common_arr)>0): 43 | common_number = common_arr.pop(0) 44 | index1 = lastIndexOf(arr1,common_number) 45 | index2 = lastIndexOf(arr2,common_number) 46 | if sum(arr1[:index1]) > sum(arr2[:index2]): 47 | sum_arr = sum_arr + sum(arr1[:index1]) 48 | else: 49 | sum_arr = sum_arr + sum(arr2[:index2]) 50 | arr1 = arr1[index1:] 51 | arr2 = arr2[index2:] 52 | 53 | if sum(arr1) > sum(arr2): 54 | sum_arr = sum_arr + sum(arr1) 55 | else: 56 | sum_arr = sum_arr + sum(arr2) 57 | 58 | return sum_arr 59 | 60 | 61 | def main(): 62 | t = int(input().strip()) 63 | for i in range(0,t): 64 | numbers = input().replace(" "," ").strip(" ").split(" ") 65 | n1 = int(numbers[0]) 66 | n2 = int(numbers[1]) 67 | arr1 = [int(x) for x in input().split(" ")] 68 | arr2 = [int(x) for x in input().split(" ")] 69 | print(collect_balls(arr1,arr2,n1)) 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /Greedy/largest_number_possible.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : 3 | Given two numbers 'N' and 'S' , find the largest number that can be formed with 'N' digits and whose sum of digits should be equals to 'S'. 4 | 5 | Input 6 | 7 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains 8 | two space separated integers N and S, where N is the number of digits and S is the sum. 9 | 10 | Output 11 | 12 | Print the largest number that is possible. 13 | If their is no such number, then print -1 14 | 15 | Constraints: 16 | 17 | 1 <= T <= 30 18 | 1 <= N <= 50 19 | 0 <= S <= 500 20 | 21 | Example 22 | 23 | Input 24 | 2 25 | 2 9 26 | 3 20 27 | 28 | Output 29 | 30 | 90 31 | 992 32 | Expected Time Complexity: O(n) 33 | 34 | """ 35 | 36 | def largest_number(n,s): 37 | if s==0: 38 | return -1 39 | digit = 9 40 | number = "" 41 | while(s>=0 and digit >=0 and len(number)= 0: 43 | s = s - digit 44 | number = number + str(digit) 45 | else: 46 | digit = digit - 1 47 | if s>0: 48 | return -1 49 | else: 50 | return number 51 | 52 | 53 | def main(): 54 | t = int(input().strip()) 55 | for i in range(0,t): 56 | numbers = input().strip().split(" ") 57 | n = int(numbers[0]) 58 | k = int(numbers[1]) 59 | print(largest_number(n,k)) 60 | 61 | if __name__ == '__main__': 62 | main() -------------------------------------------------------------------------------- /Greedy/maximum_toys.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/maximize-toys/0 3 | Given an array consisting cost of toys. Given an integer K depicting the amount with you. Maximise the number of toys you can have with K amount. 4 | 5 | Input: 6 | 7 | The first line contains an integer T, depicting total number of test cases. 8 | Then following T lines contains an integer N depicting the number of toys and an integer K depicting the value of K. 9 | Next line is followed by the cost of toys. 10 | 11 | Output: 12 | 13 | Print the maximum toys in separate line. 14 | 15 | Constraints: 16 | 17 | 1 <= T <= 30 18 | 1 <= N <= 1000 19 | 1 <= K <= 10000 20 | 1 <= A[i] <= 10000 21 | 22 | Example: 23 | 24 | Input 25 | 1 26 | 7 50 27 | 1 12 5 111 200 1000 10 28 | Output 29 | 4 30 | """ 31 | 32 | def maximum_toys(arr,n,k): 33 | arr = sorted(arr) 34 | index = 0 35 | count = 0 36 | while(k>0 and index < n): 37 | if k - arr[index] >= 0: 38 | k = k - arr[index] 39 | count = count + 1 40 | index = index + 1 41 | else: 42 | break 43 | print(count) 44 | 45 | 46 | def main(): 47 | t = int(input().strip()) 48 | for i in range(0,t): 49 | numbers = input().strip().split(" ") 50 | n = int(numbers[0]) 51 | k = int(numbers[1]) 52 | 53 | arr = [int(x) for x in input().strip().split(" ")] 54 | maximum_toys(arr,n,k) 55 | 56 | if __name__ == '__main__': 57 | main() -------------------------------------------------------------------------------- /Greedy/minimize_sum_of_products.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given two arrays, A and B, of equal size n, the task is to find the minimum value of A[0] * B[0] + A[1] * B[1] +...+ A[n-1] * B[n-1], where 4 | shuffling of elements of arrays A and B is allowed. 5 | 6 | Examples: 7 | Input : A[] = {3, 1, 1} and B[] = {6, 5, 4}. 8 | Output : 23 Minimum value of S = 1*6 + 1*5 + 3*4 = 23. 9 | Input : A[] = { 6, 1, 9, 5, 4 } and B[] = { 3, 4, 8, 2, 4 } 10 | Output : 80. Minimum value of S = 1*8 + 4*4 + 5*4 + 6*3 + 9*2 = 80. 11 | 12 | Input: 13 | The first line of input contains an integer denoting the no of test cases. Then T test cases follow. Each test case contains three lines. The first 14 | line of input contains an integer N denoting the size of the arrays. In the second line are N space separated values of the array A[], and in 15 | the last line are N space separated values of the array B[]. 16 | Output: 17 | For each test case in a new line print the required result. 18 | Constraints: 19 | 1<=T<=100 20 | 1<=N<=50 21 | 1<=A[]<=20 22 | Example: 23 | Input: 24 | 2 25 | 3 26 | 3 1 1 27 | 6 5 4 28 | 5 29 | 6 1 9 5 4 30 | 3 4 8 2 4 31 | Output: 32 | 23 33 | 80 34 | 35 | """ 36 | def multiply(n,arr1,arr2): 37 | product = 0 38 | for i in range(0,n): 39 | product = product + arr1[i]*arr2[i] 40 | return product 41 | 42 | def minimize_product(n,arr1,arr2): 43 | return multiply(n,sorted(arr1),sorted(arr2,reverse=True)) 44 | 45 | def main(): 46 | t = int(input()) 47 | for i in range(0,t): 48 | n = int(input()) 49 | arr1 = [int(x) for x in input().strip().split(" ")] 50 | arr2 = [int(x) for x in input().strip().split(" ")] 51 | print(minimize_product(n,arr1,arr2)) 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /Greedy/minimum_number_of_coins.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/-minimum-number-of-coins/0 3 | 4 | Given a value N, if we want to make change for N Rs, and we have infinite supply of each of the denominations in Indian currency, i.e., we have 5 | infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, Find the minimum number of coins and/or notes needed to make the 6 | change. 7 | 8 | Input: 9 | 10 | The first line of input contains an integer T denoting the number of test cases. 11 | Each test case consist of an Integer value N denoting the amount to get change for. 12 | 13 | Output: 14 | 15 | Print all the possible denominations needed to make the change in a separate line. 16 | 17 | Constraints: 18 | 19 | 1 <= T <= 30 20 | 1 <= N <= 2000 21 | 22 | Example: 23 | 24 | Input 25 | 1 26 | 43 27 | Output 28 | 20 20 2 1 29 | """ 30 | 31 | def minimum_coins(n,coins): 32 | index = len(coins) - 1 33 | while(n>0 and index >= 0): 34 | if n - coins[index] >= 0: 35 | n = n - coins[index] 36 | print(coins[index], end=" ") 37 | else: 38 | index = index - 1 39 | print() 40 | 41 | def main(): 42 | coins = [1, 2, 5, 10, 20, 50, 100, 500, 1000] 43 | t = int(input()) 44 | for i in range(0,t): 45 | n = int(input()) 46 | minimum_coins(n,coins) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() -------------------------------------------------------------------------------- /Greedy/minimum_operations.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a number N the task is to find an optimal solution to reach N from 0 using 2 operations ie 4 | 1. Double the number 5 | 2. Add one to the number 6 | Example 7 | Input : N = 8 8 | Output : 4 9 | 0 + 1 = 1, 1 + 1 = 2, 2 * 2 = 4, 4 * 2 = 8 10 | 11 | Input : N = 7 12 | Output : 5 13 | 0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3, 3 * 2 = 6, 6 + 1 = 7 14 | 15 | Input: 16 | The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N. 17 | Output: 18 | For each test case in a new line print an integer denoting the min no of operation to be performed to reach N from 0. 19 | Constraints: 20 | 1<=T<=100 21 | 1<=N<=10000 22 | Example: 23 | Input: 24 | 2 25 | 8 26 | 7 27 | Input: 28 | 4 29 | 5 30 | 31 | """ 32 | def minimum_operations(n): 33 | count = 0 34 | while(n>0): 35 | if n % 2 == 0: 36 | n = n/2 37 | else: 38 | n = n-1 39 | count = count +1 40 | return count 41 | 42 | def main(): 43 | t = int(input()) 44 | for i in range(0,t): 45 | n = int(input()) 46 | print(minimum_operations(n)) 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /Greedy/n_meetings_in_one_room.py: -------------------------------------------------------------------------------- 1 | """ 2 | There is one meeting room in Flipkart. There are n meetings in the form of (S [ i ], F [ i ]) where S [ i ] is start time of meeting i and F [ i ] is 3 | finish time of meeting i 4 | 5 | What is the maximum number of meetings that can be accommodated in the meeting room ? 6 | 7 | 8 | Input: 9 | 10 | The first line of input consists number of the test cases. The description of T test cases is as follows: 11 | 12 | The first line consists of the size of the array, second line has the array containing the starting time of all the meetings each separated by a 13 | space, i.e., S [ i ]. And the third line has the array containing the finishing time of all the meetings each separated by a space, i.e., F [ i ]. 14 | 15 | Output: 16 | 17 | In each separate line print the order in which the meetings take place separated by a space. 18 | 19 | Constraints: 20 | 21 | 1 <= T <= 70 22 | 23 | 1 <= N <= 100 24 | 25 | 1 <= S[ i ], F[ i ] <= 100000 26 | 27 | Example: 28 | 29 | Input: 30 | 31 | 2 32 | 6 33 | 1 3 0 5 8 5 34 | 2 4 6 7 9 9 35 | 8 36 | 75250 50074 43659 8931 11273 27545 50879 77924 37 | 112960 114515 81825 93424 54316 35533 73383 160252 38 | 39 | Output: 40 | 41 | 1 2 4 5 42 | 6 7 1 43 | """ 44 | 45 | def activity_selection(arr,n): 46 | arr = sorted(arr,key=lambda item:item[2]) 47 | activities = [] 48 | prev_time = -1 49 | for element in arr: 50 | if element[1] >= prev_time: 51 | activities.append(element[0]) 52 | prev_time = element[2] 53 | 54 | for item in activities: 55 | print(item, end=" ") 56 | print() 57 | 58 | 59 | def main(): 60 | t = int(input().strip()) 61 | for i in range(0,t): 62 | n = int(input().strip()) 63 | s_arr = [int(x) for x in input().strip().split(" ")] 64 | e_arr = [int(x) for x in input().strip().split(" ")] 65 | arr = [] 66 | for j in range(0,n): 67 | arr.append((j+1,s_arr[j],e_arr[j])) 68 | activity_selection(arr,n) 69 | 70 | if __name__ == '__main__': 71 | main() 72 | 73 | -------------------------------------------------------------------------------- /Greedy/page_faults_in_LRU.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/page-faults-in-lru/0 3 | 4 | In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needs to be replaced when the 5 | new page comes in. Whenever a new page is referred and is not present in memory, the page fault occurs and Operating System replaces one of the 6 | existing pages with a newly needed page. 7 | Given a sequence of pages and memory capacity, your task is to find the number of page faults using Least Recently Used (LRU) Algorithm. 8 | Input: 9 | The first line of input contains an integer T denoting the number of test cases. Each test case contains n number of pages and next line contains 10 | space seaprated sequence of pages. The following line consist of the capacity of the memory. 11 | Note: Pages are referred in the order left to right from the array (i.e index 0 page is referred first then index 1 and so on). Memory is empty at 12 | thestart . 13 | Output: 14 | Output the number of page faults. 15 | Constraints: 16 | 1<=T<=100 17 | 1<=n<=1000 18 | 4<=capacity<=100 19 | Example: 20 | Input: 21 | 2 22 | 9 23 | 5 0 1 3 2 4 1 0 5 24 | 4 25 | 8 26 | 3 1 0 2 5 4 1 2 27 | 4 28 | Output: 29 | 8 30 | 7 31 | 32 | """ 33 | 34 | def page_faults(arr,n,k): 35 | pages = [] 36 | count = 0 37 | for item in arr: 38 | if item in pages: 39 | pages.remove(item) 40 | pages.append(item) 41 | continue 42 | else: 43 | pages.append(item) 44 | count = count + 1 45 | if len(pages) > k: 46 | pages.pop(0) 47 | print(count) 48 | 49 | 50 | def main(): 51 | t = int(input().strip()) 52 | for i in range(0,t): 53 | n = int(input()) 54 | arr = [int(x) for x in input().strip().split(" ")] 55 | k = int(input()) 56 | page_faults(arr,n,k) 57 | 58 | if __name__ == '__main__': 59 | main() 60 | 61 | -------------------------------------------------------------------------------- /Greedy/shop_in_candy_store.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. 4 | You are now provided with an attractive offer. 5 | You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free. 6 | Now you have to answer two questions. Firstly, you have to tell what is the minimum amount of money you have to spend to buy all the N different 7 | candies. Secondly, you have to tell what is the maximum amount of money you have to spend to buy all the N different candies. 8 | In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free. 9 | 10 | Input 11 | The first line of the input contains T the number of test cases. Each test case consists of two lines. The first line of each test case contains the 12 | values of N and K as described above. Then in the next line N integers follow denoting the price of each of the N different candies. 13 | 14 | Output 15 | For each test case output a single line containing 2 space separated integers , the first denoting the minimum amount of money required to be spent 16 | and the second denoting the maximum amount of money to be spent. 17 | Remember to output the answer of each test case in a new line. 18 | Constraints 19 | 1 <= T <= 50 20 | 1 <= N <= 1000 21 | 0 <= K <= N-1 22 | 1 <= Ai <= 100 23 | 24 | Expected Time Complexity : O(nlogn) 25 | 26 | Example: 27 | Input 28 | 1 29 | 4 2 30 | 3 2 1 4 31 | 32 | Output 33 | 3 7 34 | 35 | """ 36 | 37 | def shop_candy(arr,n,k): 38 | min_money = 0 39 | max_money = 0 40 | arr = sorted(arr) 41 | min_arr = arr[:] 42 | max_arr = arr[::-1] 43 | 44 | while(len(min_arr)>0): 45 | min_money = min_money + min_arr.pop(0) 46 | if k > 0: 47 | min_arr = min_arr[:-k] 48 | 49 | while(len(max_arr)>0): 50 | max_money = max_money + max_arr.pop(0) 51 | if k > 0: 52 | max_arr = max_arr[:-k] 53 | return str(min_money) + " " + str(max_money) 54 | 55 | def main(): 56 | t = int(input()) 57 | for i in range(0,t): 58 | numbers = input().replace(" "," ").strip(" ").split(" ") 59 | n = int(numbers[0]) 60 | k = int(numbers[1]) 61 | arr = [int(x) for x in input().strip().split(" ")] 62 | print(shop_candy(arr,n,k)) 63 | 64 | if __name__ == '__main__': 65 | main() 66 | 67 | -------------------------------------------------------------------------------- /Hashing/largest_subarray_with0sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array having both positive an negative integers . Your task is to complete the function maxLen which returns the length of maximum subarray with 0 sum . The function takes two arguments an array A and n where n is the size of the array A . 3 | 4 | Input: 5 | The first line of input contains an element T denoting the No of test cases. Then T test cases follow. Each test case consist of 2 lines. The first line of each test case contains a number denoting the size of the array A. Then in the next line are space separated values of the array A . 6 | 7 | Output: 8 | For each test case output will be the length of the largest subarray which has sum 0 . 9 | 10 | Constraints: 11 | 1<=T<=100 12 | 1<=N<=100 13 | -1000<=A[]<=1000 14 | 15 | Example: 16 | Input 17 | 1 18 | 8 19 | 15 -2 2 -8 1 7 10 23 20 | 21 | Output 22 | 5 23 | 24 | """ 25 | 26 | # Contributed by: Harshit Sidhwa 27 | 28 | ''' Please note that it's Function problem i.e. 29 | you need to write your solution in the form of Function(s) only. 30 | Driver Code to call/invoke your function is mentioned above. ''' 31 | 32 | #Your task is to complete this function 33 | #Your should return the required output 34 | def maxLen(n, arr): 35 | #Code here 36 | index_arr = [0]*(n) 37 | max_sum = 0 38 | for i in range(0,len(arr)): 39 | arr_sum = 0 40 | for j in range(i,len(arr)): 41 | arr_sum = arr_sum + arr[j] 42 | if arr_sum == 0: 43 | index_arr[i] = j-i+1 44 | return max(index_arr) 45 | 46 | if __name__=='__main__': 47 | t= int(input()) 48 | for i in range(t): 49 | n = int(input()) 50 | arr = list(map(int, input().strip().split())) 51 | print(maxLen(n ,arr)) -------------------------------------------------------------------------------- /Hashing/swapping_pairs_make_sum_equal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two arrays of integers, write a program to check if a pair of values (one value from each array) exists such that swapping the elements of the pair will make the sum of two arrays equal. 3 | 4 | Input: 5 | First line of input contains a single integer T which denotes the number of test cases. T test cases follows. First line of each test case contains two space separated integers N and M. Second line of each test case contains N space separated integers denoting the elements of first array. Third line of each test case contains M space separated integers denoting the elements of second array. 6 | 7 | Output: 8 | For each test case, print 1 if there exists any such pair otherwise print -1. 9 | 10 | Constraints: 11 | 1<=T<=100 12 | 1<=N<=10000 13 | 1<=M<=10000 14 | 15 | Example: 16 | Input: 17 | 2 18 | 6 4 19 | 4 1 2 1 1 2 20 | 3 6 3 3 21 | 4 4 22 | 5 7 4 6 23 | 1 2 3 8 24 | Output: 25 | 1 26 | 1 27 | """ 28 | 29 | def swapping_pair(arr1,arr2): 30 | sum1 = sum(arr1) 31 | sum2 = sum(arr2) 32 | 33 | diff = abs(sum1 - sum2) 34 | if diff%2 !=0: 35 | return -1 36 | item = int(diff/2) 37 | 38 | for item1 in arr1: 39 | for item2 in arr2: 40 | if abs(item1-item2) == item: 41 | return 1 42 | 43 | return -1 44 | 45 | def main(): 46 | t = int(input()) 47 | for i in range(0,t): 48 | numbers = input().strip(" ").split(" ") 49 | n = int(numbers[0]) 50 | m = int(numbers[1]) 51 | arr1 = [int(x) for x in input().strip(" ").split(" ")] 52 | arr2 = [int(x) for x in input().strip(" ").split(" ")] 53 | print(swapping_pair(arr1,arr2)) 54 | if __name__ == '__main__': 55 | main() -------------------------------------------------------------------------------- /Heap/heap_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/heap-sort/1 3 | The task is to complete heapify() and buildHeap() functions which are used to implement Heap Sort. 4 | 5 | Input: 6 | First line of the input denotes number of test cases 'T'. First line of the test case is the size of array and second line consists of array elements. 7 | 8 | 9 | Output: 10 | Sorted array in ascending order. 11 | 12 | 13 | Constraints: 14 | 1 <=T<= 50 15 | 1 <=N<= 1000 16 | 1 <=arr[i]<= 1000 17 | 18 | 19 | Example: 20 | 21 | Input: 22 | 2 23 | 5 24 | 4 1 3 9 7 25 | 10 26 | 10 9 8 7 6 5 4 3 2 1 27 | 28 | Output: 29 | 1 3 4 7 9 30 | 1 2 3 4 5 6 7 8 9 10 31 | """ 32 | 33 | def left(i): 34 | return 2*i+1 35 | def right(i): 36 | return 2*i +2 37 | 38 | def max_headpify(arr,i): 39 | max_index = i 40 | 41 | if left(i)arr[left(i)]: 53 | min_index = left(i) 54 | 55 | if right(i) arr[right(i)]: 56 | min_index = right(i) 57 | 58 | if i != min_index: 59 | arr[i],arr[min_index] = arr[min_index],arr[i] 60 | min_headpify(arr,min_index) 61 | 62 | 63 | def insert_min_heap(min_heap,item): 64 | min_heap.append(item) 65 | min_heap_up(min_heap,len(min_heap)-1) 66 | 67 | def kth_largest(arr,n,k): 68 | min_heap = [] 69 | for i in range(0,n): 70 | if i < k-1: 71 | insert_min_heap(min_heap,arr[i]) 72 | print("-1",end=" ") 73 | continue 74 | if i == k-1: 75 | insert_min_heap(min_heap,arr[i]) 76 | print(min_heap[0],end=" ") 77 | continue 78 | if arr[i] > min_heap[0]: 79 | min_heap[0] = arr[i] 80 | min_headpify(min_heap,0) 81 | print(min_heap[0],end=" ") 82 | print() 83 | 84 | t = int(input()) 85 | for i in range(0,t): 86 | numbers = input().strip().split(" ") 87 | k = int(numbers[0]) 88 | n = int(numbers[1]) 89 | arr = [int(x) for x in input().strip().split(" ")] 90 | kth_largest(arr,n,k) -------------------------------------------------------------------------------- /LinkedList/add_two_numbers.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | 9 | 10 | def node_value(node): 11 | if node: 12 | return node.data 13 | else: 14 | return 0 15 | 16 | 17 | def add_digits(d1, d2, c=0): 18 | return (d1 + d2 + c) // 10, (d1 + d2 + c) % 10 19 | 20 | 21 | def add(carry, list1, list2): 22 | if carry == 0 and list1 == None and list2 == None: 23 | return None 24 | 25 | carry, value = add_digits(node_value(list1), node_value(list2), carry) 26 | node = Node(value) 27 | if list1: 28 | list1 = list1.next 29 | 30 | if list2: 31 | list2 = list2.next 32 | 33 | node.next = add(carry, list1, list2) 34 | return node 35 | 36 | 37 | def print_linked_list(link: Node): 38 | while link: 39 | print(f"{link.data} -> ", end="") 40 | link = link.next 41 | print(f"Null") 42 | 43 | 44 | class TestCase(unittest.TestCase): 45 | def test_reverse(self): 46 | list1 = None 47 | for i in [7, 5, 9, 4, 6][::-1]: 48 | node = Node(i) 49 | node.next = list1 50 | list1 = node 51 | 52 | list2 = None 53 | for i in [8, 4][::-1]: 54 | node = Node(i) 55 | node.next = list2 56 | list2 = node 57 | 58 | print_linked_list(list1) 59 | print_linked_list(list2) 60 | result = add(0, list1, list2) 61 | print_linked_list(result) 62 | 63 | 64 | if __name__ == "__main__": 65 | unittest.main() 66 | -------------------------------------------------------------------------------- /LinkedList/merge_two_sorted_list.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | 9 | 10 | def merge(list1, list2): 11 | if not list1: 12 | return list2 13 | 14 | if not list2: 15 | return list1 16 | 17 | if list1.data < list2.data: 18 | list1.next = merge(list1.next, list2) 19 | return list1 20 | else: 21 | list2.next = merge(list1, list2.next) 22 | return list2 23 | 24 | 25 | def print_linked_list(link: Node): 26 | while link: 27 | print(f"{link.data} -> ", end="") 28 | link = link.next 29 | print(f"Null") 30 | 31 | 32 | class TestCase(unittest.TestCase): 33 | def test_reverse(self): 34 | list1 = None 35 | for i in range(10, 0, -2): 36 | node = Node(i) 37 | node.next = list1 38 | list1 = node 39 | 40 | list2 = None 41 | for i in range(9, 0, -2): 42 | node = Node(i) 43 | node.next = list2 44 | list2 = node 45 | 46 | print_linked_list(list1) 47 | print_linked_list(list2) 48 | result = merge(list1, list2) 49 | print_linked_list(result) 50 | 51 | 52 | if __name__ == "__main__": 53 | unittest.main() 54 | -------------------------------------------------------------------------------- /LinkedList/reverse_linked_list.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | 9 | 10 | def k_reverse(reversed, remain, k): 11 | if not remain: 12 | return reversed 13 | 14 | count = k 15 | 16 | start = remain 17 | while count > 0 and remain.next: 18 | remain = remain.next 19 | count -= 1 20 | 21 | end = remain 22 | 23 | next = remain.next 24 | remain.next = reversed 25 | reversed = remain 26 | 27 | return reverse(reversed, next) 28 | 29 | 30 | def reverse(reversed, remain): 31 | if not remain: 32 | return reversed 33 | next = remain.next 34 | remain.next = reversed 35 | reversed = remain 36 | 37 | return reverse(reversed, next) 38 | 39 | 40 | def print_linked_list(link: Node): 41 | while link: 42 | print(f"{link.data} -> ", end="") 43 | link = link.next 44 | print(f"Null") 45 | 46 | 47 | class TestCase(unittest.TestCase): 48 | def test_reverse(self): 49 | head = None 50 | for i in range(10, 0, -1): 51 | node = Node(i) 52 | node.next = head 53 | head = node 54 | 55 | result = reverse(None, head) 56 | print_linked_list(result) 57 | 58 | 59 | if __name__ == "__main__": 60 | unittest.main() 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Geeks for Geeks Must Do Coding Questions in Python 2 | 3 | ## you can refer the link here : 4 | [Geeks For Geeks Must Do Coding Questions](https://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/#bits) -------------------------------------------------------------------------------- /Recursion/combination_sum_part2.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/combination-sum-part-2/0 3 | 4 | Given an array of integers A and a sum B, find all unique combinations in A where the sum is equal to B. 5 | 6 | ach number in A may only be used once in the combination. 7 | 8 | Note: 9 | All numbers will be positive integers. 10 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 11 | The combinations themselves must be sorted in ascending order. 12 | If there is no combination possible the print "Empty" (without qoutes). 13 | Example, 14 | Given A = 10,1,2,7,6,1,5 and B(sum) 8, 15 | 16 | A solution set is: 17 | 18 | [1, 7] 19 | [1, 2, 5] 20 | [2, 6] 21 | [1, 1, 6] 22 | 23 | Input: 24 | First is T , no of test cases. 1<=T<=500 25 | Every test case has three lines. 26 | First line is N, size of array. 1<=N<=12 27 | Second line contains N space seperated integers(x). 1<=x<=9. 28 | Third line is the sum B. 1<=B<=30. 29 | 30 | Output: 31 | One line per test case, every subset enclosed in () and in every set intergers should be space seperated.(See example) 32 | 33 | Example: 34 | Input: 35 | 2 36 | 7 37 | 10 1 2 7 6 1 5 38 | 8 39 | 5 40 | 8 1 8 6 8 41 | 12 42 | 43 | Output: 44 | (1 1 6)(1 2 5)(1 7)(2 6) 45 | Empty 46 | 47 | """ 48 | def to_tuple(arr): 49 | if len(arr) == 0: 50 | return "" 51 | result = "(" 52 | comma_flag = True 53 | for item in arr: 54 | if comma_flag: 55 | comma_flag = False 56 | result = result + str(item) 57 | else: 58 | result = result + " " + str(item) 59 | return result + ")" 60 | 61 | 62 | def combination_sum(prefix,rem,given_sum): 63 | prefix_sum = sum(prefix) 64 | difference = given_sum - prefix_sum 65 | if difference < 0: 66 | return "" 67 | if difference == 0: 68 | return to_tuple(prefix) 69 | 70 | result = "" 71 | prev = None 72 | for i in range(0,len(rem)): 73 | item = rem[i] 74 | if prev and prev == item: 75 | prev = item 76 | continue 77 | if prefix_sum + item > given_sum: 78 | break 79 | result = result + combination_sum(prefix+[item],rem[i+1:],given_sum) 80 | prev = item 81 | return result 82 | 83 | 84 | 85 | 86 | def main(): 87 | t = int(input()) 88 | for i in range(0,t): 89 | n = int(input()) 90 | arr = [int(x) for x in input().strip().split(" ")] 91 | given_sum = int(input()) 92 | result = combination_sum([],sorted(arr),given_sum) 93 | if len(result) == 0: 94 | print("Empty") 95 | else: 96 | print(result) 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /Recursion/josephus_problem.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/josephus-problem/1 3 | 4 | Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle in a fixed direction.​ The task is to choose the safe place in the circle so that when you perform these operations starting from 1st place in the circle, you are the last one remaining and survive. You are required to complete the function josephus which returns an integer denoting such position . 5 | 6 | Input: 7 | The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains 2 integers n and k . 8 | 9 | Output: 10 | For each test case in a new line output will be the safe position which satisfies the above condition. 11 | 12 | Constraints: 13 | 1<=T<=100 14 | 1<=k,n<=20 15 | 16 | Example(To be used only for expected output) : 17 | Input: 18 | 2 19 | 3 2 20 | 5 3 21 | 22 | Output 23 | 3 24 | 4 25 | 26 | """ 27 | 28 | 29 | 30 | ''' Please note that it's Function problem i.e. 31 | you need to write your solution in the form of Function(s) only. 32 | Driver Code to call/invoke your function is mentioned above. ''' 33 | 34 | #Your task is to complete this function 35 | #Your function should return an integer 36 | def find_position(arr,k,start): 37 | if len(arr) == 1: 38 | return arr[0] 39 | 40 | index = (start+k-1)%len(arr) 41 | arr.pop(index) 42 | 43 | return find_position(arr,k,(index)%len(arr)) 44 | 45 | def josephus(n, k): 46 | arr = [] 47 | for i in range(1,n+1): 48 | arr.append(i) 49 | return find_position(arr,k,0) 50 | 51 | 52 | #Your Code goes here 53 | if __name__=='__main__': 54 | t= int(input()) 55 | for i in range(t): 56 | n,k = list(map(int, input().strip().split())) 57 | print(josephus(n ,k)) 58 | # contributed by:Harshit Sidhwa -------------------------------------------------------------------------------- /Recursion/number_of_paths.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/number-of-paths/0 3 | 4 | he problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down. 5 | 6 | Input: 7 | The first line of input contains an integer T, denoting the number of test cases. 8 | The first line of each test case is M and N, M is number of rows and N is number of columns. 9 | 10 | Output: 11 | For each test case, print the number of paths. 12 | 13 | Constraints: 14 | 15 | 1 ≤ T ≤ 30 16 | 1 ≤ M,N ≤ 10 17 | 18 | Example: 19 | Input 20 | 2 21 | 3 3 22 | 2 8 23 | Output 24 | 6 25 | 8 26 | 27 | """ 28 | 29 | def number_of_paths(x,y,n,m): 30 | if x >= n or y >= m: 31 | return 0 32 | if x == n-1 and y == m-1: 33 | return 1 34 | return number_of_paths(x+1,y,n,m) + number_of_paths(x,y+1,n,m) 35 | 36 | def main(): 37 | t = int(input()) 38 | for i in range(0,t): 39 | numbers = input().strip().split(" ") 40 | n = int(numbers[0]) 41 | m = int(numbers[1]) 42 | print(number_of_paths(0,0,n,m)) 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /Recursion/water_overflow.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/champagne-overflow/0 3 | 4 | There is a stack of water glasses in a form of pascal triangle and a person wants to pour the water at the topmost glass, but the capacity of each glass is 1 unit . Overflow takes place in such a way that after 1 unit, 1/2 of remaining unit gets into bottom left glass and other half in bottom right glass. 5 | 6 | Now the pours K units of water in the topmost glass and wants to know how much water is there in the jth glass of the ith row. 7 | 8 | Assume that there are enough glasses in the triangle till no glass overflows. 9 | 10 | Input: First line of the input contains an integer T denoting the number of test cases and each test case consists of three lines. First line contain an integer K, second line contains an integer i and third line contains an integer j. 11 | 12 | 13 | Output: Corresponding to each test case output the remaining amount of water in jth cup of the ith row correct to 6 decimal places. 14 | 15 | 16 | Constraints: 17 | 18 | T<=20 19 | K<=1000 20 | i <= K 21 | j<= K 22 | 23 | Example: 24 | Input: 25 | 26 | 1 27 | 3 28 | 2 29 | 1 30 | 31 | Output: 32 | 1 33 | 34 | """ 35 | def water_in_glass(k,i,j): 36 | if j>i or j <= 0: 37 | return 0 38 | if i == 1 and j==1: 39 | return k 40 | 41 | left_water = water_in_glass(k,i-1,j-1) 42 | right_water = water_in_glass(k,i-1,j) 43 | 44 | total_water = 0.0 45 | if left_water > 1: 46 | total_water = total_water + (left_water-1)/2 47 | 48 | if right_water > 1: 49 | total_water = total_water + (right_water-1)/2 50 | 51 | return total_water 52 | 53 | 54 | def main(): 55 | t = int(input()) 56 | for i in range(0,t): 57 | k = int(input()) 58 | i = int(input()) 59 | j = int(input()) 60 | over_flow_water = water_in_glass(k,i,j) 61 | if over_flow_water > 1: 62 | print(1.0) 63 | else: 64 | print(over_flow_water) 65 | 66 | if __name__ == '__main__': 67 | main() 68 | -------------------------------------------------------------------------------- /StackAndQueues/GetMinElementFromStack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Get_Min_From_Stack 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | int T = sc.nextInt(); 8 | while(T>0) 9 | { 10 | int q = sc.nextInt(); 11 | GfG g = new GfG(); 12 | while(q>0) 13 | { 14 | int qt = sc.nextInt(); 15 | 16 | if(qt == 1) 17 | { 18 | int att = sc.nextInt(); 19 | g.push(att); 20 | //System.out.println(att); 21 | } 22 | else if(qt == 2) 23 | { 24 | System.out.print(g.pop()+" "); 25 | } 26 | else if(qt == 3) 27 | { 28 | System.out.print(g.getMin()+" "); 29 | } 30 | 31 | q--; 32 | } 33 | System.out.println(); 34 | T--; 35 | } 36 | 37 | } 38 | } 39 | 40 | /*Please note that it's Function problem i.e. 41 | you need to write your solution in the form of Function(s) only. 42 | Driver Code to call/invoke your function is mentioned above.*/ 43 | 44 | class GfG 45 | { 46 | int minEle; 47 | Stack s = new Stack(); 48 | Stack minStack = new Stack(); 49 | /*returns min element from stack*/ 50 | int getMin() 51 | { 52 | if (minStack.isEmpty()) 53 | return -1; 54 | return minStack.peek(); 55 | } 56 | 57 | /*returns poped element from stack*/ 58 | int pop() 59 | { 60 | if(s.isEmpty()) 61 | return -1; 62 | minStack.pop(); 63 | return s.pop(); 64 | } 65 | /*push element x into the stack*/ 66 | void push(int x) 67 | { 68 | s.push(x); 69 | if(minStack.isEmpty() || minStack.peek()>x){ 70 | minStack.push(x); 71 | } 72 | else{ 73 | minStack.push(minStack.peek()); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /StackAndQueues/StackUsingQueue.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | class StackUsingQueues 4 | { 5 | public static void main(String args[]) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | int t = sc.nextInt(); 9 | while(t>0) 10 | { 11 | GfG g = new GfG(); 12 | 13 | int q = sc.nextInt(); 14 | while(q>0) 15 | { 16 | int QueryType = sc.nextInt(); 17 | if(QueryType == 1) 18 | { 19 | int a = sc.nextInt(); 20 | g.push(a); 21 | } 22 | else if(QueryType == 2) 23 | System.out.print(g.pop()+" "); 24 | q--; 25 | } 26 | System.out.println(); 27 | 28 | 29 | 30 | t--; 31 | } 32 | } 33 | } 34 | 35 | /*Please note that it's Function problem i.e. 36 | you need to write your solution in the form of Function(s) only. 37 | Driver Code to call/invoke your function is mentioned above.*/ 38 | 39 | class GfG 40 | { 41 | Queue q1 = new LinkedList(); 42 | Queue q2 = new LinkedList(); 43 | 44 | /*The method pop which return the element poped out of the stack*/ 45 | int pop() 46 | { 47 | int lastElement = -1; 48 | if(q1.size()==0){ 49 | while(q2.size()>0){ 50 | lastElement = q2.poll(); 51 | if(q2.size()!=0) 52 | q1.add(lastElement); 53 | } 54 | } 55 | else{ 56 | while(q1.size()>0){ 57 | lastElement = q1.poll(); 58 | if(q1.size()!=0) 59 | q2.add(lastElement); 60 | } 61 | } 62 | 63 | return lastElement; 64 | } 65 | 66 | /* The method push to push element into the stack */ 67 | void push(int a) 68 | { 69 | if(q1.size()>0){ 70 | q1.add(a); 71 | return; 72 | } 73 | 74 | if(q2.size()>0){ 75 | q2.add(a); 76 | return; 77 | } 78 | 79 | q1.add(a); 80 | } 81 | } -------------------------------------------------------------------------------- /StackAndQueues/circular_tour.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/circular-tour/1 3 | 4 | Suppose there is a circle. There are n petrol pumps on that circle. You will be given two sets of data. 5 | 6 | 1. The amount of petrol that every petrol pump has. 7 | 2. Distance from that petrol pump to the next petrol pump. 8 | 9 | Your task is to complete the function tour which returns an integer denoting the first point from where a truck will be able to complete the circle (The truck will stop at each petrol pump and it has infinite capacity). 10 | 11 | Note : Assume for 1 litre petrol, the truck can go 1 unit of distance. 12 | 13 | Input 14 | The first line of input will be the no of test cases . Then T test cases follow . Each Test case contains 2 lines . The first line will contain an integer N denoting the no of petrol pumps and in the next line are N space separated values petrol and distance denoting the amount of petrol every petrol pump has and the distance to next petrol pump respectively . 15 | 16 | Output 17 | The output of each test case will be the index of the the first point from where a truck will be able to complete the circle otherwise -1 . 18 | 19 | Constraints: 20 | 1<=T<=100 21 | 1<=N<=50 22 | 1<=petrol,distance<=100 23 | 24 | Example (To be used only for expected output) 25 | Input 26 | 1 27 | 4 28 | 4 6 6 5 7 3 4 5 29 | Output 30 | 1 31 | """ 32 | 33 | 34 | ''' Please note that it's Function problem i.e. 35 | you need to write your solution in the form of Function(s) only. 36 | Driver Code to call/invoke your function is mentioned above. ''' 37 | 38 | ''' 39 | lis[][0]:Petrol 40 | lis[][1]:Distance 41 | ''' 42 | #Your task isto complete this function 43 | #Your function should return the starting point 44 | def tour(lis, n): 45 | l = 0 46 | r = 0 47 | sum = 0 48 | count = 0 49 | while(count i: 52 | print(-1,end=" ") 53 | 54 | 55 | print() 56 | def main(): 57 | t = int(input()) 58 | for i in range(t): 59 | n = int(input()) 60 | arr = input().strip(" ").split(" ") 61 | non_repeating(arr,n) 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /StackAndQueues/infix_to_postfix..py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def priority(char): 5 | if char == "+" or char == "-": 6 | return 1 7 | if char == "*" or char == "/": 8 | return 2 9 | if char == "^": 10 | return 3 11 | return 0 12 | 13 | 14 | def infix_to_postfix(string): 15 | 16 | stack = [] 17 | result = "" 18 | for i in range(len(string)): 19 | if string[i] == "(": 20 | stack.append(string[i]) 21 | continue 22 | if string[i] == ")": 23 | while len(stack) > 0: 24 | item = stack.pop() 25 | if item == "(": 26 | break 27 | else: 28 | result = result + item 29 | continue 30 | if priority(string[i]) == 0: 31 | result = result + string[i] 32 | continue 33 | if priority(string[i]) != 0: 34 | while len(stack) > 0 and priority(stack[-1]) >= priority(string[i]): 35 | result = result + stack.pop() 36 | stack.append(string[i]) 37 | while len(stack) > 0: 38 | result = result + stack.pop() 39 | return result 40 | 41 | 42 | class TestCase(unittest.TestCase): 43 | def test_sample(self): 44 | dataT = [("a+b*(c^d-e)^(f+g*h)-i", "abcd^e-fgh*+^*+i-")] 45 | for item in dataT: 46 | result = infix_to_postfix(item[0]) 47 | self.assertEqual(result, item[1]) 48 | 49 | 50 | def main(): 51 | t = int(input()) 52 | for i in range(t): 53 | string = input() 54 | print(infix_to_postfix(string)) 55 | 56 | 57 | if __name__ == "__main__": 58 | unittest.main() 59 | -------------------------------------------------------------------------------- /StackAndQueues/max_rectangular_area_histogram.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def max_histogram_area(arr): 5 | stack = [] 6 | 7 | max_area = 0 8 | 9 | # add dummy value to array to push it all the end 10 | arr.append(0) 11 | 12 | for i in range(len(arr)): 13 | if len(stack) == 0 or arr[stack[-1]] <= arr[i]: 14 | stack.append(i) 15 | continue 16 | 17 | while arr[stack[-1]] > arr[i]: 18 | last = stack.pop() 19 | left_index = stack[-1] if len(stack) > 0 else -1 20 | max_area = max(max_area, (i - left_index - 1) * arr[last]) 21 | 22 | if len(stack) == 0: 23 | break 24 | 25 | stack.append(i) 26 | 27 | return max_area 28 | 29 | 30 | class TestCase(unittest.TestCase): 31 | def test_sample(self): 32 | dataT = [([6, 2, 5, 4, 5, 1, 6], 12), ([6, 3, 4, 2], 9)] 33 | for item in dataT: 34 | result = max_histogram_area(item[0]) 35 | self.assertEqual(result, item[1]) 36 | 37 | 38 | def main(): 39 | t = int(input()) 40 | for _ in range(t): 41 | n = int(input()) 42 | arr = [int(x) for x in input().split()] 43 | print(max_histogram_area(arr)) 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /StackAndQueues/next_larger_element.py: -------------------------------------------------------------------------------- 1 | """ 2 | url : https://practice.geeksforgeeks.org/problems/next-larger-element/0 3 | 4 | Given an array A [ ] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1 5 | 6 | Input: 7 | The first line of input contains a single integer T denoting the number of test cases.Then T test cases follow. Each test case consists of two lines. The first line contains an integer N denoting the size of the array. The Second line of each test case contains N space separated positive integers denoting the values/elements in the array A[ ]. 8 | 9 | Output: 10 | For each test case, print in a new line, the next greater element for each array element separated by space in order. 11 | 12 | Constraints: 13 | 1<=T<=200 14 | 1<=N<=1000 15 | 1<=A[i]<=1000 16 | 17 | Example: 18 | Input 19 | 1 20 | 4 21 | 1 3 2 4 22 | 23 | Output 24 | 3 4 4 -1 25 | 26 | Explanation 27 | In the array, the next larger element to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? since it doesn't exist hence -1. 28 | 29 | """ 30 | 31 | def next_larger_element(arr,n): 32 | stack = [] 33 | result = [-1]*n 34 | for i in range(0,n): 35 | while(len(stack)>0 and arr[stack[-1]]1: 85 | result.append(palin) 86 | 87 | return result 88 | 89 | 90 | def count_palindrome(st): 91 | str1 = st 92 | str2 = st[::-1] 93 | n = len(st) 94 | 95 | matrix = [] 96 | for i in range(n): 97 | matrix.append([0]*n) 98 | longest_common_substring(str1,str2,matrix) 99 | 100 | # print_matrix(matrix,n,n) 101 | result = all_palindromes(matrix,n,st) 102 | 103 | count = 0 104 | for item in set(result): 105 | count+=len(item)//2 106 | 107 | print(count) 108 | 109 | 110 | 111 | def main(): 112 | t = int(input()) 113 | for i in range(t): 114 | n = input() 115 | st = input() 116 | 117 | count_palindrome(st) 118 | 119 | if __name__ == '__main__': 120 | main() -------------------------------------------------------------------------------- /String/divisible_by_8_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/divisible-by-8/0 3 | 4 | Given a number, you need to check whether any permutation of the number is divisible by 8 or not. Print Yes or No. 5 | 6 | Input: 7 | The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of one line. The first line of each test case consists of an integer N. 8 | 9 | Output: 10 | Corresponding to each test case, in a new line, print Yes if divisible by 8, else No. 11 | 12 | Constraints: 13 | 1 ≤ T ≤ 100 14 | 1 ≤ N ≤ 100000 15 | 16 | Example: 17 | 18 | Input 19 | 2 20 | 46 21 | 345 22 | 23 | Output 24 | Yes 25 | 26 | No 27 | 28 | """ 29 | 30 | 31 | -------------------------------------------------------------------------------- /String/form_a_palindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string, find the minimum number of characters to be inserted to convert it to palindrome. 4 | For Example: 5 | ab: Number of insertions required is 1. bab or aba 6 | aa: Number of insertions required is 0. aa 7 | abcd: Number of insertions required is 3. dcbabcd 8 | 9 | Input: 10 | 11 | The first line of input contains an integer T denoting the number of test cases. 12 | The first line of each test case is S. 13 | 14 | Output: 15 | 16 | Print the minimum number of characters. 17 | 18 | Constraints: 19 | 20 | 1 ≤ T ≤ 50 21 | 1 ≤ S ≤ 40 22 | 23 | Example: 24 | 25 | Input: 26 | 3 27 | abcd 28 | aba 29 | geeks 30 | 31 | Output: 32 | 3 33 | 0 34 | 3 35 | 36 | """ 37 | 38 | def form_a_palindrome(string,s,e,matrix): 39 | 40 | if e digits[break_idx]: 22 | digits[i], digits[break_idx] = digits[break_idx], digits[i] 23 | break 24 | 25 | return int( 26 | "".join( 27 | [ 28 | str(digit) 29 | for digit in digits[: break_idx + 1] + sorted(digits[break_idx + 1 :]) 30 | ] 31 | ) 32 | ) 33 | 34 | 35 | class TestCase(unittest.TestCase): 36 | def test_largest_number(self): 37 | dataT = [ 38 | (1234, 1243), 39 | (4321, 0), 40 | (10001, 10010), 41 | (218765, 251678), 42 | (534976, 536479), 43 | ] 44 | 45 | for number, expected in dataT: 46 | result = immediate_largest_number(number) 47 | self.assertEqual(result, expected) 48 | 49 | 50 | if __name__ == "__main__": 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /String/implement_atoi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it. 3 | 4 | Input: 5 | The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains a string str . 6 | 7 | Output: 8 | For each test case in a new line output will be an integer denoting the converted integer, if the input string is not a numerical string then output will be -1. 9 | 10 | Constraints: 11 | 1<=T<=100 12 | 1<=length of (s,x)<=10 13 | 14 | Example(To be used only for expected output) : 15 | Input: 16 | 2 17 | 123 18 | 21a 19 | 20 | Output: 21 | 123 22 | -1 23 | """ 24 | def atoi(string): 25 | number = 0 26 | flag = 1 27 | for i in string: 28 | if i == '-': 29 | flag = -1 30 | continue 31 | 32 | t = ord(i)-ord('0') 33 | if t>9: 34 | return -1 35 | number = number*10 + t 36 | return number * flag -------------------------------------------------------------------------------- /String/implement_strstr.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task is to implement the function strstr. The function takes two strings as arguments(s,x) and locates the occurrence of the string x in the string s. The function returns and integer denoting the first occurrence of the string x . 3 | 4 | Input: 5 | The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of each test case contains two strings str and target. 6 | 7 | Output: 8 | For each test case in a new line output will be an integer denoting the first occurrence of the target string in the string s. Return -1 if no match found. 9 | 10 | Constraints: 11 | 1<=T<=100 12 | 1<=length of (s,x)<=1000 13 | 14 | Example: 15 | Input 16 | 2 17 | GeeksForGeeks Fr 18 | GeeksForGeeks For 19 | Output 20 | -1 21 | 5 22 | 23 | """ 24 | 25 | def strstr(str, substr): 26 | # code here 27 | 28 | for i in range(0,len(str)): 29 | j = 0 30 | k = i 31 | while(j0 and stack[-1] == '{': 46 | stack.pop() 47 | else: 48 | print("not balanced") 49 | return 50 | elif item == ')': 51 | if len(stack)>0 and stack[-1] == '(': 52 | stack.pop() 53 | else: 54 | print("not balanced") 55 | return 56 | elif item == ']': 57 | if len(stack)>0 and stack[-1] == '[': 58 | stack.pop() 59 | else: 60 | print("not balanced") 61 | return 62 | else: 63 | print("not balanced") 64 | return 65 | if len(stack) == 0: 66 | print("balanced") 67 | else: 68 | print("not balanced") 69 | 70 | t = int(input()) 71 | 72 | for i in range(0,t): 73 | string = input() 74 | parenthesis_checker(string) -------------------------------------------------------------------------------- /String/permutations_of_a_given_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, print all permutations of a given string. 3 | 4 | Input: 5 | The first line of input contains an integer T, denoting the number of test cases. 6 | Each test case contains a single string S in capital letter. 7 | 8 | Output: 9 | For each test case, print all permutations of a given string S with single space and all permutations should be in lexicographically increasing order. 10 | 11 | Constraints: 12 | 1 ≤ T ≤ 10 13 | 1 ≤ size of string ≤ 5 14 | 15 | Example: 16 | Input: 17 | 2 18 | ABC 19 | ABSG 20 | Output: 21 | ABC ACB BAC BCA CAB CBA 22 | ABGS ABSG AGBS AGSB ASBG ASGB BAGS BASG BGAS BGSA BSAG BSGA GABS GASB GBAS GBSA GSAB GSBA SABG SAGB SBAG SBGA SGAB SGBA 23 | 24 | 25 | """ 26 | 27 | def permutations(prefix,string): 28 | if string == "": 29 | print(prefix,end=" ") 30 | return 31 | for i in range(0,len(string)): 32 | permutations(prefix+string[i],string[:i]+string[i+1:]) 33 | 34 | 35 | 36 | t = int(input()) 37 | for i in range(0,t): 38 | string = input() 39 | permutations("","".join(sorted(string))) 40 | print() -------------------------------------------------------------------------------- /String/rearrange_character.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/rearrange-characters/0 3 | 4 | Given a string with repeated characters, task is to rearrange characters in a string such that no two adjacent characters are same. 5 | 6 | Note : It may be assumed that the string has only lowercase English alphabets. 7 | 8 | 9 | Input: 10 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a single line containing a string of lowercase english alphabets. 11 | 12 | Output: 13 | For each test case in a new line print 1 if the generated sting doesn't contains any same adjacent characters, else if no such string is possible to be made print 0. 14 | Constraints: 15 | 1<=T<=100 16 | 1<=length of string<=600 17 | 18 | Example: 19 | Input: 20 | 3 21 | geeksforgeeks 22 | bbbabaaacd 23 | bbbbb 24 | 25 | Output: 26 | 1 27 | 1 28 | 0 29 | 30 | """ 31 | 32 | def rearrange_char(st): 33 | rem = [0]*26 34 | for char in st: 35 | rem[ord(char)-ord('a')]+=1 36 | 37 | max_val = max(rem) 38 | print(rem) 39 | 40 | if max_val >= len(st)//2 + 1: 41 | return 0 42 | return 1 43 | 44 | def main(): 45 | t = int(input()) 46 | for i in range(t): 47 | st = input() 48 | print(rearrange_char(st)) 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /String/recursively_remove_all_adjacent_duplicates.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates. 4 | 5 | 6 | Input: 7 | The first line of input contains an integer T, denoting the no of test cases. Then T test cases follow. Each test case contains a string str. 8 | 9 | Output: 10 | For each test case, print a new line containing the resulting string. 11 | 12 | Constraints: 13 | 1<=T<=100 14 | 1<=Length of string<=50 15 | 16 | Example: 17 | Input: 18 | 2 19 | geeksforgeek 20 | acaaabbbacdddd 21 | 22 | Output: 23 | gksforgk 24 | acac 25 | 26 | """ 27 | 28 | def remove_adjacent_duplicates(string): 29 | 30 | prev = 0 31 | seq = [] 32 | 33 | for i in range(1,len(string)): 34 | if string[prev] == string[i]: 35 | continue 36 | else: 37 | if prev != i-1: 38 | seq.append((prev,i)) 39 | prev = i 40 | 41 | if prev != len(string)-1: 42 | seq.append((prev,len(string))) 43 | 44 | result = "" 45 | 46 | start = 0 47 | for item in seq: 48 | result = result + string[start:item[0]] 49 | start = item[1] 50 | result = result + string[start:len(string)] 51 | 52 | if result == string: 53 | return string 54 | else: 55 | return remove_adjacent_duplicates(result) 56 | 57 | t = int(input()) 58 | 59 | for i in range(0,t): 60 | string = input() 61 | print(remove_adjacent_duplicates(string)) -------------------------------------------------------------------------------- /String/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def remove_duplicates(string): 4 | map = {} 5 | for c in string: 6 | map[c] = 1 7 | 8 | result = "" 9 | 10 | for c in string: 11 | if map[c] == 1: 12 | result = result + c 13 | map[c] = 0 14 | print(result) 15 | 16 | 17 | 18 | t = int(input()) 19 | 20 | for i in range(0,t): 21 | string = input() 22 | remove_duplicates(string) -------------------------------------------------------------------------------- /String/reverse_words_in_a_given_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a String of length N reverse the words in it. Words are separated by dots. 3 | 4 | Input: 5 | The first line contains T denoting the number of testcases. Then follows description of testcases. Each case contains a string containing spaces and characters. 6 | 7 | 8 | Output: 9 | For each test case, output a single line containing the reversed String. 10 | 11 | Constraints: 12 | 1<=T<=20 13 | 1<=Lenght of String<=2000 14 | 15 | 16 | Example: 17 | Input: 18 | 2 19 | i.like.this.program.very.much 20 | pqr.mno 21 | 22 | Output: 23 | much.very.program.this.like.i 24 | mno.pqr 25 | """ 26 | 27 | 28 | def reverse_words(string): 29 | str_arr = string.split(".") 30 | print(".".join(str_arr[::-1])) 31 | 32 | t = int(input()) 33 | 34 | for i in range(0,t): 35 | string = input() 36 | reverse_words(string) -------------------------------------------------------------------------------- /String/roll_chars.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/roll-the-characters-of-a-string/0 3 | 4 | We are given a string s and an array roll where roll[i] represents rolling first roll[i] characters in string. We need to apply every roll[i] on string and output final string. Rolling means increasing ASCII value of character, like rolling ‘z’ would result in ‘a’, rolling ‘b’ would result in ‘c’, etc. 5 | 6 | Input : s = "bca" 7 | roll[] = {1, 2, 3} 8 | Output : eeb 9 | 10 | Explanation : 11 | arr[0] = 1 means roll first character of string -> cca 12 | arr[1] = 2 means roll first two characters of string -> dda 13 | arr[2] = 3 means roll first three characters of string -> eeb 14 | So final ans is "eeb" 15 | Input: 16 | First line consist of T test cases. First line of every test case consists of N. Second and third line consists of String and Array of N size, respectively. 17 | 18 | Output: 19 | Single line output, print the modified String. 20 | 21 | Constraints: 22 | 1<=T<=100 23 | 1<=N<=1000 24 | 25 | Example: 26 | Input: 27 | 1 28 | 3 29 | bca 30 | 1 2 3 31 | Output: 32 | eeb 33 | 34 | """ 35 | 36 | 37 | 38 | 39 | def roll_string(string,rolls): 40 | rotated = [0]*len(string) 41 | for item in rolls: 42 | rotated[item-1]+=1 43 | for j in range(len(rotated)-2,-1,-1): 44 | rotated[j] = rotated[j+1]+rotated[j] 45 | 46 | for j in range(0,len(string)): 47 | string = string[:j]+chr(ord('a')+(ord(string[j])-ord('a')+rotated[j])%26)+string[j+1:] 48 | print(string) 49 | 50 | def main(): 51 | t = int(input()) 52 | for i in range(t): 53 | n = int(input()) 54 | string = input() 55 | arr = list(map(int,input().split())) 56 | roll_string(string,arr) 57 | 58 | if __name__ == '__main__': 59 | main() 60 | -------------------------------------------------------------------------------- /String/sum_string_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/sum-string/0 3 | 4 | Given a string of digits, the task is to check if it is a ‘sum-string’. A string S is called a sum-string if a rightmost substring can be written as sum of two substrings before it and same is recursively true for substrings before it. 5 | 6 | Input: 7 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a string S as input. 8 | 9 | Output: 10 | For each test case, print "1", if the string is sum-string else print "0". 11 | 12 | 13 | Constraints: 14 | 1<=T<=100 15 | 1<=S<=105 16 | 17 | Example: 18 | Input: 19 | 3 20 | 12243660 21 | 1111112223 22 | 2368 23 | 24 | Output: 25 | 1 26 | 1 27 | 0 28 | 29 | Explanation: 30 | 31 | In 1st test case 32 | "12243660" is a sum string. 33 | As we can get, 24 + 36 = 60 & 12 + 24 = 36 34 | In 2nd test case 35 | "1111112223" is a sum string. 36 | As we can get, 111+112 = 223 & 1+111 = 112 37 | 38 | """ 39 | 40 | def Int(s): 41 | if len(s) == 0: 42 | return 0 43 | return int(s) 44 | 45 | def isvalidString(string,st): 46 | 47 | if string == '': 48 | return True 49 | 50 | n = len(st) 51 | if st != string[:n]: 52 | return False 53 | 54 | new_string = string[n:] 55 | 56 | for i in range(0,len(new_string)): 57 | if isvalidString(new_string[i+1:],str(Int(st)+Int(new_string[:i]))): 58 | return True 59 | 60 | return False 61 | 62 | if __name__ == '__main__': 63 | st = "1111112223" 64 | print(isvalidString(st,'')) 65 | 66 | 67 | -------------------------------------------------------------------------------- /String/transform_string_X.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://practice.geeksforgeeks.org/problems/transform-string/0 3 | 4 | You are provided two strings A and B. You have to transform string A into string B in minimum number of steps. Only one operation is allowed, chose any of the characters in string A and place it in the front of A. If its not possible to transform string A into string B then print -1 otherwise print the minimum number of steps required. 5 | 6 | Note: All the characters in the string are lowercase English characters. 7 | 8 | Input : 9 | 10 | The first line contains integer T, denoting number of test cases. Then T test cases follow . 11 | The first line of each test case contains two space separated strings A and B. 12 | 13 | Output: 14 | Print in a new line the answer of each test case . 15 | 16 | Constraints : 17 | 18 | 1<=T<=100 19 | 20 | 1<=|A|,|B|<=10^5 21 | 22 | Example: 23 | Input: 24 | 2 25 | bcad abcd 26 | abdd dbad 27 | 28 | Output : 29 | 1 30 | 2 31 | 32 | """ 33 | # longest common subsequence 34 | def lcs(s1,s2,m,n): 35 | if m<0 or n<0: 36 | return 0 37 | if s1[l] == s2[r]: 38 | return 1 + lcs(s1,s2,m-1, n-1) 39 | else: 40 | return max(lcs(s1,s2,m-1,n),lcs(s1,s2,m,n-1)) 41 | 42 | def transfrom_cost(s1,s2): 43 | if sorted(s1) != sorted(s2): 44 | return -1 45 | return len(s1) - lcs(s1,s2,len(s1)-1,len(s2)-1) 46 | 47 | 48 | def main(): 49 | t = int(input()) 50 | for i in range(t): 51 | st1,st2 = list(map(int,input.split())) 52 | print(transfrom_cost(st1,st2)) 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /Tree/count_leaves_in_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, count leaves in it. For example, there are two leaves in below tree 3 | 4 | 1 5 | / \ 6 | 10 39 7 | / 8 | 5 9 | 10 | Input: 11 | The task is to complete the method which takes one argument, root of Binary Tree. The struct Node has a data part which stores the data, pointer to left child and pointer to right child. 12 | There are multiple test cases. For each test case, this method will be called individually. 13 | 14 | Output: 15 | The function should return count of leaves 16 | 17 | Constraints: 18 | 1 <=T<= 30 19 | 1 <=Number of nodes<= 100 20 | 1 <=Data of a node<= 1000 21 | 22 | Example: 23 | Input: 24 | 2 25 | 2 26 | 1 2 R 1 3 L 27 | 4 28 | 10 20 L 10 30 R 20 40 L 20 60 R 29 | 30 | Output: 31 | 2 32 | 3 33 | 34 | """ 35 | #Initial Template for Python 3 36 | class Node: 37 | def __init__(self, val): 38 | self.right = None 39 | self.data = val 40 | self.left = None 41 | 42 | 43 | ''' Please note that it's Function problem i.e. 44 | you need to write your solution in the form of Function(s) only. 45 | Driver Code to call/invoke your function is mentioned above. ''' 46 | 47 | #User function Template for python3 48 | ''' 49 | class Node: 50 | def __init__(self, val): 51 | self.right = None 52 | self.data = val 53 | self.left = None 54 | ''' 55 | # your task is to complete this function 56 | # function should return the count of Leaf node's 57 | # Note: You required to print a new line after every test case 58 | def countLeaves(root): 59 | if root == None: 60 | return 0 61 | # Code here 62 | if root.left == None and root.right == None: 63 | return 1 64 | return countLeaves(root.left) + countLeaves(root.right) 65 | 66 | # Driver Program 67 | if __name__=='__main__': 68 | 69 | root = None 70 | t = int(input()) 71 | for i in range(t): 72 | n = int(input()) 73 | arr = input().strip().split() 74 | if n ==0: 75 | print(0) 76 | continue 77 | dictTree = dict() 78 | 79 | for j in range(n): 80 | if arr[3*j] not in dictTree: 81 | dictTree[arr[3*j]] = Node(arr[3*j]) 82 | parent = dictTree[arr[3*j]] 83 | if j is 0: 84 | root = parent 85 | 86 | else: 87 | parent = dictTree[arr[3*j]] 88 | 89 | child = Node(arr[3*j+1]) 90 | if (arr[3*j+2] == 'L'): 91 | parent.left = child 92 | else: 93 | parent.right = child 94 | dictTree[arr[3*j+1]] = child 95 | 96 | print(countLeaves(root)) -------------------------------------------------------------------------------- /Tree/create_tree_from_traversals.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.left = None 8 | self.right = None 9 | 10 | 11 | def construct_tree(inorder, preorder): 12 | if len(preorder) == 0: 13 | return None 14 | 15 | data = preorder[0] 16 | indexOfInorder = inorder.index(data) 17 | node = Node(data) 18 | node.left = construct_tree( 19 | inorder[:indexOfInorder], preorder[1 : indexOfInorder + 1] 20 | ) 21 | 22 | node.right = construct_tree( 23 | inorder[indexOfInorder + 1 :], preorder[indexOfInorder + 1 :] 24 | ) 25 | 26 | return node 27 | 28 | 29 | def print_preorder(tree): 30 | if not tree: 31 | return 32 | 33 | print(tree.data, end=" ") 34 | 35 | print_preorder(tree.left) 36 | print_preorder(tree.right) 37 | 38 | 39 | class TestCase(unittest.TestCase): 40 | def test_sample(self): 41 | inOrder = ["D", "B", "E", "A", "F", "C"] 42 | preOrder = ["A", "B", "D", "E", "C", "F"] 43 | 44 | result = construct_tree(inOrder, preOrder) 45 | 46 | print_preorder(result) 47 | print("") 48 | 49 | 50 | if __name__ == "__main__": 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /Tree/diagonal_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a Binary Tree, print the diagnol traversal of the binary tree. 3 | 4 | Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line. 5 | 6 | Input : Root of below tree 7 | unnamed 8 | 9 | Output : 10 | Diagonal Traversal of binary tree : 11 | 8 10 14 3 6 7 13 1 4 12 | 13 | Input: 14 | The task is to complete the method which takes 1 argument, root of Binary Tree. The struct Node has a data part which stores the data, pointer to left child and pointer to right child. 15 | There are multiple test cases. For each test case, this method will be called individually. 16 | 17 | Output: 18 | The function should print out the diagonal traversal of the binary tree. 19 | 20 | Constraints: 21 | 1 <=T<= 30 22 | 1 <= Number of nodes<= 100 23 | 1 <= Data of a node<= 1000 24 | 25 | Example: 26 | 27 | Input 28 | 2 29 | 2 30 | 1 2 R 1 3 L 31 | 4 32 | 10 20 L 10 30 R 20 40 L 20 60 R 33 | 34 | Output 35 | 1 2 3 36 | 10 30 20 60 40 37 | 38 | There are two test casess. First case represents a tree with 3 nodes and 2 edges where root is 1, left child of 1 is 3 and right child of 1 is 2. Second test case represents a tree with 4 edges and 5 nodes. 39 | 40 | """ 41 | 42 | 43 | if __name__ == '__main__': 44 | main() 45 | -------------------------------------------------------------------------------- /Tree/is_preorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Preorder Traversal and BST 3 | Given an array, write a program that prints 1 if given array can represent preorder traversal of a BST, else prints 0. 4 | 5 | Input: 6 | The first line of input contains an integer T denoting the number of test cases. 7 | The first line of each test case is N,N is the size of array. 8 | The second line of each test case contains N input A[i]. 9 | 10 | Output: 11 | Should print 1 if given array can represent preorder traversal of BST. Otherwise 0. 12 | 13 | Constraints: 14 | 1 <=T<= 55 15 | 1 <= N <= 1000 16 | 1 <= arr[i] <= 1000 17 | 18 | Example: 19 | 20 | Input: 21 | 3 22 | 5 23 | 40 30 35 80 100 24 | 8 25 | 40 30 32 35 80 90 100 120 26 | 8 27 | 7 9 6 1 4 2 3 40 28 | 29 | Output: 30 | 1 31 | 1 32 | 0 33 | 34 | """ 35 | 36 | def is_preorder_traversal(arr): 37 | if len(arr) == 0: 38 | return True 39 | 40 | pivot = arr[0] 41 | 42 | i = 1 43 | split_index = len(arr) 44 | while(i pivot: 46 | split_index = i 47 | break 48 | i = i + 1 49 | 50 | while(i pivot: 39 | break 40 | i = i + 1 41 | print_leafs(arr[1:i]) 42 | print_leafs(arr[i:]) 43 | 44 | def main(): 45 | t = int(input()) 46 | for i in range(t): 47 | n = int(input()) 48 | arr = list(map(int,input().split())) 49 | print_leafs(arr) 50 | print() 51 | 52 | if __name__ == '__main__': 53 | main() 54 | 55 | # 45 56 | # 61 8 48 767 675 465 323 95 91 212 156 201 210 240 265 261 270 401 393 388 425 558 556 502 478 598 563 587 646 621 754 689 686 696 713 702 757 993 967 870 837 829 925 920 999 57 | # Need Help ? 58 | 59 | # 48 91 210 261 270 388 425 478 587 621 686 702 757 829 920 999 60 | # 48 91 210 261 270 388 425 502 478 587 621 686 702 757 829 925 920 999 61 | 62 | 63 | --------------------------------------------------------------------------------