├── .gitignore ├── LICENSE ├── README.md ├── adhoc_problems ├── circular_list_of_students.cpp ├── interesting_sequences.cpp ├── light_up_the_bulbs.cpp └── winning_strategy.cpp ├── advanced_recursion ├── merge_sort_code.cpp ├── print_keypad_combinations_code.cpp ├── quick_sort_code.cpp ├── remove_duplicates_recursively.cpp ├── replace_character_recursively.cpp └── return_keypad_code.cpp ├── assignment_backtracking_binary_Search_and_merge_sort_problems ├── collecting_the_balls.cpp ├── find_power_of_a_number.cpp ├── sorting_the_skills.cpp └── sudoku_solver.cpp ├── backtracking ├── crossword_problem.cpp ├── n_queens_problem.cpp └── rat_in_a_maze_problem.cpp ├── basics_of_recursion ├── all_indices_of_number.py ├── check_number.py ├── first_index_of_number.py ├── last_index_of_numbers.py ├── number_of_digits.cpp ├── power.py ├── print_number.cpp └── sum_of_array.py ├── bit_manipulation ├── clear_all_bits_from_msb.cpp ├── find_first_set_bit.cpp ├── set_ith_bit.cpp ├── turn_off_1st_set_bit.cpp └── unset_ith_bit.cpp ├── dp_&_bit_masking └── ghost_type.cpp ├── dynamic_programming_1 ├── adjacent_bit_counts.cpp ├── alphacode_question.cpp ├── alyona_and_speadsheet.cpp ├── angry_children.cpp ├── boredom.cpp ├── coin_change_problem.cpp ├── count_bsts.cpp ├── hasan_and_trip.cpp ├── jon_snow_and_his_favourite_number.cpp ├── largest_bitonic_subarray.cpp ├── loot_houses.cpp ├── magic_grid_problem.cpp ├── maximum_square_matrix_with_all_zeros.cpp ├── maximum_sum_rectangle.cpp ├── mimimum_number_of_chocolates.cpp ├── minimum_count.cpp ├── roy_and_coin_boxes.cpp ├── staircase_problem.cpp └── vanya_and_gcd.cpp ├── dynamic_programming_2 ├── balika_vadhu_problem.cpp ├── charlie_and_pilots.cpp ├── distinct_subsequences.cpp ├── edit_distance.cpp ├── knapsack_problem.cpp ├── lcs_problem.cpp ├── miser_man.cpp ├── party_problem.cpp ├── shortest_subsequence.cpp ├── smallest_super_sequence.cpp ├── square_brackets.cpp ├── subset_sum_problem.cpp └── trader_profit.cpp ├── greedy_problems ├── activity_selection.cpp ├── fractional_knapsack.cpp ├── min_absolute_difference_array.cpp ├── nikunj_and_donuts.cpp ├── perimeter_with_condition.cpp ├── problem_discussion.cpp ├── weighted_job_scheduling.cpp └── winning_lottery.cpp ├── language_tools ├── different_names.cpp ├── different_names.py ├── extract_unique_characters.cpp ├── extract_unique_characters.py ├── love_for_characters.py ├── tell_the_positions.cpp ├── tell_the_positions.py ├── warm_reception.cpp └── warm_reception.py ├── language_tools_+_time_and_compexity_assignment ├── duplicate_in_array.py ├── find_the_unique_element.py ├── longest_consecutive_sequence.cpp ├── longest_consecutive_sequence.py ├── pair_sum_to_0.py ├── rotate_array.cpp ├── rotate_array.py ├── sum_me_up.py └── triplet_sum.cpp ├── modulo_arithmetic └── number_of_balanced_bts.cpp ├── prerequisites ├── chakri.py ├── even_and_odd_indexes.cpp ├── even_and_odd_indexes.py ├── pre4.cpp ├── pre4.py ├── target_marbles.cpp ├── target_marbles.py ├── total_sum_on_the_boundaries_and_diagonals.cpp ├── total_sum_on_the_boundaries_and_diagonals.py └── total_sum_on_the_boundaries_and_diagonals_2.cpp └── searching_&_sorting_applications ├── aggressive_cows_problem.cpp ├── distribute_candies.cpp ├── inversion_counts.py ├── momo_market.cpp ├── murder.py └── taj_mahal_entry.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Don't track content of these folders 2 | /.vscode/ 3 | # Compiled source # 4 | *.out -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding-Ninjas-Competitive-Programming 2 | This Repository contains solutions to all the questions I solved during the Competitive programming course with Coding Ninjas. 3 | -------------------------------------------------------------------------------- /adhoc_problems/circular_list_of_students.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a circular list of students as follows: 3 | 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 4 | This list is circular, means that 11 will follow 0 again. You will be given the student number ‘i’ and some position ‘p’. You will have to tell that if the list will start from (i+1)th student, then which student will be at pth position. 5 | Input Format: 6 | First line will have an integer ‘t’, denoting the number of test cases. 7 | Next line will have two space separated integers denoting the value of ‘i’ and ‘p’ respectively. 8 | Output Format: 9 | Print ‘t’ lines containing single integer denoting the student number. 10 | Constraints: 11 | 1 <= t <= 10^5 12 | 0 <= i <= 11 13 | 1 <= p <= 12 14 | Sample Input: 15 | 2 16 | 2 3 17 | 5 8 18 | Sample Output: 19 | 5 20 | 1 21 | Explanation: 22 | First, list will start at 3. 3 -> 4 -> 5. Hence, 5 will be at third position. 23 | Second, list will start at 6. 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 0 -> 1. Hence, 1 will be at 8th position. 24 | */ 25 | #include 26 | using namespace std; 27 | int main() 28 | { 29 | int t; 30 | cin >> t; 31 | while(t--){ 32 | int i, p; 33 | cin >> i >> p; 34 | cout << (i + p)%12 << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /adhoc_problems/interesting_sequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Professor Jain has a class full of notorious students. To get anything done from them is a herculean task. Prof Jain wanted to organize a test. He gave this responsibility to Aahad. Aahad did an excellent job of organizing the test. As a reward, the professor gave him an sequence of numbers to play with. But Aahad likes playing with "interesting" sequence of numbers, which are sequences that have equal elements. 3 | Now, the problem is - Prof Jain has a sequence with elements, and that sequence isn't always "interesting”. To ensure sequence has equal elements, Prof Jain has 2 options: 4 | 1) Choose two elements of sequence . DECREASE the first element by 1 and INCREASE the second element by 1. This operation costs 'k' coins. 5 | 2) Choose one element of array and INCREASE it by 1. This operation costs 'l' coins. 6 | What’s the minimum number of coins Prof Jain needs to turn his sequence into a “interesting" sequence for Aahad? 7 | Input Format 8 | The first line of input contains three space-separated integers: n, k, l . Integer n is the size of array . Integer k is the number of coins needed to perform the first operation. Integer l is the number of coins needed to perform the second operation. 9 | 10 | The second line contains n integers: (a1, a2, a3... an) representing sequence. 11 | Constraints: 12 | 1 <= n, k, l <= 1000 13 | 1 <= ai <= 1000 14 | Time Limit: 1 second 15 | Output Format 16 | In single line, print one integer number: the minimum number of coins required to make "interesting" sequence. 17 | Sample Test Cases: 18 | Sample Input 1: 19 | 4 1 2 20 | 3 4 2 2 21 | Sample Output 1: 22 | 3 23 | Explanation Output 1 : 24 | The professor has a sequence with 4 elements. To perform the first operation, they must pay 1 coin and to perform the second operation, they must pay 2 coins. The optimal strategy is: 25 | 26 | -Perform the second operation on the fourth element. Now the sequence is {3, 4, 2, 3}. This costs 2 coins. 27 | 28 | -Perform the first operation on the second and third element. The sequence is now "interesting", and it looks like {3, 3, 3, 3}. This costs 1 coin. 29 | 30 | The total amount of coins needed is 2 + 1 = 3. 31 | Sample Input 2: 32 | 3 2 1 33 | 5 5 5 34 | Sample Output 2: 35 | 0 36 | Explanation Output 2 : 37 | The given sequence is already "interesting". The professor would spend 0 coins. 38 | Sample Input 3: 39 | 5 2 1 40 | 1 2 3 4 5 41 | Sample Output 3: 42 | 6 43 | Explanation Output 3 : 44 | The professor has a sequence with 5 elements. To perform the first operation, they must pay 2 coin and to perform the second operation, they must pay 1 coin. The optimal strategy is: 45 | 46 | -Perform the first operation on the first and last element. Now the sequence is {2, 2, 3, 4, 4}. This costs 2 coins. 47 | 48 | -Perform the first operation again on the first and last element. Now the sequence is {3, 2, 3, 4, 3}. This costs 2 coins. 49 | 50 | -Perform the first operation on the second and second last element. Now the sequence is {3, 3, 3, 3, 3}. This costs 2 coins. 51 | 52 | The total amount of coins needed is 2 + 2 + 2 = 6. 53 | */ 54 | #include 55 | using namespace std; 56 | int main() { 57 | 58 | // Write your code here 59 | int n, k, l; 60 | cin >> n >> k >> l; 61 | int arr[n]; 62 | for(int i = 0; i < n; i++){ 63 | cin >> arr[i]; 64 | } 65 | 66 | int cost = INT_MAX; 67 | for(int j = *min_element(arr, arr + n); j <= *max_element(arr, arr + n); j++){ 68 | int inc = 0, dec = 0; 69 | //cout << "h1" << endl; 70 | for(int i = 0; i < n; i++){ 71 | //cout << "h2" << endl; 72 | if(arr[i] > j){ 73 | //cout << "h3" << endl; 74 | dec += (arr[i] - j); 75 | } 76 | else{ 77 | //cout << "h4" << endl; 78 | inc += (j - arr[i]); 79 | } 80 | } 81 | 82 | //cout << inc << " " << dec << endl; 83 | long cost1; 84 | if(inc >= dec){ 85 | cost1 = ((inc - dec) * l) + dec * k; 86 | //cout << cost1 << endl; 87 | } 88 | if(cost1 < cost){ 89 | cost = cost1; 90 | } 91 | } 92 | //cout << avg1 << " " << inc << " " << dec << endl; 93 | cout << cost; 94 | } -------------------------------------------------------------------------------- /adhoc_problems/light_up_the_bulbs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A bulb can be ‘ON’ or ‘OFF’. Mr. Navdeep got ‘n’ number of bulbs and their status, whether they are ‘ON’ or ‘OFF’. Their status is represented in a string of size ‘n’ consisting of 0’s and 1’s, where ‘0’ represents the bulb is in ‘OFF’ condition and ‘1’ represent the bulb is ‘ON’. Mr. Navdeep has been given the task to light up all the bulbs. 3 | He can perform two operations. 4 | First, chose any segment of bulbs and reverse them means chose any substring and reverse it. E.g. “0 110 001” -> “0 011 001”. Substring (1, 3) is reversed here. This operation will cost him Rs. ‘X’. 5 | Second, chose any segment of bulbs and reverse their present condition. i.e. if the bulb is ‘ON’, make it ‘OFF’ and if it is ‘OFF’, make it ‘ON’. E.g. “0 011 001” -> “0 100 001”. Substring (1, 3) is complemented. This operation will cost him Rs. ‘Y’. 6 | You need to help Mr. Navdeep that how much minimum amount it will require to make all the bulbs lightened. (or make all the characters as ‘1’ in the representation string) 7 | Input Format: 8 | The first line will contain three space separated integers: ‘n’, ‘X’, ‘Y’ denoting the number of bulbs, cost of first operation and cost of second operation respectively. 9 | The second line contains a representation string of length ‘n’ consisting of 0’s and 1’s representing whether the bulb is ‘OFF’ or ‘ON’. 10 | Output Format: 11 | Print a single integer denoting the minimum cost required to light up all the bulbs. 12 | Constraints: 13 | 1 <= n <= 3,00,000 14 | 0 <= X, Y <= 10^9 15 | Time Limit: 1 second 16 | Sample Input: 17 | 5 1 10 18 | 01000 19 | Sample Output: 20 | 11 21 | Explanation: 22 | First, Reverse substring (0, 1): “01000” -> “10000”, COST = 1 23 | Second, Invert substring (1, 4): “10000” -> “11111”, COST = 10 24 | Total cost = 1+10 => 11 25 | */ 26 | #include 27 | using namespace std; 28 | int main() 29 | { 30 | int n; 31 | long x, y; 32 | cin >> n >> x >> y; 33 | long ans = INT_MAX; 34 | string s; 35 | cin >> s; 36 | long count = 0; 37 | 38 | if(s[0] == '0') 39 | count++; 40 | 41 | for(int i=1; i 1 2 3 5 4 -> 1 2 5 3 4 -> 2 1 5 3 4 32 | In the second case, no way to form this specific order 33 | */ 34 | #include 35 | using namespace std; 36 | int main() { 37 | 38 | // Write your code here 39 | int n; 40 | bool possible = true; 41 | int count = 0; 42 | cin >> n; 43 | int arr[n]; 44 | for(int i = 0; i < n; i++){ 45 | cin >> arr[i]; 46 | } 47 | for(int i = n - 1; i >= 0; i--){ 48 | if(arr[i] == i + 1){ 49 | //cout << count << endl; 50 | continue; 51 | } 52 | else if(arr[i - 1] == i + 1 && i - 1 >= 0){ 53 | //cout << count << endl; 54 | swap(arr[i], arr[i - 1]); 55 | count++; 56 | continue; 57 | } 58 | else if(arr[i - 2] == i + 1 && i - 2 >= 0){ 59 | //cout << count << endl; 60 | swap(arr[i], arr[i - 2]); 61 | count++; 62 | continue; 63 | } 64 | else{ 65 | //cout << count << endl; 66 | possible = false; 67 | break; 68 | } 69 | } 70 | if(possible){ 71 | cout << "YES" << endl; 72 | cout << count << endl; 73 | }else{ 74 | cout << "NO" << endl; 75 | } 76 | } -------------------------------------------------------------------------------- /advanced_recursion/merge_sort_code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort an array A using Merge Sort. 3 | Change in the input array itself. So no need to return or print anything. 4 | Input format : 5 | Line 1 : Integer n i.e. Array size 6 | Line 2 : Array elements (separated by space) 7 | Output format : 8 | Array elements in increasing order (separated by space) 9 | Constraints : 10 | 1 <= n <= 10^3 11 | Sample Input 1 : 12 | 6 13 | 2 6 8 5 4 3 14 | Sample Output 1 : 15 | 2 3 4 5 6 8 16 | Sample Input 2 : 17 | 5 18 | 2 1 5 2 3 19 | Sample Output 2 : 20 | 1 2 2 3 5 21 | */ 22 | #include 23 | using namespace std; 24 | void merge(int *arr, int st, int mid, int e){ 25 | int i, j, k, temp[e - st + 1]; 26 | i = st; 27 | j = mid + 1; 28 | k = 0; 29 | while(i <= mid && j <= e){ 30 | if(arr[i] < arr[j]){ 31 | temp[k] = arr[i]; 32 | //cout << "h1" << endl; 33 | i++; 34 | } 35 | else{ 36 | temp[k] = arr[j]; 37 | //cout << "h2" << endl; 38 | j++; 39 | } 40 | k++; 41 | } 42 | 43 | while(i <= mid){ 44 | temp[k] = arr[i]; 45 | //cout << "h3" << endl; 46 | i++; 47 | k++; 48 | } 49 | 50 | while(j <= e){ 51 | temp[k] = arr[j]; 52 | //cout << "h4" << endl; 53 | j++; 54 | k++; 55 | } 56 | 57 | 58 | for(i = st; i <= e; i++){ 59 | arr[i] = temp[i - st]; 60 | } 61 | } 62 | 63 | void mergeSort1(int *arr,int st,int e){ 64 | if(st < e){ 65 | int mid = (st + e)/2; 66 | mergeSort1(arr, st, mid); 67 | mergeSort1(arr, mid + 1, e); 68 | merge(arr, st, mid, e); 69 | } 70 | } 71 | 72 | void mergeSort(int input[], int size){ 73 | // Write your code here 74 | int start = 0, end = size - 1; 75 | mergeSort1(input, start, end); 76 | } 77 | -------------------------------------------------------------------------------- /advanced_recursion/print_keypad_combinations_code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 3 | Note : The order of strings are not important. Just print different strings in new lines. 4 | Input Format : 5 | Integer n 6 | Output Format : 7 | All possible strings in different lines 8 | Constraints : 9 | 1 <= n <= 10^6 10 | Sample Input: 11 | 23 12 | Sample Output: 13 | ad 14 | ae 15 | af 16 | bd 17 | be 18 | bf 19 | cd 20 | ce 21 | cf 22 | */ 23 | #include 24 | #include 25 | using namespace std; 26 | 27 | 28 | void print(int num, string output) 29 | { string s[8] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 30 | 31 | if(num == 0) 32 | { cout< 20 | void removeConsecutiveDuplicates1(char *input, int i){ 21 | int l = strlen(input); 22 | if(input[i] == '\0') 23 | return; 24 | 25 | while(input[i] == input[i + 1]){ 26 | int j; 27 | for(j = i; j < l - 1; j++){ 28 | input[j] = input[j + 1]; 29 | } 30 | input[j] = '\0'; 31 | } 32 | removeConsecutiveDuplicates1(input, i + 1); 33 | } 34 | 35 | void removeConsecutiveDuplicates(char *input) { 36 | /* Don't write main(). 37 | * Don't read input, it is passed as function argument. 38 | * Change in the given string itself. 39 | * No need to return or print anything 40 | * Taking input and printing output is handled automatically. 41 | */ 42 | removeConsecutiveDuplicates1(input, 0); 43 | } -------------------------------------------------------------------------------- /advanced_recursion/replace_character_recursively.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an input string S and two characters c1 and c2, you need to replace every occurrence of character c1 with character c2 in the given string. 3 | Do this recursively. 4 | Input Format : 5 | Line 1 : Input String S 6 | Line 2 : Character c1 and c2 (separated by space) 7 | Output Format : 8 | Updated string 9 | Constraints : 10 | 1 <= Length of String S <= 10^6 11 | Sample Input : 12 | abacd 13 | a x 14 | Sample Output : 15 | xbxcd 16 | */ 17 | #include 18 | void replaceCharacters1(char input[], char c1, char c2, int i){ 19 | int size = strlen(input); 20 | if(i > size){ 21 | //cout << i << size << " khatam" << endl; 22 | return; 23 | } 24 | 25 | if(input[i] == c1){ 26 | input[i] = c2; 27 | //cout << i << " mc"< 26 | using namespace std; 27 | 28 | int keypad(int num, string output[]){ 29 | /* Insert all the possible combinations of the integer number into the output string array. You do not need to 30 | print anything, just return the number of strings inserted into the array. 31 | */ 32 | if(num==0 || num==1) 33 | { 34 | output[0]=""; 35 | return 1; 36 | } 37 | int sos=keypad(num/10,output); 38 | if(num%10==0 || num%10==1) 39 | { 40 | return sos; 41 | } 42 | else if(num%10==2) 43 | { 44 | for(int i=0;i+2*sos<3*sos;i++) 45 | { 46 | output[i+sos]=output[i]+'b'; 47 | output[i+2*sos]=output[i]+'c'; 48 | output[i]=output[i]+'a'; 49 | } 50 | return 3*sos; 51 | } 52 | else if(num%10==3) 53 | { 54 | for(int i=0;i+2*sos<3*sos;i++) 55 | { 56 | output[i+sos]=output[i]+'e'; 57 | output[i+2*sos]=output[i]+'f'; 58 | output[i]=output[i]+'d'; 59 | } 60 | return 3*sos; 61 | } 62 | else if(num%10==4) 63 | { 64 | for(int i=0;i+2*sos<3*sos;i++) 65 | { 66 | output[i+sos]=output[i]+'h'; 67 | output[i+2*sos]=output[i]+'i'; 68 | output[i]=output[i]+'g'; 69 | } 70 | return 3*sos; 71 | } 72 | else if(num%10==5) 73 | { 74 | for(int i=0;i+2*sos<3*sos;i++) 75 | { 76 | output[i+sos]=output[i]+'k'; 77 | output[i+2*sos]=output[i]+'l'; 78 | output[i]=output[i]+'j'; 79 | } 80 | return 3*sos; 81 | } 82 | else if(num%10==6) 83 | { 84 | for(int i=0;i+2*sos<3*sos;i++) 85 | { 86 | output[i+sos]=output[i]+'n'; 87 | output[i+2*sos]=output[i]+'o'; 88 | output[i]=output[i]+'m'; 89 | } 90 | return 3*sos; 91 | } 92 | else if(num%10==7) 93 | { 94 | for(int i=0;i+3*sos<4*sos;i++) 95 | { 96 | output[i+sos]=output[i]+'q'; 97 | output[i+2*sos]=output[i]+'r'; 98 | output[i+3*sos]=output[i]+'s'; 99 | output[i]=output[i]+'p'; 100 | } 101 | return 4*sos; 102 | } 103 | 104 | else if(num%10==8) 105 | { 106 | for(int i=0;i+2*sos<3*sos;i++) 107 | { 108 | output[i+sos]=output[i]+'u'; 109 | output[i+2*sos]=output[i]+'v'; 110 | output[i]=output[i]+'t'; 111 | } 112 | return 3*sos; 113 | } 114 | else if(num%10==9) 115 | { 116 | for(int i=0;i+3*sos<4*sos;i++) 117 | { 118 | output[i+sos]=output[i]+'x'; 119 | output[i+2*sos]=output[i]+'y'; 120 | output[i+3*sos]=output[i]+'z'; 121 | output[i]=output[i]+'w'; 122 | } 123 | return 4*sos; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /assignment_backtracking_binary_Search_and_merge_sort_problems/collecting_the_balls.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are ‘n’ number of balls in a container. Mr. Sharma and Singh want to take balls out from the container. At each step, Mr. Sharma took ‘k’ balls out of the box and Mr. Singh took one-tenth of the remaining balls. Suppose there are 29 balls at the moment and k=4. Then, Mr. Sharma will take 4 balls and Mr. Singh will take 2 balls (29-4 = 25; 25/10 = 2). If there are less than ‘k’ balls remaining at some moment, then Mr. Sharma will take all the balls which will get the container empty. The process will last until the container becomes empty. Your task is to choose minimal ‘k’ for Mr. Sharma such that Mr. Sharma will take at least half of the balls from the container. 3 | Input Format: 4 | The Only line of input contains a single integer ‘n’. 5 | 6 | Output Format: 7 | Print a single integer denoting the minimal value of ‘k’. 8 | Constraints: 9 | 1 <= n <= 10^18 10 | Time Limit: 1 second 11 | Sample Input: 12 | 68 13 | Sample Output: 14 | 3 15 | Explanation: 16 | 68-3 = 65; 65/10 = 6; 65-6 = 59 17 | 59-3 = 56; 56/10 = 5; 56-5 = 51 18 | 51-3 = 48; 48/10 = 4; 48-4 = 44 19 | 44-3 = 41; 41/10 = 4; 41-4 = 37 20 | ….. 21 | ….. 22 | ….. 23 | 6-3 = 3; 3/10 = 0; 3-0 = 3 24 | 3-3 = 0; 0/10 = 0; 0-0 = 0 25 | */ 26 | #include 27 | using namespace std; 28 | bool find(long curr, long k) { 29 | long sum=0,n=curr; 30 | while(n>0) { 31 | long add=min(k,n); 32 | sum+=add; n-=add; n-=(n/10); 33 | } 34 | return 2*sum>=curr; 35 | } 36 | long bsearch(long n) { 37 | long ans=n/2,lo=1,hi=n; 38 | while(lo<=hi) { 39 | long mid=(lo+hi)/2; 40 | if(find(n,mid)) { 41 | ans=mid; 42 | hi=mid-1; 43 | } else { 44 | lo=mid+1; 45 | } 46 | } 47 | return ans; 48 | } 49 | int main() { 50 | long n; 51 | cin>>n; 52 | cout<<(bsearch(n)); 53 | } -------------------------------------------------------------------------------- /assignment_backtracking_binary_Search_and_merge_sort_problems/find_power_of_a_number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer. 3 | Note : For this question, you can assume that 0 raised to the power of 0 is 1 4 | 5 | 6 | Input format : 7 | Two integers x and n (separated by space) 8 | Output Format : 9 | x^n (i.e. x raise to the power n) 10 | Constraints: 11 | 0 <= x <= 8 12 | 0 <= n <= 9 13 | Sample Input 1 : 14 | 3 4 15 | Sample Output 1 : 16 | 81 17 | Sample Input 2 : 18 | 2 5 19 | Sample Output 2 : 20 | 32 21 | */ 22 | #include 23 | using namespace std; 24 | int power(int x, int n){ 25 | if(n == 0){ 26 | return 1; 27 | } 28 | return x * power(x, n - 1); 29 | } 30 | 31 | int main() { 32 | // Write your code here 33 | int x, n; 34 | cin >> x >> n; 35 | cout << power(x, n); 36 | } 37 | -------------------------------------------------------------------------------- /assignment_backtracking_binary_Search_and_merge_sort_problems/sorting_the_skills.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There is a company named James Peterson & Co. The company has ‘n’ employees. The employees have skills from 0 to n-1. All the employees have distinct skills. The manager of James Peterson & Co. wants to sort the employees on the basis of their skills in ascending order. He is only allowed to swap two employees which are adjacent to each other. He is given the skills of employees in an array of size ‘n’. He can swap the skills as long as the absolute difference between their skills is 1. You need to help the manager out and tell whether it is possible to sort the skills of employees or not. 3 | Input Format: 4 | First Line will have an integer ‘t’ denoting the no. of test cases. 5 | First line of each test case contains an integer ‘n’ denoting the no. of employees in the company. 6 | Second line of each test case contains ‘n’ distinct integers in the range [0, n-1]. 7 | Output Format: 8 | For each test case, print “Yes” if it is possible to sort the skills otherwise “No”. 9 | Constraints: 10 | 1 <= t <= 10 11 | 1 <= n <= 10^5 12 | Sample Input: 13 | 2 14 | 4 15 | 1 0 3 2 16 | 3 17 | 2 1 0 18 | Sample Output: 19 | Yes 20 | No 21 | Explanation: 22 | In first T.C., [1, 0, 3, 2] -> [0, 1, 3, 2] -> [0, 1, 2, 3] 23 | In second T.C., [2, 1, 0] -> [1, 2, 0] OR [2, 1, 0] -> [2, 0, 1] So, it is impossible to sort. 24 | */ 25 | #include 26 | using namespace std; 27 | 28 | bool Sorted(int *a, int n){ 29 | for (int i = 1; i < n; i++){ 30 | if (a[i] < a[i - 1]) { 31 | return false; 32 | } 33 | } 34 | return true; 35 | } 36 | 37 | int main() 38 | { 39 | int t; 40 | cin >> t; 41 | while(t--){ 42 | int n; 43 | cin >> n; 44 | int arr[n]; 45 | for(int i = 0; i < n; i++){ 46 | cin >> arr[i]; 47 | } 48 | 49 | for(int i = 0; i < n; i++){ 50 | if(arr[i + 1] == arr[i] - 1){ 51 | swap(arr[i], arr[i + 1]); 52 | } 53 | } 54 | if(Sorted(arr, n)){ 55 | cout << "Yes" << endl; 56 | } 57 | else{ 58 | cout << "No" << endl; 59 | } 60 | } 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /assignment_backtracking_binary_Search_and_merge_sort_problems/sudoku_solver.cpp: -------------------------------------------------------------------------------- 1 | #define UNASSIGNED 0 2 | #define N 9 3 | 4 | 5 | bool FindUnassignedLocation(int grid[N][N], 6 | int &row, int &col); 7 | 8 | 9 | bool isSafe(int grid[N][N], int row, 10 | int col, int num); 11 | 12 | 13 | bool SolveSudoku(int grid[N][N]) 14 | { 15 | int row, col; 16 | 17 | 18 | if (!FindUnassignedLocation(grid, row, col)) 19 | return true; 20 | 21 | for (int num = 1; num <= 9; num++) 22 | { 23 | 24 | if (isSafe(grid, row, col, num)) 25 | { 26 | 27 | grid[row][col] = num; 28 | 29 | 30 | if (SolveSudoku(grid)) 31 | return true; 32 | 33 | 34 | grid[row][col] = UNASSIGNED; 35 | } 36 | } 37 | return false; 38 | } 39 | 40 | 41 | bool FindUnassignedLocation(int grid[N][N], 42 | int &row, int &col) 43 | { 44 | for (row = 0; row < N; row++) 45 | for (col = 0; col < N; col++) 46 | if (grid[row][col] == UNASSIGNED) 47 | return true; 48 | return false; 49 | } 50 | 51 | 52 | /* 53 | Given a 9*9 sudoku board, in which some entries are filled and others are 0 (0 indicates that the cell is empty), you need to find out whether the Sudoku puzzle can be solved or not i.e. return true or false. 54 | Input Format : 55 | 9 Lines where ith line contains ith row elements separated by space 56 | Output Format : 57 | true or false 58 | Sample Input : 59 | 9 0 0 0 2 0 7 5 0 60 | 6 0 0 0 5 0 0 4 0 61 | 0 2 0 4 0 0 0 1 0 62 | 2 0 8 0 0 0 0 0 0 63 | 0 7 0 5 0 9 0 6 0 64 | 0 0 0 0 0 0 4 0 1 65 | 0 1 0 0 0 5 0 8 0 66 | 0 9 0 0 7 0 0 0 4 67 | 0 8 2 0 4 0 0 0 6 68 | Sample Output : 69 | true 70 | */ 71 | bool UsedInRow(int grid[N][N], int row, int num) 72 | { 73 | for (int col = 0; col < N; col++) 74 | if (grid[row][col] == num) 75 | return true; 76 | return false; 77 | } 78 | 79 | 80 | bool UsedInCol(int grid[N][N], int col, int num) 81 | { 82 | for (int row = 0; row < N; row++) 83 | if (grid[row][col] == num) 84 | return true; 85 | return false; 86 | } 87 | 88 | 89 | bool UsedInBox(int grid[N][N], int boxStartRow, 90 | int boxStartCol, int num) 91 | { 92 | for (int row = 0; row < 3; row++) 93 | for (int col = 0; col < 3; col++) 94 | if (grid[row + boxStartRow] 95 | [col + boxStartCol] == num) 96 | return true; 97 | return false; 98 | } 99 | 100 | 101 | bool isSafe(int grid[N][N], int row, 102 | int col, int num) 103 | { 104 | 105 | return !UsedInRow(grid, row, num) && 106 | !UsedInCol(grid, col, num) && 107 | !UsedInBox(grid, row - row % 3 , 108 | col - col % 3, num); 109 | } 110 | bool sudokuSolver(int board[][9]){ 111 | 112 | 113 | if (SolveSudoku(board) == true) 114 | return true; 115 | return false; 116 | 117 | } 118 | -------------------------------------------------------------------------------- /backtracking/crossword_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | CodingNinjas has provided a crossword of 10*10 grid. The grid contains '+' or '-' as its cell values. Now, you are also provided with a word list that needs to placed accurately in the grid. Cells marked with '-' are to be filled with word list. 3 | For example, The following is an example for the input crossword grid and the word list. 4 | +-++++++++ 5 | +-++-+++++ 6 | +-------++ 7 | +-++-+++++ 8 | +-++-+++++ 9 | +-++-+++++ 10 | ++++-+++++ 11 | ++++-+++++ 12 | ++++++++++ 13 | ---------- 14 | CALIFORNIA;NIGERIA;CANADA;TELAVIV 15 | Output for the given input should be: 16 | +C++++++++ 17 | +A++T+++++ 18 | +NIGERIA++ 19 | +A++L+++++ 20 | +D++A+++++ 21 | +A++V+++++ 22 | ++++I+++++ 23 | ++++V+++++ 24 | ++++++++++ 25 | CALIFORNIA 26 | Note: We have provided such test cases that there is only one solution for the given input. 27 | Input format: 28 | The first 10 lines of input contain crossword. Each of 10 lines has a character array of size 10. Input characters are either '+' or '-'. 29 | The next line of input contains the word list, in which each word is separated by ';'. 30 | Output format: 31 | Print the crossword grid, after placing the words of word list in '-' cells. 32 | Sample Test Cases: 33 | Sample Input 1: 34 | +-++++++++ 35 | +-++-+++++ 36 | +-------++ 37 | +-++-+++++ 38 | +-++-+++++ 39 | +-++-+++++ 40 | ++++-+++++ 41 | ++++-+++++ 42 | ++++++++++ 43 | ---------- 44 | CALIFORNIA;NIGERIA;CANADA;TELAVIV 45 | Sample Output 1: 46 | +C++++++++ 47 | +A++T+++++ 48 | +NIGERIA++ 49 | +A++L+++++ 50 | +D++A+++++ 51 | +A++V+++++ 52 | ++++I+++++ 53 | ++++V+++++ 54 | ++++++++++ 55 | CALIFORNIA 56 | */ 57 | #include 58 | using namespace std; 59 | 60 | void printSolution(char cross[][10]) 61 | { 62 | for(int i=0;i<10;i++) { 63 | for(int j=0;j<10;j++) 64 | cout << cross[i][j] << ""; 65 | cout << endl; 66 | } 67 | } 68 | bool isValidVertical(char cross[][10],string s,int row,int col) 69 | { 70 | int i=row; 71 | while((cross[i][col]=='-' || s[i-row]==cross[i][col]) && (i-row) words,int index) 138 | { 139 | if(index==words.size()) 140 | { 141 | printSolution(cross); 142 | return true; 143 | } 144 | for(int i=0;i<10;i++) 145 | { 146 | for(int j=0;j<10;j++) 147 | { 148 | if(cross[i][j]=='-' || cross[i][j]==words[index][0]) 149 | { 150 | if(isValidVertical(cross,words[index],i,j)) 151 | { 152 | int len = words[index].length(); 153 | bool filled[len]; 154 | for(int i=0;i> cross[i][j]; 188 | 189 | string str; 190 | cin >> str; 191 | 192 | 193 | vector words; 194 | int i=0; 195 | while(str[i]!='\0') 196 | { 197 | string a =""; 198 | while(str[i]!='\0' && str[i]!=';') 199 | a+=str[i++]; 200 | i++; 201 | words.push_back(a); 202 | } 203 | 204 | 205 | crossWord(cross,words,0); 206 | 207 | 208 | 209 | 210 | } -------------------------------------------------------------------------------- /backtracking/n_queens_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given N, and for a given N x N chessboard, find a way to place N queens such that no queen can attack any other queen on the chess board. A queen can be killed when it lies in the same row, or same column, or the same diagonal of any of the other queens. You have to print all such configurations. 3 | Input Format : 4 | Line 1 : Integer N 5 | Output Format : 6 | One Line for every board configuration. 7 | Every line will have N*N board elements printed row wise and are separated by space 8 | Note : Don't print anything if there isn't any valid configuration. 9 | Constraints : 10 | 1<=N<=10 11 | Sample Input 1: 12 | 4 13 | Sample Output 1 : 14 | 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 15 | 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 16 | */ 17 | #include 18 | int board[11][11]; 19 | 20 | bool possible(int n, int row, int col){ 21 | for(int i = 0; i <= row - 1; i++){ 22 | if(board[i][col] == 1) 23 | return false; 24 | } 25 | 26 | /*for(int i = 0, j = 0; i <= row - 1 && j <= col - 1; i++, j++){ 27 | if(board[i][j] == 1) 28 | return false; 29 | }*/ 30 | for(int i=row-1,j=col-1;i>=0 && j>=0 ; i--,j--){ 31 | if(board[i][j] ==1){ 32 | return false; 33 | } 34 | } 35 | 36 | /*for(int i = 0, j = n - 1; i <= row - 1 && j >= col + 1; i++, j--){ 37 | if(board[i][j] == 1) 38 | return false; 39 | }*/ 40 | for(int i=row-1,j=col+1;i>=0 && j n - 1 || col > n - 1 || maze[row][col] == 0 || solution[row][col] == 1){ 50 | return; 51 | } 52 | solution[row][col] = 1; 53 | ratmazeHelper(maze, solution, n, row - 1, col); 54 | ratmazeHelper(maze, solution, n, row, col - 1); 55 | ratmazeHelper(maze, solution, n, row + 1, col); 56 | ratmazeHelper(maze, solution, n, row, col + 1); 57 | solution[row][col] = 0; 58 | return; 59 | } 60 | 61 | void ratInAMaze(int maze[][20], int n){ 62 | 63 | /* Don't write main(). 64 | * Don't read input, it is passed as function argument. 65 | * Print output as specified in the question 66 | */ 67 | int solution[20][20]; 68 | for(int i = 0; i < n; i++){ 69 | for(int j = 0; j < n; j++){ 70 | solution[i][j] = 0; 71 | } 72 | } 73 | ratmazeHelper(maze, solution, n, 0, 0); 74 | 75 | } 76 | -------------------------------------------------------------------------------- /basics_of_recursion/all_indices_of_number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). 3 | Do this recursively. Indexing in the array starts from 0. 4 | Input Format : 5 | Line 1 : An Integer N i.e. size of array 6 | Line 2 : N integers which are elements of the array, separated by spaces 7 | Line 3 : Integer x 8 | Output Format : 9 | indexes where x is present in the array (separated by space) 10 | Constraints : 11 | 1 <= N <= 10^3 12 | Sample Input : 13 | 5 14 | 9 8 10 8 8 15 | 8 16 | Sample Output : 17 | 1 3 4 18 | ''' 19 | def firstIndex(arr, n, x): 20 | # Please add your code here 21 | if len(arr) == 0: 22 | return 23 | if arr[0] == x: 24 | print(n, end = ' ') 25 | firstIndex(arr[1:], n + 1, x) 26 | 27 | # Main 28 | from sys import setrecursionlimit 29 | setrecursionlimit(11000) 30 | n=int(input()) 31 | arr=list(int(i) for i in input().strip().split(' ')) 32 | x=int(input()) 33 | firstIndex(arr, 0, x) 34 | -------------------------------------------------------------------------------- /basics_of_recursion/check_number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. 3 | Do this recursively. 4 | Input Format : 5 | Line 1 : An Integer N i.e. size of array 6 | Line 2 : N integers which are elements of the array, separated by spaces 7 | Line 3 : Integer x 8 | Output Format : 9 | 'true' or 'false' 10 | Constraints : 11 | 1 <= N <= 10^3 12 | Sample Input 1 : 13 | 3 14 | 9 8 10 15 | 8 16 | Sample Output 1 : 17 | true 18 | Sample Input 2 : 19 | 3 20 | 9 8 10 21 | 2 22 | Sample Output 2 : 23 | false 24 | ''' 25 | def checkNumber(arr, x): 26 | # Please add your code here 27 | if len(arr) == 0: 28 | return False 29 | if arr[0] == x: 30 | return True 31 | return checkNumber(arr[1:], x) 32 | 33 | # Main 34 | from sys import setrecursionlimit 35 | setrecursionlimit(11000) 36 | n=int(input()) 37 | arr=list(int(i) for i in input().strip().split(' ')) 38 | x=int(input()) 39 | if checkNumber(arr, x): 40 | print('true') 41 | else: 42 | print('false') 43 | -------------------------------------------------------------------------------- /basics_of_recursion/first_index_of_number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. 3 | First index means, the index of first occurrence of x in the input array. 4 | Do this recursively. Indexing in the array starts from 0. 5 | Input Format : 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Line 3 : Integer x 9 | Output Format : 10 | first index or -1 11 | Constraints : 12 | 1 <= N <= 10^3 13 | Sample Input : 14 | 4 15 | 9 8 10 8 16 | 8 17 | Sample Output : 18 | 1 19 | ''' 20 | def firstIndex(arr, x): 21 | # Please add your code here 22 | if len(arr) == 0: 23 | return -1 24 | if arr[0] == x: 25 | return 0 26 | so = firstIndex(arr[1:], x) 27 | if so == -1: 28 | return -1 29 | else: 30 | return so + 1 31 | 32 | # Main 33 | from sys import setrecursionlimit 34 | setrecursionlimit(11000) 35 | n=int(input()) 36 | arr=list(int(i) for i in input().strip().split(' ')) 37 | x=int(input()) 38 | print(firstIndex(arr, x)) 39 | -------------------------------------------------------------------------------- /basics_of_recursion/last_index_of_numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. 3 | Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. 4 | You should start traversing your array from 0, not from (N - 1). 5 | Do this recursively. Indexing in the array starts from 0. 6 | Input Format : 7 | Line 1 : An Integer N i.e. size of array 8 | Line 2 : N integers which are elements of the array, separated by spaces 9 | Line 3 : Integer x 10 | Output Format : 11 | last index or -1 12 | Constraints : 13 | 1 <= N <= 10^3 14 | Sample Input : 15 | 4 16 | 9 8 10 8 17 | 8 18 | Sample Output : 19 | 3 20 | ''' 21 | ## Read input as specified in the question. 22 | ## Print output as specified in the question. 23 | def LastIndex(arr, n, x): 24 | # Please add your code here 25 | if len(arr) == 0: 26 | return -1 27 | if arr[n - 1] == x: 28 | return 0 29 | so = LastIndex(arr[0:n - 1], n - 1 , x) 30 | if so == -1: 31 | return -1 32 | else: 33 | return so + 1 34 | 35 | # Main 36 | from sys import setrecursionlimit 37 | setrecursionlimit(11000) 38 | n=int(input()) 39 | arr=list(int(i) for i in input().strip().split(' ')) 40 | x=int(input()) 41 | if LastIndex(arr, n, x) != -1: 42 | print(n - 1 - LastIndex(arr, n, x)) 43 | else: 44 | print(-1) 45 | -------------------------------------------------------------------------------- /basics_of_recursion/number_of_digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the code to find out and return the number of digits present in a number recursively. But it contains few bugs, that you need to rectify such that all the test cases should pass. 3 | Input Format : 4 | Integer n 5 | Output Format : 6 | Count of digits 7 | Constraints : 8 | 1 <= n <= 10^6 9 | Sample Input 1 : 10 | 156 11 | Sample Output 1 : 12 | 3 13 | Sample Input 2 : 14 | 7 15 | Sample Output 2 : 16 | 1 17 | */ 18 | int count(int n){ 19 | if(n == 0){ 20 | return 0; 21 | } 22 | int smallAns = count(n / 10); 23 | return smallAns + 1; 24 | } -------------------------------------------------------------------------------- /basics_of_recursion/power.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer. 3 | Do this recursively. 4 | Input format : 5 | Two integers x and n (separated by space) 6 | Output Format : 7 | x^n (i.e. x raise to the power n) 8 | Constraints : 9 | 1 <= x <= 30 10 | 0 <= n <= 30 11 | Sample Input 1 : 12 | 3 4 13 | Sample Output 1 : 14 | 81 15 | Sample Input 2 : 16 | 2 5 17 | Sample Output 2 : 18 | 32 19 | ''' 20 | 21 | def power(x, n): 22 | # Please add your code here 23 | if(n == 0): 24 | return 1 25 | return (x*power(x, n - 1)) 26 | 27 | # Main 28 | from sys import setrecursionlimit 29 | setrecursionlimit(11000) 30 | x, n=list(int(i) for i in input().strip().split(' ')) 31 | print(power(x, n)) 32 | -------------------------------------------------------------------------------- /basics_of_recursion/print_number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given is the code to print numbers from 1 to n in increasing order recursively. But it contains few bugs that you need to rectify such that all the test cases pass. 3 | Input Format : 4 | Integer n 5 | Output Format : 6 | Numbers from 1 to n (separated by space) 7 | Constraints : 8 | 1 <= n <= 10000 9 | Sample Input 1 : 10 | 6 11 | Sample Output 1 : 12 | 1 2 3 4 5 6 13 | Sample Input 2 : 14 | 4 15 | Sample Output 2 : 16 | 1 2 3 4 17 | */ 18 | #include 19 | using namespace std; 20 | void print(int n){ 21 | if(n == 1){ 22 | cout << n << " "; 23 | return; 24 | } 25 | print(n - 1); 26 | cout << n << " "; 27 | } -------------------------------------------------------------------------------- /basics_of_recursion/sum_of_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of length N, you need to find and return the sum of all elements of the array. 3 | Do this recursively. 4 | Input Format : 5 | Line 1 : An Integer N i.e. size of array 6 | Line 2 : N integers which are elements of the array, separated by spaces 7 | Output Format : 8 | Sum 9 | Constraints : 10 | 1 <= N <= 10^3 11 | Sample Input 1 : 12 | 3 13 | 9 8 9 14 | Sample Output 1 : 15 | 26 16 | Sample Input 2 : 17 | 3 18 | 4 2 1 19 | Sample Output 2 : 20 | 7 21 | ''' 22 | def sumArray(arr): 23 | # Please add your code here 24 | if(len(arr) == 1): 25 | return arr[0] 26 | return (arr[0] + sumArray(arr[1:])) 27 | 28 | # Main 29 | from sys import setrecursionlimit 30 | setrecursionlimit(11000) 31 | n=int(input()) 32 | arr=list(int(i) for i in input().strip().split(' ')) 33 | print(sumArray(arr)) 34 | -------------------------------------------------------------------------------- /bit_manipulation/clear_all_bits_from_msb.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left) and return the updated N. 3 | Counting of bits starts from 0 from right to left. 4 | Input Format : 5 | Two integers N and i (separated by space) 6 | Output Format : 7 | Updated N 8 | Sample Input 1 : 9 | 15 2 10 | Sample Output 1 : 11 | 3 12 | Sample Output 1 Explanation : 13 | We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st. 14 | Sample Input 2 : 15 | 4 4 16 | Sample Output 2 : 17 | 4 18 | */ 19 | int clearAllBits(int n, int i){ 20 | /* Don't write main(). 21 | * Don't read input, it is passed as function argument. 22 | * Return output and don't print it. 23 | * Taking input and printing output is handled automatically. 24 | */ 25 | int mask = (1 << i) - 1; 26 | return n & mask; 27 | } -------------------------------------------------------------------------------- /bit_manipulation/find_first_set_bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer N. You need to return an integer M, in which only one bit is set which at position of lowest set bit of N (from right to left). 3 | Input Format : 4 | Integer N 5 | Output Format : 6 | Integer M 7 | Sample Input 1 : 8 | 7 9 | Sample Output 1 : 10 | 1 11 | Sample Input 2 : 12 | 12 13 | Sample Output 2 : 14 | 4 15 | */ 16 | #include 17 | #define INT_SIZE 32 18 | int returnFirstSetBit(int n){ 19 | /* Don't write main(). 20 | * Don't read input, it is passed as function argument. 21 | * Return output and don't print it. 22 | * Taking input and printing output is handled automatically. 23 | */ 24 | return (n & (-1 * n)); 25 | } 26 | 27 | -------------------------------------------------------------------------------- /bit_manipulation/set_ith_bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to make ith bit of binary representation of N to 1 and return the updated N. 3 | Counting of bits start from 0 from right to left. 4 | Input Format : 5 | Two integers N and i (separated by space) 6 | Output Format : 7 | Updated N 8 | Sample Input 1 : 9 | 4 1 10 | Sample Output 1 : 11 | 6 12 | Sample Input 2 : 13 | 4 4 14 | Sample Output 2 : 15 | 20 16 | */ 17 | int turnOnIthBit(int n, int i){ 18 | /* Don't write main(). 19 | * Don't read input, it is passed as function argument. 20 | * Return output and don't print it. 21 | * Taking input and printing output is handled automatically. 22 | */ 23 | return ((1 << i) |n); 24 | } 25 | 26 | -------------------------------------------------------------------------------- /bit_manipulation/turn_off_1st_set_bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer Ni. You need to make first set bit of binary representation of N to 0 and return the updated N. 3 | Counting of bits start from 0 from right to left. 4 | Input Format : 5 | Integer N 6 | Output Format : 7 | Updated N 8 | Sample Input 1 : 9 | 4 10 | Sample Output 1 : 11 | 0 12 | Sample Input 2 : 13 | 12 14 | Sample Output 2 : 15 | 8 16 | */ 17 | #include 18 | int turnOffFirstSetBit(int n){ 19 | /* Don't write main(). 20 | * Don't read input, it is passed as function argument. 21 | * Return output and don't print it. 22 | * Taking input and printing output is handled automatically. 23 | */ 24 | int i = log2(n & (-1 * n)); 25 | return (n & ~(1 << i)); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /bit_manipulation/unset_ith_bit.cpp: -------------------------------------------------------------------------------- 1 | /*You are given two integers N and i. You need to make ith bit of binary representation of N to 0 and return the updated N. 2 | Counting of bits start from 0 from right to left. 3 | Input Format : 4 | Two integers N and i (separated by space) 5 | Output Format : 6 | Updated N 7 | Sample Input 1 : 8 | 7 2 9 | Sample Output 1 : 10 | 3 11 | Sample Input 2 : 12 | 12 1 13 | Sample Output 2 : 14 | 12*/ 15 | int turnOffIthBit(int n, int i){ 16 | /* Don't write main(). 17 | * Don't read input, it is passed as function argument. 18 | * Return output and don't print it. 19 | * Taking input and printing output is handled automatically. 20 | */ 21 | //if (i <= 0) return n; 22 | 23 | 24 | return (n & ~(1 << (i))); 25 | } 26 | 27 | -------------------------------------------------------------------------------- /dp_&_bit_masking/ghost_type.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | long long int dp[1 << 20]; 6 | int can[20]; 7 | int main(){ 8 | int n; 9 | cin >> n; 10 | dp[0] = 1; 11 | for (int i = 0; i < n; i++){ 12 | for (int j = 0; j < n; j++){ 13 | if (i == j)continue; 14 | if (((i + 1) & (j + 1)) == j + 1){ 15 | can[i] |= (1 << j); 16 | } 17 | } 18 | } 19 | for (int i = 0; i < (1 << n); i++){ 20 | 21 | for (int j = 0; j < n; j++){ 22 | if ((i >> j) & 1){ 23 | 24 | } 25 | else{ 26 | if ((i&can[j]) == can[j]){ 27 | dp[i | (1 << j)] += dp[i]; 28 | } 29 | } 30 | } 31 | } 32 | cout << dp[(1 << n) - 1]<< endl; 33 | return 0; 34 | } -------------------------------------------------------------------------------- /dynamic_programming_1/adjacent_bit_counts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | For a string of n bits x1,x2,x3,...,Xn the adjacent bit count of the string (AdjBC(x)) is given by 3 | X1*X2 + X2*X3 + X3*X4 + ... + Xn-1 * Xn 4 | which counts the number of times a 1 bit is adjacent to another 1 bit. For example: 5 | AdjBC(011101101) = 3 6 | AdjBC(111101101) = 4 7 | AdjBC(010101010) = 0 8 | Write a program which takes as input integers n and k and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy AdjBC(x) = k. For example, for 5 bit strings, there are 6 ways of getting AdjBC(x) = 2: 9 | 11100, 01110, 00111, 10111, 11101, 11011 10 | Input 11 | The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by a decimal integer (k) giving the desired adjacent bit count. The number of bits (n) will not be greater than 100. 12 | Output 13 | For each data set there is one line of output. It contains the data set number followed by a single space, followed by the number of n-bit strings with adjacent bit count equal to k. As answer can be very large print your answer modulo 10^9+7. 14 | Sample Input 15 | 10 16 | 1 5 2 17 | 2 20 8 18 | 3 30 17 19 | 4 40 24 20 | 5 50 37 21 | 6 60 52 22 | 7 70 59 23 | 8 80 73 24 | 9 90 84 25 | 10 100 90 26 | Sample Output 27 | 1 6 28 | 2 63426 29 | 3 1861225 30 | 4 168212501 31 | 5 44874764 32 | 6 160916 33 | 7 22937308 34 | 8 99167 35 | 9 15476 36 | 10 23076518 37 | */ 38 | #include 39 | #define mod 1000000007 40 | using namespace std; 41 | 42 | long adjBC(int n, int k){ 43 | long dp[n + 1][k + 1][2]; 44 | memset(dp, 0, sizeof(dp)); 45 | dp[1][0][0] = 1; 46 | dp[1][0][1] = 1; 47 | for(int i = 2; i <= n; i++){ 48 | for(int j = 0; j <= k; j++){ 49 | dp[i][j][0] = (dp[i - 1][j][0] % mod+dp[i - 1][j][1] % mod) % mod; 50 | if(j > 0) 51 | dp[i][j][1] += dp[i - 1][j - 1][1] % mod; 52 | dp[i][j][1] += dp[i - 1][j][0] % mod; 53 | } 54 | } 55 | return (dp[n][k][0] + dp[n][k][1]) % mod; 56 | } 57 | 58 | int main() 59 | { 60 | int t; 61 | cin >> t; 62 | while(t--){ 63 | int i, n, k; 64 | cin >> i >> n >> k; 65 | cout << i << " " << adjBC(n, k) << endl; 66 | } 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /dynamic_programming_1/alphacode_question.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages: 3 | Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.” 4 | 5 | Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’ encoded as 25114. You could decode that in many different ways!” 6 | 7 | Alice: “Sure you could, but what words would you get? Other than ‘BEAN’, you’d get ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. I think you would be able to figure out the correct decoding. And why would you send me the word ‘BEAN’ anyway?” 8 | 9 | Bob: “OK, maybe that’s a bad example, but I bet you that if you got a string of length 5000 there would be tons of different decodings and with that many you would find at least two different ones that would make sense.” 10 | 11 | Alice: “How many different decodings?” 12 | 13 | Bob: “Jillions!” 14 | For some reason, Alice is still unconvinced by Bob’s argument, so she requires a program that will determine how many decodings there can be for a given string using her code. 15 | Input 16 | Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of ‘0’ will terminate the input and should not be processed. 17 | Output 18 | For each input set, output the number of possible decodings for the input string. Print your answer taking modulo "10^9+7" 19 | Sample Input: 20 | 25114 21 | 1111111111 22 | 3333333333 23 | 0 24 | Sample Output: 25 | 6 26 | 89 27 | 1 28 | */ 29 | #include 30 | #define mod 1000000007 31 | 32 | using namespace std; 33 | 34 | long long alphaCodesHelper(string s) 35 | { 36 | int n = s.length(); 37 | long long* dp = new long long[n]; 38 | if (s[0] - '0' == 0) 39 | { 40 | delete[] dp; 41 | return 0; 42 | } 43 | else 44 | { 45 | dp[0] = 1; 46 | } 47 | if (s[1] != '0') 48 | { 49 | if (((s[0] - '0') * 10 + (s[1] - '0')) < 27 && s[2] != '0') 50 | { 51 | dp[1] = 2; 52 | } 53 | else 54 | { 55 | dp[1] = 1; 56 | } 57 | } 58 | else 59 | { 60 | if (((s[0] - '0') * 10 + (s[1] - '0')) < 27) 61 | { 62 | dp[1] = 1; 63 | } 64 | else 65 | { 66 | delete[] dp; 67 | return 0; 68 | } 69 | } 70 | for (int i = 2; i < n; i++) 71 | { 72 | if (s[i] != '0') 73 | { 74 | if (s[i - 1] != '0') 75 | { 76 | if (((s[i - 1] - '0') * 10 + (s[i] - '0')) < 27) 77 | { 78 | if(s[i+1]!='0') 79 | { 80 | dp[i] = (dp[i - 1]%mod + dp[i - 2]%mod)%mod; 81 | } 82 | else 83 | { 84 | dp[i] = dp[i - 1]%mod; 85 | } 86 | } 87 | else 88 | { 89 | dp[i] = dp[i - 1]%mod; 90 | } 91 | } 92 | else 93 | { 94 | dp[i] = dp[i - 1]%mod; 95 | } 96 | } 97 | else 98 | { 99 | if (s[i - 1] == '0') 100 | { 101 | delete[] dp; 102 | return 0; 103 | } 104 | else if (((s[i - 1] - '0') * 10 + (s[i] - '0')) < 27) 105 | { 106 | dp[i] = dp[i - 1]; 107 | } 108 | else 109 | { 110 | delete[] dp; 111 | return 0; 112 | } 113 | } 114 | } 115 | long long ans = dp[n - 1]; 116 | /*cout << endl; 117 | for (int i = 0; i < n; i++) 118 | { 119 | cout << i << " : " << dp[i] <<"->" << s[i] << endl; 120 | } 121 | cout << endl;*/ 122 | delete[] dp; 123 | return ans; 124 | } 125 | 126 | void alphaCodes(vector v) 127 | { 128 | for (int i = 0; i < v.size() - 1; i++) 129 | { 130 | cout << alphaCodesHelper(v[i]) % mod << endl; 131 | } 132 | } 133 | 134 | int main() 135 | { 136 | vector v; 137 | string str; 138 | while (str != "0") 139 | { 140 | cin >> str; 141 | v.push_back(str); 142 | } 143 | alphaCodes(v); 144 | return 0; 145 | } 146 | 147 | -------------------------------------------------------------------------------- /dynamic_programming_1/alyona_and_speadsheet.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. 3 | Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai, j ≤ ai + 1, j for all i from 1 to n - 1. 4 | Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai, j ≤ ai + 1, j for all i from l to r - 1 inclusive. 5 | Alyona is too small to deal with this task and asks you to help! 6 | Input 7 | The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table. 8 | 9 | Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai, j (1 ≤ ai, j ≤ 109). 10 | 11 | The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona. 12 | 13 | The i-th of the next k lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n). 14 | Output 15 | Print "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No". 16 | Sample Input 17 | 5 4 18 | 1 2 3 5 19 | 3 1 3 2 20 | 4 5 2 3 21 | 5 5 3 2 22 | 4 4 3 4 23 | 6 24 | 1 1 25 | 2 5 26 | 4 5 27 | 3 5 28 | 1 3 29 | 1 5 30 | Sample Output 31 | Yes 32 | No 33 | Yes 34 | Yes 35 | Yes 36 | No 37 | */ 38 | #include 39 | using namespace std; 40 | int ans[100000]; 41 | 42 | void sortedFrom(int **arr, int n, int m){ 43 | int dp[n][m]; 44 | 45 | for(int i = 0; i < m; i++){ 46 | dp[0][i] = 1; 47 | } 48 | for(int i = 1; i < n; i++){ 49 | for(int j = 0; j < m; j++){ 50 | if(arr[i][j] >= arr[i - 1][j]){ 51 | dp[i][j] = dp[i - 1][j]; 52 | } 53 | else{ 54 | dp[i][j] = i + 1; 55 | } 56 | } 57 | } 58 | for (int i = 0; i < n; i++) { 59 | int minm = dp[i][0]; 60 | 61 | for (int j = 1; j < m; j++) { 62 | if (dp[i][j] < minm) 63 | minm = dp[i][j]; 64 | ans[i] = minm; 65 | } 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | int n, m; 72 | cin >> n >> m; 73 | int **arr = new int*[n]; 74 | for(int i = 0; i < n; i++) 75 | arr[i] = new int[m]; 76 | 77 | for(int i = 0; i < n; i++) 78 | for(int j = 0; j < m; j++) 79 | cin >> arr[i][j]; 80 | 81 | sortedFrom(arr, n, m); 82 | 83 | int t; 84 | cin >> t; 85 | while(t--){ 86 | int s, e; 87 | cin >> s >> e; 88 | if(ans[e - 1] <= s){ 89 | cout << "Yes" << endl; 90 | } 91 | else{ 92 | cout << "No" << endl; 93 | } 94 | } 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /dynamic_programming_1/angry_children.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has N packets of candies and would like to distribute one packet to each of the K children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick K out of N packets such that the unfairness is minimized. 3 | Suppose the K packets have (x1, x2, x3,....xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as 4 | unfairness=0; 5 | for(i=0;i 37 | using namespace std; 38 | 39 | long long minUnfairness(int n, int k, long *arr){ 40 | sort(arr, arr + n); 41 | long long dp[n - k + 1], cost[k]; 42 | cost[0] = 0; 43 | long long sum = arr[0]; 44 | for(int i = 1; i < k; i++){ 45 | cost[i] = cost[i - 1] + i * arr[i] - sum; 46 | sum += arr[i]; 47 | } 48 | dp[0] = cost[k - 1]; 49 | int c = k; 50 | for(int i = 1; i < (n - k + 1); i++){ 51 | sum -= arr[c - k]; 52 | //cout << sum << endl; 53 | //cout << arr[c] << " " << arr[c - k] << endl; 54 | dp[i] = dp[i - 1] - 2 * sum + (k - 1) * (arr[c] + arr[c - k]); 55 | sum += arr[c]; 56 | c++; 57 | //cout << dp[i] << endl; 58 | } 59 | return *min_element(dp, dp + (n - k + 1)); 60 | } 61 | 62 | int main() 63 | { 64 | int n, k; 65 | cin >> n >> k; 66 | long arr[n]; 67 | for(int i = 0; i < n; i++){ 68 | cin >> arr[i]; 69 | } 70 | cout << minUnfairness(n, k, arr) << endl; 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /dynamic_programming_1/boredom.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Gary is bored and wants to play an interesting but tough game . So he figured out a new board game called "destroy the neighbours" . In this game there are N integers on a board. In one move, he can pick any integer x from the board and then all the integers with value x+1 or x-1 gets destroyed .This move will give him x points. 3 | He plays the game until the board becomes empty . But as he want show this game to his friend Steven, he wants to learn techniques to maximise the points to show off . Can you help Gary in finding out the maximum points he receive grab from the game ? 4 | Input Format : 5 | Line 1 : Integer N 6 | Line 2 : A list of N integers 7 | Output Format : 8 | Maximum points Gary can recieve from the Game setup 9 | Constraints : 10 | 1<=N<=10^5 11 | 1<=A[i]<=1000 12 | Sample Input : 13 | 2 14 | 1 2 15 | Sample Output : 16 | 2 17 | */ 18 | #include 19 | using namespace std; 20 | int solve(int n,vectorA){ 21 | /* Don't write main(). 22 | Don't read input, it is passed as function argument. 23 | Return output and don't print it. 24 | Taking input and printing output is handled automatically. 25 | */ 26 | int freq[1000]; 27 | for(int i = 0; i < 1000; i++){ 28 | freq[i] = 0; 29 | for(int j = 0; j < n; j++){ 30 | if(i == A[j]){ 31 | freq[i]++; 32 | } 33 | } 34 | } 35 | //cout << freq[1]; 36 | 37 | int dp[1000]; 38 | dp[0] = 0; 39 | dp[1] = freq[1]; 40 | 41 | for(int i = 2; i < 1000; i++){ 42 | dp[i] = max(dp[i - 2] + i * freq[i], dp[i - 1]); 43 | } 44 | return *max_element(dp, dp + 1000); 45 | } -------------------------------------------------------------------------------- /dynamic_programming_1/coin_change_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}. You need to figure out the total number of ways W, in which you can make change for Value V using coins of denominations D. 3 | Note : Return 0, if change isn't possible. 4 | Input Format 5 | Line 1 : Integer n i.e. total number of denominations 6 | Line 2 : N integers i.e. n denomination values 7 | Line 3 : Value V 8 | Output Format 9 | Line 1 : Number of ways i.e. W 10 | Constraints : 11 | 1<=n<=10 12 | 1<=V<=1000 13 | Sample Input 1 : 14 | 3 15 | 1 2 3 16 | 4 17 | Sample Output 18 | 4 19 | Sample Output Explanation : 20 | Number of ways are - 4 total i.e. (1,1,1,1), (1,1, 2), (1, 3) and (2, 2). 21 | */ 22 | 23 | int coin_change(int n, int* d, int numD, int output[][11]){ 24 | //cout << n << " " << numD << endl; 25 | //cout << output[n][numD] << endl; 26 | if (n == 0) { 27 | return 1; 28 | } 29 | if (n < 0) { 30 | return 0; 31 | } 32 | if (numD == 0) { 33 | return 0; 34 | } 35 | if (output[n][numD] > -1) { 36 | //cout << n << " " << numD << endl; 37 | return output[n][numD]; 38 | } 39 | int first = coin_change(n - d[0], d, numD, output); 40 | int second = coin_change(n, d + 1, numD - 1, output); 41 | output[n][numD] = first + second; 42 | /*for(int i = 0; i < n; i++){ 43 | for(int j = 0; j < numD; j++) 44 | cout << output[i][j] << " "; 45 | cout << endl; 46 | }*/ 47 | return first + second; 48 | } 49 | 50 | int countWaysToMakeChange(int denominations[], int numDenominations, int value){ 51 | 52 | /* Don't write main(). 53 | * Don't read input, it is passed as function argument. 54 | * Return output and don't print it. 55 | * Taking input and printing output is handled automatically. 56 | */ 57 | //cout << value << endl; 58 | int output[value + 1][11]; 59 | for(int i = 0; i < value + 1; i++){ 60 | for(int j = 0; j < numDenominations + 1; j++) 61 | output[i][j] = -1; 62 | } 63 | /*for(int i = 0; i < value + 1; i++){ 64 | for(int j = 0; j < numDenominations + 1; j++) 65 | cout << output[i][j] << " "; 66 | cout << endl; 67 | } 68 | cout << output[value][numDenominations] << endl;*/ 69 | return coin_change(value, denominations, numDenominations, output); 70 | } 71 | -------------------------------------------------------------------------------- /dynamic_programming_1/count_bsts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer N, find and return the count of unique Binary search trees (BSTs) are possible with nodes valued from 1 to N. 3 | Output count can be very large, so return the count modulo 10^9+7. 4 | Input Format : 5 | Integer n 6 | Output Format : 7 | Count of BSTs 8 | Contraints : 9 | 1<= N <=1000 10 | Sample Input 1: 11 | 8 12 | Sample Output 1: 13 | 1430 14 | Sample Input 2: 15 | 3 16 | Sample Output 2: 17 | 5 18 | */ 19 | #define mod 1000000007 20 | int countBST( int n) 21 | { 22 | /* Don't write main(). 23 | * Don't read input, it is passed as function argument. 24 | * Return output and don't print it. 25 | * Taking input and printing output is handled automatically. 26 | */ 27 | // DP to store the number of unique BST with key i 28 | long long dp[n + 1]; 29 | fill_n(dp, n + 1, 0); 30 | 31 | dp[0] = 1; 32 | dp[1] = 1; 33 | 34 | for (int i = 2; i <= n; i++){ 35 | for (int j = 1; j <= i; j++){ 36 | 37 | dp[i] = (dp[i] + ((dp[i - j])%mod * (dp[j - 1])%mod))%mod; 38 | //dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%mod + dp[i - 1])%mod) % mod; 39 | } 40 | } 41 | 42 | return dp[n]; 43 | } -------------------------------------------------------------------------------- /dynamic_programming_1/hasan_and_trip.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Hasan has finally finished his final exams and he decided to go in a trip among cities in Syria. 3 | There are N cities in Syria and they are numbered from 1 to N, each city has coordinates on plane, i-th city is in (Xi, Yi). 4 | Hasan is in first city and he wants to visit some cities by his car in the trip but the final destination should be N-th city and the sequence of cities he will visit should be increasing in index (i.e. if he is in city i he can move to city j if and only if i < j ). 5 | Visiting i-th city will increase Hasan's happiness by Fi units (including first and last cities), also Hasan doesn't like traveling too much, so his happiness will decrease by total distance traveled by him. 6 | Help Hasan by choosing a sequence of cities to visit which maximizes his happiness. 7 | Input format: 8 | First line contain integer N. 9 | Next N lines contains three integers each, i-th line contains coordinates of i-th city Xi, Yi and Fi. 10 | Output format: 11 | Output one number rounded to 6 digits after floating point, the maximum possible happiness Hasan can get. Note: If answer is 2 print 2.000000 12 | Constraints: 13 | 1 <= N <= 3,000 14 | 0 <= Xi, Yi, Fi <= 100,000 15 | Sample Input 16 | 3 17 | 0 0 1 18 | 3 1 1 19 | 6 0 9 20 | Sample Output 21 | 4.675445 22 | */ 23 | #include 24 | using namespace std; 25 | long double x[100001],y[100001],f[100001]; 26 | double dist1(int a,int b) 27 | { 28 | return sqrt(((x[b] - x[a]) * (x[b] - x[a])) + ((y[b] - y[a]) * (y[b] - y[a]))); 29 | } 30 | 31 | long double fun(int n,long double *x,long double *y,long double *f) 32 | { 33 | long double dist,ans=0,temp = 0; 34 | double dp[n]; 35 | for(int i=0;i>n; 55 | for(int i=0;i>x[i]>>y[i]>>f[i]; 58 | } 59 | cout.precision(6); 60 | 61 | cout< 26 | using namespace std; 27 | 28 | int freq[2][1024]; 29 | int main(){ 30 | int n, x, k, i, j, a, ma=0; 31 | cin>>n>>k>>x; 32 | for(i=0;i>a; 34 | ma=max(ma, a); 35 | ma=max(ma, a^x); 36 | freq[0][a]++; 37 | freq[1][a]++; 38 | } 39 | ma=min(ma*2, 1023); 40 | for(i=0;i=0;i--) 62 | if(freq[0][i]>0) 63 | break; 64 | cout<0) 67 | break; 68 | cout< 32 | int longestBitonicSubarray(int *input, int n) { 33 | 34 | /* Don't write main(). 35 | * the input is already passed as function argument. 36 | * Taking input and printing output is handled automatically. 37 | */ 38 | int* output = new int[n]; 39 | output[0] = 1; 40 | for(int i = 1; i < n; i++) { 41 | output[i] = 1; 42 | for (int j = i - 1; j >= 0; j--) { 43 | if (input[j] >= input[i]) { 44 | continue; 45 | } 46 | int possibleAns = output[j] + 1; 47 | if (possibleAns > output[i]) { 48 | output[i] = possibleAns; 49 | } 50 | } 51 | } 52 | 53 | int* out = new int[n]; 54 | out[n - 1] = 1; 55 | for(int i = n - 2; i >= 0; i--){ 56 | out[i] = 1; 57 | for(int j = i + 1; j < n; j++){ 58 | if(input[j] >= input[i]){ 59 | continue; 60 | } 61 | int possibleAns = out[j] + 1; 62 | if (possibleAns > out[i]) { 63 | out[i] = possibleAns; 64 | } 65 | } 66 | } 67 | 68 | for(int i = 0; i < n; i++){ 69 | //std :: cout << output[i] << " " << out[i] << endl; 70 | output[i] += (out[i] - 1); 71 | } 72 | return *max_element(output, output + n); 73 | } 74 | 75 | -------------------------------------------------------------------------------- /dynamic_programming_1/loot_houses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot. 3 | Input Format 4 | Line 1 : An integer N 5 | Line 2 : N spaced integers denoting money in each house 6 | Output Format 7 | Line 1 : Maximum amount of money looted 8 | Input Constraints 9 | 1 <= n <= 10^4 10 | 1 <= A[i] < 10^4 11 | Sample Input : 12 | 6 13 | 5 5 10 100 10 5 14 | Sample Output 1 : 15 | 110 16 | */ 17 | #include 18 | using namespace std; 19 | int maxMoneyLooted(int *arr, int n) 20 | { 21 | //Write your code here 22 | if (n == 1) return arr[0]; 23 | 24 | int prev = arr[0]; 25 | int curr = max(arr[0], arr[1]); 26 | for (int i = 2; i < n; i++) { 27 | int temp = curr; 28 | curr = max(curr, prev + arr[i]); 29 | prev = temp; 30 | } 31 | return max(prev, curr); 32 | } 33 | -------------------------------------------------------------------------------- /dynamic_programming_1/magic_grid_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a magrid S ( a magic grid ) having R rows and C columns. Each cell in this magrid has either a Hungarian horntail dragon that our intrepid hero has to defeat, or a flask of magic potion that his teacher Snape has left for him. A dragon at a cell (i,j) takes away |S[i][j]| strength points from him, and a potion at a cell (i,j) increases Harry's strength by S[i][j]. If his strength drops to 0 or less at any point during his journey, Harry dies, and no magical stone can revive him. 3 | Harry starts from the top-left corner cell (1,1) and the Sorcerer's Stone is in the bottom-right corner cell (R,C). From a cell (i,j), Harry can only move either one cell down or right i.e., to cell (i+1,j) or cell (i,j+1) and he can not move outside the magrid. Harry has used magic before starting his journey to determine which cell contains what, but lacks the basic simple mathematical skill to determine what minimum strength he needs to start with to collect the Sorcerer's Stone. Please help him once again. 4 | Input (STDIN) 5 | The first line contains the number of test cases T. T cases follow. Each test case consists of R C in the first line followed by the description of the grid in R lines, each containing C integers. Rows are numbered 1 to R from top to bottom and columns are numbered 1 to C from left to right. Cells with S[i][j] < 0 contain dragons, others contain magic potions. 6 | Output (STDOUT): 7 | Output T lines, one for each case containing the minimum strength Harry should start with from the cell (1,1) to have a positive strength through out his journey to the cell (R,C). 8 | Constraints: 9 | 1 ≤ T ≤ 5 10 | 11 | 2 ≤ R, C ≤ 500 12 | 13 | -10^3 ≤ S[i][j] ≤ 10^3 14 | 15 | S[1][1] = S[R][C] = 0 16 | Sample Input 17 | 3 18 | 2 3 19 | 0 1 -3 20 | 1 -2 0 21 | 2 2 22 | 0 1 23 | 2 0 24 | 3 4 25 | 0 -2 -3 1 26 | -1 4 0 -2 27 | 1 -2 -3 0 28 | Sample Output 29 | 2 30 | 1 31 | 2 32 | */ 33 | 34 | #include 35 | using namespace std; 36 | 37 | int min_cost2(int** input, int m, int n) { 38 | int **dp = new int*[m]; 39 | for (int i = 0; i < m; i++) { 40 | dp[i] = new int[n]; 41 | } 42 | dp[m - 1][n-1] = 1; 43 | for (int i = m - 2; i >= 0; i--) { 44 | dp[i][n -1] = dp[i + 1][n-1] - input[i][n-1]; 45 | if(dp[i][n-1]<1){ ///as at any point of time we shuld not have negative health 46 | dp[i][n-1]=1; ///see in hint video for more 47 | } 48 | } 49 | 50 | for (int j = n - 2; j >=0; j--) { 51 | dp[m -1][j] = dp[m - 1][j + 1] - input[m-1][j]; 52 | if(dp[m-1][j]<1){ 53 | dp[m-1][j]=1; 54 | } 55 | } 56 | 57 | for (int i = m - 2; i >=0; i--) { 58 | for (int j = n - 2; j >=0 ; j--) { 59 | dp[i][j] = min(dp[i+1][j], dp[i][j + 1]) - input[i][j]; 60 | if(dp[i][j]<1){ 61 | dp[i][j]=1; 62 | } 63 | } 64 | } 65 | return dp[0][0]; 66 | } 67 | 68 | int main() 69 | { 70 | int t; 71 | cin>>t; 72 | int r,c; 73 | for(int i=0;i>r>>c; 75 | int** ans=new int*[r]; 76 | for(int m=0;m>ans[j][k]; 82 | } 83 | } 84 | int op=min_cost2(ans,r,c); 85 | if(op<0){ 86 | cout<<1< 17 | using namespace std; 18 | int findMaxSquareWithAllZeros(int** arr, int row, int col){ 19 | 20 | /* Don't write main(). 21 | * Don't read input, it is passed as function argument. 22 | * Return output and don't print it. 23 | * Taking input and printing output is handled automatically. 24 | */ 25 | int dp[row][col]; 26 | memset(dp, 0, row*col*sizeof(int)); 27 | 28 | for(int i = 0; i < row; i++){ 29 | if(arr[i][0] == 1){ 30 | dp[i][0] = 0; 31 | } 32 | else{ 33 | dp[i][0] = 1; 34 | } 35 | } 36 | 37 | for(int i = 0; i < col; i++){ 38 | if(arr[0][i] == 1){ 39 | dp[0][i] = 0; 40 | } 41 | else{ 42 | dp[0][i] = 1; 43 | } 44 | } 45 | 46 | for(int i = 1; i < row; i++){ 47 | for(int j = 1; j < col; j++){ 48 | if(arr[i][j] == 1){ 49 | dp[i][j] = 0; 50 | } 51 | else{ 52 | dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); 53 | } 54 | } 55 | } 56 | 57 | /*for(int i = 0; i < row; i++){ 58 | for(int j = 0; j < col; j++) 59 | cout << dp[i][j] << " "; 60 | cout << endl; 61 | }*/ 62 | 63 | int maxElement = INT_MIN; 64 | for (int i = 0; i < row; i++) { 65 | for (int j = 0; j < col; j++) { 66 | if (dp[i][j] > maxElement) { 67 | maxElement = dp[i][j]; 68 | } 69 | } 70 | } 71 | return maxElement; 72 | } -------------------------------------------------------------------------------- /dynamic_programming_1/maximum_sum_rectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix. 3 | Input 4 | First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm. 5 | Output 6 | Output a single integer, maximum sum rectangle. 7 | Constraints 8 | 1<=n,m<=100 9 | Sample Input 10 | 4 5 11 | 1 2 -1 -4 -20 12 | -8 -3 4 2 1 13 | 3 8 10 1 3 14 | -4 -1 1 7 -6 15 | Sample Output 16 | 29 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | 23 | int kadane(int* arr, int* start, 24 | int* finish, int n) 25 | { 26 | 27 | int sum = 0, maxSum = INT_MIN, i; 28 | 29 | 30 | *finish = -1; 31 | 32 | int local_start = 0; 33 | 34 | for (i = 0; i < n; ++i) 35 | { 36 | sum += arr[i]; 37 | if (sum < 0) 38 | { 39 | sum = 0; 40 | local_start = i + 1; 41 | } 42 | else if (sum > maxSum) 43 | { 44 | maxSum = sum; 45 | *start = local_start; 46 | *finish = i; 47 | } 48 | } 49 | 50 | 51 | if (*finish != -1) 52 | return maxSum; 53 | 54 | 55 | maxSum = arr[0]; 56 | *start = *finish = 0; 57 | 58 | for (i = 1; i < n; i++) 59 | { 60 | if (arr[i] > maxSum) 61 | { 62 | maxSum = arr[i]; 63 | *start = *finish = i; 64 | } 65 | } 66 | return maxSum; 67 | } 68 | 69 | 70 | void findMaxSum(int **M, int ROW, int COL) 71 | { 72 | int maxSum = INT_MIN, finalLeft, finalRight, 73 | finalTop, finalBottom; 74 | 75 | int left, right, i; 76 | int temp[ROW], sum, start, finish; 77 | 78 | 79 | for (left = 0; left < COL; ++left) 80 | { 81 | 82 | memset(temp, 0, sizeof(temp)); 83 | 84 | for (right = left; right < COL; ++right) 85 | { 86 | 87 | 88 | for (i = 0; i < ROW; ++i) 89 | temp[i] += M[i][right]; 90 | 91 | 92 | sum = kadane(temp, &start, &finish, ROW); 93 | 94 | 95 | if (sum > maxSum) 96 | { 97 | maxSum = sum; 98 | finalLeft = left; 99 | finalRight = right; 100 | finalTop = start; 101 | finalBottom = finish; 102 | } 103 | } 104 | } 105 | 106 | cout << maxSum << endl; 107 | } 108 | 109 | 110 | int main() 111 | { 112 | int ROW, COL; 113 | cin >> ROW >> COL; 114 | int **M = new int*[ROW]; 115 | for(int i = 0; i < ROW; i++) 116 | M[i] = new int[COL]; 117 | for(int i = 0; i < ROW; i++){ 118 | for(int j = 0; j < COL; j++){ 119 | cin >> M[i][j]; 120 | } 121 | } 122 | 123 | findMaxSum(M, ROW, COL); 124 | 125 | return 0; 126 | } -------------------------------------------------------------------------------- /dynamic_programming_1/mimimum_number_of_chocolates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Noor is a teacher. She wants to give some chocolates to the students in her class. All the students sit in a line and each of them has a score according to performance. Noor wants to give at least 1 chocolate to each student. She distributes chocolates to them such that If two students sit next to each other then the one with the higher score must get more chocolates. Noor wants to save money, so she wants to minimise the total number of chocolates. 3 | Note that when two students have equal score they are allowed to have different number of chocolates. 4 | Input Format: 5 | First Line: Integer N, the number of students in Noor’s class. 6 | Second Line: Each of the student's score separated by spaces. 7 | Output Format: 8 | Output a single line containing the minimum number of chocolates Noor must give. 9 | Input Constraints 10 | 1 <= N <= 100000 11 | 1 <= score <= 100000 12 | Sample Input: 13 | 4 14 | 1 4 4 6 15 | sample Output: 16 | 6 17 | Sample Input: 18 | 3 19 | 8 7 5 20 | sample Output: 21 | 6 22 | */ 23 | #include 24 | using namespace std; 25 | int getMin(int *arr, int n){ 26 | /* Don't write main(). 27 | Don't read input, it is passed as function argument. 28 | Return output and don't print it. 29 | Taking input and printing output is handled automatically. 30 | */ 31 | int dp[n]; 32 | dp[0] = 1; 33 | for(int i = 1; i < n; i++){ 34 | if(arr[i] > arr[i - 1]){ 35 | dp[i] = dp[i - 1] + 1; 36 | } 37 | else{ 38 | dp[i] = 1; 39 | } 40 | //cout << dp[i] << endl; 41 | } 42 | 43 | for(int i = n - 2; i >= 0; i--){ 44 | if(arr[i] > arr[i + 1] && dp[i] <= dp[i + 1]){ 45 | dp[i] = dp[i + 1] + 1; 46 | //cout << "a" << endl; 47 | } 48 | //cout << dp[i] << endl; 49 | } 50 | 51 | return accumulate(dp, dp + n, 0); 52 | } 53 | -------------------------------------------------------------------------------- /dynamic_programming_1/minimum_count.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer N, find and return the count of minimum numbers, sum of whose squares is equal to N. 3 | That is, if N is 4, then we can represent it as : {1^2 + 1^2 + 1^2 + 1^2} and {2^2}. Output will be 1, as 1 is the minimum count of numbers required. 4 | Note : x^y represents x raise to the power y. 5 | Input Format : 6 | Integer N 7 | Output Format : 8 | Required minimum count 9 | Constraints : 10 | 1 <= N <= 1000 11 | Sample Input 1 : 12 | 12 13 | Sample Output 1 : 14 | 3 15 | Sample Output 1 Explanation : 16 | 12 can be represented as : 17 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 18 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 2^2 19 | 1^1 + 1^1 + 1^1 + 1^1 + 2^2 + 2^2 20 | 2^2 + 2^2 + 2^2 21 | As we can see, the output should be 3. 22 | Sample Input 2 : 23 | 9 24 | Sample Output 2 : 25 | 1 26 | */ 27 | #include 28 | using namespace std; 29 | int minCount(int n){ 30 | 31 | /* Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Return output and don't print it. 34 | * Taking input and printing output is handled automatically. 35 | */ 36 | int dp[n + 1]; 37 | dp[0] = 0; 38 | dp[1] = 1; 39 | dp[2] = 2; 40 | dp[3] = 3; 41 | 42 | for(int i = 4; i < n + 1; i++){ 43 | dp[i] = i; 44 | for (int x = 1; x <= sqrt(i); x++) { 45 | int temp = x * x; 46 | if (temp > i) 47 | break; 48 | else 49 | dp[i] = min(dp[i], 1 + dp[i - temp]); 50 | } 51 | } 52 | return dp[n]; 53 | } -------------------------------------------------------------------------------- /dynamic_programming_1/roy_and_coin_boxes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Roy has N coin boxes numbered from 1 to N. 3 | Every day he selects two indices [L,R] and adds 1 coin to each coin box starting from L to R (both inclusive). 4 | He does this for M number of days. 5 | 6 | After M days, Roy has a query: How many coin boxes have atleast X coins. 7 | He has Q such queries. 8 | Input 9 | First line contains N - number of coin boxes. 10 | Second line contains M - number of days. Each of the next M lines consists of two space separated integers L and R. Followed by integer Q - number of queries. 11 | Each of next Q lines contain a single integer X.a 12 | Output 13 | For each query output the result in a new line. 14 | Constraints 15 | 1 ≤ N ≤ 1000000 16 | 17 | 1 ≤ M ≤ 1000000 18 | 19 | 1 ≤ L ≤ R ≤ N 20 | 21 | 1 ≤ Q ≤ 1000000 22 | 23 | 1 ≤ X ≤ N 24 | Sample Input 25 | 7 26 | 4 27 | 1 3 28 | 2 5 29 | 1 2 30 | 5 6 31 | 4 32 | 1 33 | 7 34 | 4 35 | 2 36 | Sample Output 37 | 6 38 | 0 39 | 0 40 | 4 41 | */ 42 | #include 43 | using namespace std; 44 | 45 | void NOofCoins(int *ans, int *l, int *r, int n, int m){ 46 | ans[0] = l[0]; 47 | for(int i = 1; i < n; i++){ 48 | ans[i] = l[i] - r[i - 1] + ans[i - 1]; 49 | } 50 | } 51 | 52 | int main(){ 53 | int n, m; 54 | cin >> n >> m; 55 | int l[n], r[n]; 56 | fill(l, l + n, 0); 57 | fill(r, r + n, 0); 58 | for(int i = 0; i < m; i++){ 59 | int st, en; 60 | cin >> st >> en; 61 | l[st - 1]++; 62 | r[en - 1]++; 63 | } 64 | 65 | 66 | int ans[n]; 67 | fill(ans, ans + n, 0); 68 | NOofCoins(ans, l, r, n, m); 69 | /*for(int i = 0; i < n; i++){ 70 | cout << ans[i] << " "; 71 | } 72 | cout << endl;*/ 73 | int arr[n]; 74 | fill(arr, arr + n, 0); 75 | for(int i = 0; i < n; i++){ 76 | arr[ans[i] - 1]++; 77 | } 78 | /*for(int i = 0; i < n; i++){ 79 | cout << arr[i] << " "; 80 | } 81 | cout << endl;*/ 82 | 83 | for(int i = n - 2; i >= 0; i--){ 84 | arr[i] += arr[i + 1]; 85 | } 86 | 87 | 88 | int q; 89 | cin >> q; 90 | 91 | while(q--){ 92 | int x; 93 | cin >> x; 94 | cout << arr[x - 1] << endl; 95 | } 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /dynamic_programming_1/staircase_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | StairCase Problem 3 | Send Feedback 4 | A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return all possible number of ways. 5 | Time complexity of your code should be O(n). 6 | Input format : 7 | Integer n (No. of steps) 8 | Constraints : 9 | n <= 70 10 | Sample Input 1: 11 | 4 12 | Sample Output 1: 13 | 7 14 | */ 15 | 16 | long staircase(int n){ 17 | /* Don't write main(). 18 | * Don't read input, it is passed as function argument. 19 | * Return output and don't print it. 20 | * Taking input and printing output is handled automatically. 21 | */ 22 | long arr[n + 1]; 23 | arr[0] = 1; 24 | arr[1] = 1; 25 | arr[2] = 2; 26 | for(int i = 3; i < n + 1; i++){ 27 | arr[i] = arr[i - 1] + arr[i - 2] +arr[i - 3]; 28 | } 29 | return arr[n]; 30 | } 31 | -------------------------------------------------------------------------------- /dynamic_programming_1/vanya_and_gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /* 3 | Vanya has been studying all day long about sequences and other Complex Mathematical Terms. She thinks she has now become really good at it. So, her friend Vasya decides to test her knowledge and keeps the following challenge it front of her: 4 | Vanya has been given an integer array A of size N. Now, she needs to find the number of increasing sub-sequences of this array with length ≥1 and GCD=1. A sub-sequence of an array is obtained by deleting some (or none) elements and maintaining the relative order of the rest of the elements. As the answer may be large, print it Modulo 109+7 5 | She finds this task really easy, and thinks that you can do it too. Can you? 6 | Input Format: 7 | The first line contains a single integer N denoting size of array A. The next line contains N space separated integers denoting the elements of array A 8 | Output Format: 9 | Print the required answer Modulo 10^9+7 on a single line. 10 | Constraints: 11 | 1≤N≤500 12 | 13 | 1≤A[i]≤100 14 | Sample Input 15 | 3 16 | 1 2 3 17 | Sample Output 18 | 5 19 | */ 20 | #define m 1000000007 21 | using namespace std; 22 | typedef unsigned long long int ll; 23 | int main() 24 | { 25 | int n; 26 | cin >> n; 27 | int* arr = new int[n]; 28 | for (int i = 0; i < n; i++) 29 | { 30 | cin >> arr[i]; 31 | } 32 | ll** dp = new ll* [n]; 33 | for (int i = 0; i < n; i++) 34 | { 35 | dp[i] = new ll[101]; 36 | for (int g = 0; g <= 100; g++) 37 | { 38 | dp[i][g] = 0; 39 | } 40 | } 41 | 42 | dp[0][arr[0]] = 1; 43 | ll sum=dp[0][1]; 44 | for (int i = 1; i < n; i++) 45 | { 46 | for (int k = i - 1; k >= 0; k--) 47 | { 48 | if (arr[i] > arr[k]) 49 | { 50 | for (int g = 1; g <= 100; g++) 51 | { 52 | int new_gcd = __gcd(arr[i], g); 53 | dp[i][new_gcd] =(dp[i][new_gcd]+ dp[k][g])%m; 54 | } 55 | } 56 | } 57 | dp[i][arr[i]]++; 58 | sum=(sum+dp[i][1])%m; 59 | } 60 | cout< 28 | using namespace std; 29 | #define ll long long 30 | ll dp[123][123][123]; 31 | string str1,str2; 32 | ll K; 33 | vector v; 34 | ll N,M; 35 | ll fun(ll idx1,ll idx2,ll remain) 36 | { 37 | if(idx1==N || idx2==M) 38 | { 39 | if(remain>0) 40 | return -1e18; 41 | else 42 | return 0; 43 | } 44 | if(dp[idx1][idx2][remain]!=-1) 45 | return dp[idx1][idx2][remain]; 46 | if(str1[idx1]==str2[idx2]) 47 | { 48 | if(remain>0) 49 | return dp[idx1][idx2][remain]=max(str1[idx1]+fun(idx1+1,idx2+1,remain-1),max(fun(idx1+1,idx2,remain),fun(idx1,idx2+1,remain))); 50 | else 51 | return 0; 52 | } 53 | return dp[idx1][idx2][remain]=max(fun(idx1+1,idx2,remain),fun(idx1,idx2+1,remain)); 54 | } 55 | int main() 56 | { 57 | ll T; 58 | scanf("%lld",&T); 59 | while(T--) 60 | { 61 | v.clear(); 62 | memset(dp,-1,sizeof dp); 63 | cin>>str1>>str2; 64 | N=str1.size(); 65 | M=str2.size(); 66 | scanf("%lld",&K); 67 | printf("%lld\n",max(0LL,fun(0,0,K))); 68 | } 69 | return 0; 70 | } -------------------------------------------------------------------------------- /dynamic_programming_2/charlie_and_pilots.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Charlie acquired airline transport company and to stay in business he needs to lower the expenses by any means possible. There are N pilots working for his company (N is even) and N/2 plane crews needs to be made. A plane crew consists of two pilots - a captain and his assistant. A captain must be older than his assistant. Each pilot has a contract granting him two possible salaries - one as a captain and the other as an assistant. A captain's salary is larger than assistant's for the same pilot. However, it is possible that an assistant has larger salary than his captain. Write a program that will compute the minimal amount of money Charlie needs to give for the pilots' salaries if he decides to spend some time to make the optimal (i.e. the cheapest) arrangement of pilots in crews. 3 | Input 4 | The first line of input contains integer N, 2 ≤ N ≤ 10,000, N is even, the number of pilots working for the Charlie's company. The next N lines of input contain pilots' salaries. The lines are sorted by pilot's age, the salaries of the youngest pilot are given the first. Each of those N lines contains two integers separated by a space character, X i Y, 1 ≤ Y < X ≤ 100,000, a salary as a captain (X) and a salary as an assistant (Y). 5 | Output 6 | The first and only line of output should contain the minimal amount of money Charlie needs to give for the pilots' salaries. 7 | Sample Input 8 | 4 9 | 5000 3000 10 | 6000 2000 11 | 8000 1000 12 | 9000 6000 13 | Sample Output 14 | 19000 15 | */ 16 | #include 17 | #define MAX 10001 18 | using namespace std; 19 | int memo[MAX][MAX/2+2], n, A[2][MAX]; 20 | 21 | int solve(int a, int c, int cur){ 22 | if(memo[cur][a]!=0) 23 | return memo[cur][a]; 24 | if(a==n/2){ 25 | int ans=0, x=cur; 26 | while(x<=n){ 27 | ans+=A[0][x++]; 28 | } 29 | return memo[cur][a]=ans; 30 | } 31 | if(a==c){ 32 | return memo[cur][a]=A[1][cur]+solve(a+1, c, cur+1); 33 | } 34 | else if(a>c){ 35 | return memo[cur][a]=min(A[1][cur]+solve(a+1, c, cur+1), A[0][cur]+solve(a, c+1, cur+1)); 36 | } 37 | else 38 | return 0; 39 | } 40 | 41 | 42 | int main(){ 43 | int i; 44 | cin>>n; 45 | for(i=0;i>A[0][i]; 47 | cin>>A[1][i]; 48 | } 49 | cout< 23 | using namespace std; 24 | const int MAX_CHAR = 256; 25 | long long countSub(string str) 26 | { 27 | long long m=1e9+7; 28 | vector last(MAX_CHAR, -1); 29 | 30 | long long n = str.length(); 31 | 32 | long long dp[n + 1]; 33 | dp[0] = 1; 34 | 35 | for (int i = 1; i <= n; i++) 36 | { 37 | dp[i] = (2%m* (dp[i - 1])%m)%m; 38 | 39 | if (last[str[i - 1]] != -1) 40 | dp[i] = (dp[i]%m - dp[last[str[i - 1]]]%m)%m; 41 | if(dp[i] < 0){ 42 | dp[i] += m; 43 | } 44 | 45 | last[str[i - 1]] = (i - 1); 46 | } 47 | 48 | return dp[n]%m; 49 | } 50 | int main() 51 | { 52 | int t; 53 | cin>>t; 54 | while(t--) 55 | { 56 | string s; 57 | cin>>s; 58 | cout< 23 | using namespace std; 24 | 25 | int min1(int x, int y, int z) 26 | { 27 | return min(min(x, y), z); 28 | } 29 | 30 | int editDistance(string s1, string s2){ 31 | 32 | /* Don't write main(). 33 | * Don't read input, it is passed as function argument. 34 | * Return output and don't print it. 35 | * Taking input and printing output is handled automatically. 36 | */ 37 | int m = s1.length(), n = s2.length(); 38 | int dp[m + 1][n + 1]; 39 | 40 | for(int i = 0; i <= n; i++){ 41 | dp[0][i] = i; 42 | } 43 | 44 | for(int i = 0; i <= m; i++){ 45 | dp[i][0] = i; 46 | } 47 | 48 | for(int i = 1; i <= m; i++){ 49 | for(int j = 1; j <= n; j++){ 50 | if(s1[i - 1] == s2[j - 1]){ 51 | dp[i][j] = dp[i-1][j-1]; 52 | } 53 | 54 | else{ 55 | dp[i][j] = 1 + min1(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]); 56 | } 57 | } 58 | } 59 | 60 | return dp[m][n]; 61 | } 62 | -------------------------------------------------------------------------------- /dynamic_programming_2/knapsack_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A thief robbing a store and can carry a maximal weight of W into his knapsack. There are N items and ith item weigh wi and is of value vi. What is the maximum value V, that thief can take ? 3 | Space complexity should be O(W). 4 | Input Format : 5 | Line 1 : N i.e. number of items 6 | Line 2 : N Integers i.e. weights of items separated by space 7 | Line 3 : N Integers i.e. values of items separated by space 8 | Line 4 : Integer W i.e. maximum weight thief can carry 9 | Output Format : 10 | Line 1 : Maximum value V 11 | Constraints 12 | 1 <= N <= 10^4 13 | 1<= wi <= 100 14 | 1 <= vi <= 100 15 | Sample Input 1 : 16 | 4 17 | 1 2 4 5 18 | 5 4 8 6 19 | 5 20 | Sample Output : 21 | 13 22 | */ 23 | #include 24 | int knapsack(int* weights, int* values, int n, int maxWeight){ 25 | 26 | /* Don't write main(). 27 | * Don't read input, it is passed as function argument. 28 | * Return output and don't print it. 29 | * Taking input and printing output is handled automatically. 30 | */ 31 | int dp[2][maxWeight + 1]; 32 | for(int i = 0; i <= maxWeight; i++){ 33 | dp[0][i] = 0; 34 | } 35 | 36 | int flag = 1; 37 | for(int i = 1; i <= n; i++){ 38 | for(int w = 0; w <= maxWeight; w++){ 39 | dp[flag][w] = dp[flag ^ 1][w]; 40 | if(weights[i - 1] <= w){ 41 | dp[flag][w] = max(dp[flag ^ 1][w], (values[i - 1] + dp[flag ^ 1][w - weights[i - 1]])); 42 | } 43 | } 44 | flag = flag ^ 1; 45 | } 46 | 47 | return dp[flag ^ 1][maxWeight]; 48 | } 49 | -------------------------------------------------------------------------------- /dynamic_programming_2/lcs_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings S1 and S2 with lengths M and N respectively, find the length of the longest common subsequence. 3 | A subsequence of a string S whose length is K, is a string containing characters in same relative order as they are present in S, 4 | but not necessarily contiguous. Subsequences contain all the strings of length varying from 0 to K. 5 | For example, subsequences of string "abc" are -- ""(empty string), a, b, c, ab, bc, ac, abc. 6 | Input Format : 7 | Line 1: String S1 8 | Line 2: String s2 9 | Output Format : 10 | Length of the longest common subsequence. 11 | Constraints : 12 | 1 <= M <= 100 13 | 1 <= N <= 100 14 | 15 | Time Limit: 1 sec 16 | Sample Input 1: 17 | adebc 18 | dcadb 19 | Sample Output 1: 20 | 3 21 | Explanation of Sample Input 1: 22 | "a", "d", "b", "c", "ad", "ab", "db", "dc" and "adb" are present as a subsequence in both the strings in which "adb" has the maximum length. There are no other common subsequence of length greater than 3 and hence the answer. 23 | Sample Input 2: 24 | abcd 25 | acbdef 26 | Sample Output 2: 27 | 3 28 | Explanation of Sample Input 2: 29 | "a", "b", "c", "d", "ab", "ac", "ad", "bd", "cd", "abd" and "acd" are present as a subsequence in both the strings S1 and S2 in which "abd" and "acd" are of the maximum length. There are no other common subsequence of length greater than 3 and hence the answer. 30 | */ 31 | #include 32 | #include 33 | using namespace std; 34 | int lcs(string s, string t){ 35 | int m = s.size(); 36 | int n = t.size(); 37 | int **ans = new int*[m+1]; 38 | for(int i = 0; i <= m; i++) { 39 | ans[i] = new int[n+1]; 40 | } 41 | for(int j = 0; j <= n; j++) { 42 | ans[0][j] = 0; 43 | } 44 | for(int i = 0; i <= m; i++) { 45 | ans[i][0] = 0; 46 | } 47 | for(int i = 1; i <= m; i++) { 48 | for(int j = 1; j <= n; j++) { 49 | if(s[m-i] == t[n-j]) { 50 | ans[i][j] = 1 + ans[i-1][j-1]; 51 | } 52 | else { 53 | ans[i][j] = max(ans[i-1][j], ans[i][j-1]); 54 | } 55 | } 56 | } 57 | return ans[m][n]; 58 | } -------------------------------------------------------------------------------- /dynamic_programming_2/miser_man.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Jack is a wise and miser man. Always tries to save his money. 3 | One day, he wants to go from city A to city B. Between A and B, there are N number of cities(including B and excluding A) and in each city there are M buses numbered from 1 to M. And the fare of each bus is different. Means for all N*M busses, fare (K) may be different or same. Now Jack has to go from city A to city B following these conditions: 4 | 1. At every city, he has to change the bus. 5 | 2. And he can switch to only those buses which have number either equal or 1 less or 1 greater to the previous. 6 | You are to help Jack to go from A to B by spending the minimum amount of money. 7 | N, M, K <= 100. 8 | Input 9 | Line 1: N M 10 | 11 | Line 2: NxM Grid 12 | 13 | Each row lists the fares the M busses to go form the current city to the next city. 14 | Output 15 | Single Line containing the minimum amount of fare that Jack has to give. 16 | Sample Input 17 | 5 5 18 | 1 3 1 2 6 19 | 10 2 5 4 15 20 | 10 9 6 7 1 21 | 2 7 1 5 3 22 | 8 2 6 1 9 23 | Sample Output 24 | 10 25 | */ 26 | #include 27 | using namespace std; 28 | 29 | int main() 30 | { 31 | int n, m; 32 | cin >> n >> m; 33 | int arr[n][m]; 34 | for(int i = 0; i < n; i++) 35 | for(int j = 0; j < m; j++) 36 | cin >> arr[i][j]; 37 | 38 | int dp[n][m]; 39 | for(int i = 0; i < m; i++) 40 | dp[n - 1][i] = arr[n - 1][i]; 41 | 42 | for(int i = n - 2; i >= 0; i--){ 43 | dp[i][0] = arr[i][0] + min(dp[i + 1][0], dp[i + 1][1]); 44 | dp[i][m - 1] = arr[i][m - 1] + min(dp[i + 1][m - 2], dp[i + 1][m - 1]); 45 | for(int j = 1;j < m - 1; j++){ 46 | dp[i][j] = arr[i][j] + min(dp[i + 1][j - 1], min(dp[i + 1][j], dp[i + 1][j + 1])); 47 | } 48 | } 49 | int k = INT_MAX; 50 | for(int i = 0; i < m; i++){ 51 | k = min(k, dp[0][i]); 52 | } 53 | cout << k << endl; 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /dynamic_programming_2/party_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You just received another bill which you cannot pay because you lack the money. 3 | Unfortunately, this is not the first time to happen, and now you decide to investigate the cause of your constant monetary shortness. The reason is quite obvious: the lion's share of your money routinely disappears at the entrance of party localities. 4 | You make up your mind to solve the problem where it arises, namely at the parties themselves. You introduce a limit for your party budget and try to have the most possible fun with regard to this limit. 5 | You inquire beforehand about the entrance fee to each party and estimate how much fun you might have there. The list is readily compiled, but how do you actually pick the parties that give you the most fun and do not exceed your budget? 6 | Write a program which finds this optimal set of parties that offer the most fun. Keep in mind that your budget need not necessarily be reached exactly. Achieve the highest possible fun level, and do not spend more money than is absolutely necessary. 7 | Input 8 | The first line of the input specifies your party budget and the number n of parties. 9 | 10 | The following n lines contain two numbers each. The first number indicates the entrance fee of each party. Parties cost between 5 and 25 francs. The second number indicates the amount of fun of each party, given as an integer number ranging from 0 to 10. 11 | 12 | The budget will not exceed 500 and there will be at most 100 parties. All numbers are separated by a single space. 13 | 14 | There are many test cases. Input ends with 0 0. 15 | Output 16 | For each test case your program must output the sum of the entrance fees and the sum of all fun values of an optimal solution. Both numbers must be separated by a single space. 17 | Sample Input 18 | 50 10 19 | 12 3 20 | 15 8 21 | 16 9 22 | 16 6 23 | 10 2 24 | 21 9 25 | 18 4 26 | 12 4 27 | 17 8 28 | 18 9 29 | 30 | 50 10 31 | 13 8 32 | 19 10 33 | 16 8 34 | 12 9 35 | 10 2 36 | 12 8 37 | 13 5 38 | 15 5 39 | 11 7 40 | 16 2 41 | 42 | 0 0 43 | Sample Output 44 | 49 26 45 | 48 32 46 | */ 47 | #include 48 | using namespace std; 49 | 50 | void knapsack(int* weights, int* values, int n, int maxWeight){ 51 | 52 | /* Don't write main(). 53 | * Don't read input, it is passed as function argument. 54 | * Return output and don't print it. 55 | * Taking input and printing output is handled automatically. 56 | */ 57 | int dp[2][maxWeight + 1]; 58 | for(int i = 0; i <= maxWeight; i++){ 59 | dp[0][i] = 0; 60 | } 61 | 62 | int flag = 1; 63 | int money = 0; 64 | for(int i = 1; i <= n; i++){ 65 | for(int w = 0; w <= maxWeight; w++){ 66 | dp[flag][w] = dp[flag ^ 1][w]; 67 | if(weights[i - 1] <= w){ 68 | dp[flag][w] = max(dp[flag ^ 1][w], (values[i - 1] + dp[flag ^ 1][w - weights[i - 1]])); 69 | } 70 | } 71 | flag = flag ^ 1; 72 | } 73 | int maxfun = dp[flag ^ 1][maxWeight]; 74 | for(int i = 0; i <= maxWeight; i++){ 75 | if(dp[flag ^ 1][i] == maxfun){ 76 | money=i; 77 | break; 78 | } 79 | } 80 | cout << money << " " << dp[flag ^ 1][maxWeight]; 81 | } 82 | 83 | int main() 84 | { 85 | int maxW, n; 86 | while(cin >> maxW){ 87 | cin >> n; 88 | if(n == 0){ 89 | break; 90 | } 91 | int *w = new int[n]; 92 | int *v = new int[n]; 93 | for(int i = 0; i < n; i++){ 94 | cin >> w[i] >> v[i]; 95 | } 96 | knapsack(w, v, n, maxW); 97 | cout << endl; 98 | } 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /dynamic_programming_2/shortest_subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Gary has two string S and V. Now Gary wants to know the length shortest subsequence in S such that it is not a subsequence in V. 3 | Note: input data will be such so there will always be a solution. 4 | Input Format : 5 | Line 1 : String S of length N (1 <= N <= 1000) 6 | Line 2 : String V of length M (1 <= M <= 1000) 7 | Output Format : 8 | Length of shortest subsequence in S such that it is not a subsequence in V 9 | Sample Input : 10 | babab 11 | babba 12 | Sample Output : 13 | 3 14 | */ 15 | #define INF 1e9 16 | int solve(string S,string V) 17 | { 18 | // Write your code here. 19 | int n=S.size(); 20 | int m=V.size(),i,j,prev; 21 | int dp[n+1][m+1],next[n+1][m+1]; 22 | for(int i=0;i-1){ 32 | return dp[len1][len2]; 33 | } 34 | if(str1[0]==str2[0]){ 35 | dp[len1][len2]=1+smallestSuperSequenceh(str1+1,len1-1,str2+1,len2-1,dp); 36 | return dp[len1][len2]; 37 | }else{ 38 | dp[len1][len2]=1+min(smallestSuperSequenceh(str1+1,len1-1,str2,len2,dp),smallestSuperSequenceh(str1,len1,str2+1,len2-1,dp)); 39 | return dp[len1][len2]; 40 | } 41 | } 42 | int smallestSuperSequence(char str1[], int len1, char str2[], int len2) { 43 | /* Don't write main(). 44 | Don't read input, it is passed as function argument. 45 | Return output and don't print it. 46 | Taking input and printing output is handled automatically. 47 | */ 48 | int** dp=new int*[len1+1]; 49 | for(int i=0;i 43 | using namespace std; 44 | int sb(int n_2,int k,int a[],int count,int i,int** dp){ 45 | if(n_2==0&&count==0){ 46 | return 1; 47 | } 48 | if(n_2==0&&count!=0){ 49 | return 0; 50 | } 51 | if(count<0){ 52 | return 0; 53 | } 54 | if(dp[n_2][count]>-1){ 55 | return dp[n_2][count]; 56 | } 57 | if(a[0]==i+1&&k>0){ 58 | dp[n_2][count]=sb(n_2-1,k-1,a+1,count+1,i+1,dp); 59 | return dp[n_2][count]; 60 | }else{ 61 | dp[n_2][count]=sb(n_2-1,k,a,count+1,i+1,dp)+sb(n_2-1,k,a,count-1,i+1,dp); 62 | return dp[n_2][count]; 63 | } 64 | } 65 | int main() 66 | { 67 | int d; 68 | cin>>d; 69 | for(int j=0;j>n>>k; 72 | int a[k]; 73 | for(int i=0;i>a[i]; 75 | } 76 | sort(a,a+k); 77 | int** dp=new int*[2*n+1]; 78 | for(int k=0;k<=2*n;k++){ 79 | dp[k]=new int[2*n+1]; 80 | for(int h=0;h<=2*n;h++){ 81 | dp[k][h]=-1; 82 | } 83 | } 84 | cout< 17 | using namespace std; 18 | 19 | bool SubsetSum(int n, int *arr, int k){ 20 | bool** dp = new bool*[2]; 21 | for(int i = 0; i <= 1; i++){ 22 | dp[i] = new bool[k + 1]; 23 | } 24 | 25 | for(int i = 0; i <= k; i++){ 26 | dp[0][i] = false; 27 | } 28 | dp[0][0] = true; 29 | 30 | int flag = 1; 31 | 32 | for(int i=1; i<=n; i++){ 33 | for(int j=1; j<=k; j++){ 34 | 35 | dp[flag][j] = dp[flag^1][j]; 36 | 37 | if(j >= arr[i-1]){ 38 | dp[flag][j] = dp[flag][j] || dp[flag^1][j - arr[i - 1]]; 39 | } 40 | } 41 | flag = flag ^ 1; 42 | } 43 | bool ans = dp[flag^1][k]; 44 | return ans; 45 | } 46 | 47 | int main() 48 | { 49 | int n; 50 | cin >> n; 51 | int arr[n]; 52 | for(int i = 0; i < n; i++){ 53 | cin >> arr[i]; 54 | } 55 | int k; 56 | cin >> k; 57 | if(SubsetSum(n, arr, k)){ 58 | cout << "Yes" << endl; 59 | } 60 | else{ 61 | cout << "No" << endl; 62 | } 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /dynamic_programming_2/trader_profit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Mike is a stock trader and makes a profit by buying and selling stocks. He buys a stock at a lower price and sells it at a higher price to book a profit. He has come to know the stock prices of a particular stock for n upcoming days in future and wants to calculate the maximum profit by doing the right transactions (single transaction = buying + selling). Can you help him maximize his profit? 3 | Note: A transaction starts after the previous transaction has ended. Two transactions can't overlap or run in parallel. 4 | The stock prices are given in the form of an array A for n days. 5 | Given the stock prices and a positive integer k, find and print the maximum profit Mike can make in at most k transactions. 6 | Input Format 7 | The first line of input contains an integer q denoting the number of queries. 8 | 9 | The first line of each test case contains a positive integer k, denoting the number of transactions. 10 | 11 | The second line of each test case contains a positive integer n, denoting the length of the array A. 12 | 13 | The third line of each test case contains n space-separated positive integers, denoting the prices of each day in the array A. 14 | Constraints 15 | 1<=q<=100 16 | 17 | 0 41 | using namespace std; 42 | 43 | int maxProfit(int price[], int n, int k) 44 | { 45 | int profit[k+1][n+1]; 46 | 47 | for (int i = 0; i <= k; i++) 48 | profit[i][0] = 0; 49 | 50 | for (int j= 0; j <= n; j++) 51 | profit[0][j] = 0; 52 | 53 | for (int i = 1; i <= k; i++) 54 | { 55 | for (int j = 1; j < n; j++) 56 | { 57 | int max_so_far = 0; 58 | 59 | for (int m = 0; m < j; m++) 60 | max_so_far = max(max_so_far, 61 | price[j] - price[m] + profit[i-1][m]); 62 | 63 | profit[i][j] = max(profit[i][j-1], max_so_far); 64 | } 65 | } 66 | 67 | return profit[k][n-1]; 68 | } 69 | 70 | int main() 71 | { 72 | int k,n,t; 73 | 74 | cin>>t; 75 | 76 | for(int j = 0; j < t; j++) 77 | { 78 | cin>>k; 79 | cin>>n; 80 | int price[n]; 81 | 82 | for(int i = 0; i < n; i++) 83 | cin>>price[i]; 84 | 85 | cout<< maxProfit(price, n, k)< 24 | using namespace std; 25 | 26 | bool cmp(pair p1, pair p2){ 27 | if(p1.second!=p2.second) 28 | return p1.second=p2.first; 31 | } 32 | 33 | int main() 34 | { 35 | int n=0; 36 | cin >> n; 37 | vector> v; 38 | for(int i=0; i p; 40 | 41 | cin >> p.first >> p.second; 42 | v.push_back(p); 43 | } 44 | sort(v.begin(), v.end(),cmp); 45 | int ans = 1; 46 | int last = 0; 47 | for(int i=1; i 21 | using namespace std; 22 | 23 | struct Item 24 | { 25 | int time,cost,speed; 26 | }; 27 | 28 | bool compare(Item a,Item b) 29 | { 30 | 31 | if(a.timeb.speed) 38 | {return true;} 39 | else if(a.speed==b.speed) 40 | { 41 | return a.cost>n>>d; 52 | Item arr[n]; 53 | for(int i=0;i>arr[i].time>>arr[i].cost>>arr[i].speed; 56 | } 57 | sort(arr,arr+n,compare); 58 | 59 | 60 | long fcost=arr[0].cost; 61 | long currspeed=arr[0].speed; 62 | long currA=d; 63 | long currT=arr[0].time; 64 | int i=0; 65 | for(i=1;(i0);i++) 66 | { 67 | if(arr[i].speed>currspeed) 68 | { 69 | currA=currA-((arr[i].time-currT)*currspeed); 70 | fcost+=arr[i].cost; 71 | if(currA>0) 72 | { 73 | currT=arr[i].time; 74 | currspeed=arr[i].speed; 75 | } 76 | 77 | } 78 | } 79 | 80 | cout< 20 | using namespace std; 21 | int minAbsoluteDiff(int arr[], int n) { 22 | /* Don't write main(). 23 | * Don't read input, it is passed as function argument. 24 | * Return output and don't print it. 25 | * Taking input and printing output is handled automatically. 26 | */ 27 | sort(arr, arr + n); 28 | int min = INT_MAX; 29 | for(int i = 1; i < n; i++){ 30 | if(arr[i] - arr[i - 1] < min){ 31 | min = arr[i] - arr[i - 1]; 32 | } 33 | } 34 | return min; 35 | } 36 | -------------------------------------------------------------------------------- /greedy_problems/nikunj_and_donuts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Nikunj loves donuts, but he also likes to stay fit. He eats n donuts in one sitting, and each donut has a calorie count, ci. After eating a donut with k calories, he must walk at least 2^j x k(where j is the number donuts he has already eaten) miles to maintain his weight. 3 | Given the individual calorie counts for each of the n donuts, find and print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. Note that he can eat the donuts in any order. 4 | Input 5 | The first line contains an integer, n, denoting the number of donuts. 6 | The second line contains n space-separated integers describing the respective calorie counts of each donut I, i.e ci. 7 | Output 8 | Print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. 9 | Constraints 10 | 1 ≤ n ≤ 40 11 | 1 ≤ ci ≤ 1000 12 | Sample Input 13 | 3 14 | 1 3 2 15 | Sample Output 16 | 11 17 | */ 18 | #include 19 | using namespace std; 20 | int main() 21 | { 22 | //Write your code here 23 | int n; 24 | cin >> n; 25 | int c[n]; 26 | for(int i = 0; i < n; i++) 27 | cin >> c[i]; 28 | 29 | sort(c, c + n); 30 | long mi = 0; 31 | for(int i = 0; i < n; i++) 32 | mi += (pow(2, i))*c[n - i - 1]; 33 | cout << mi << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /greedy_problems/perimeter_with_condition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Aahad gives an array of integers and asks Harshit to find which three elements form a triangle (non-degenerate). The task seems easy to Harshit. 3 | So, Aahad adds some conditions to this task - 4 | 1. Find the triangle with maximum perimeter 5 | 2. If there are two or more combinations with same value of maximum perimeter, then find the one with the longest side. 6 | 3.If there are more than one combinations which satisfy all the above conditions the find with maximum longest minimum side. 7 | Input Format 8 | The First line contains no of elements of array: N 9 | Each T lines contains N space-separated integers: A [i] 10 | Output Format 11 | The output contains three space-separated elements that denote the length of the sides of triangle. If no such triangle is possible, then print -1. 12 | Constraints 13 | 1 =< N <= 10^5 14 | 1 <= A[i] <= 10^9 15 | Time Limit: 1 second 16 | Sample Input1: 17 | 5 18 | 1 1 1 3 3 19 | Sample Output1: 20 | 1 3 3 21 | Sample Input2: 22 | 3 23 | 2 2 4 24 | Sample Output3: 25 | -1 26 | Explaination 27 | In the First Sample case, the elements that form a triangle with maximum perimeter is 1,3,3. 28 | In the Second Sample case, the elements that can form a triangle are degenerate, so, we printed -1. 29 | */ 30 | #include 31 | using namespace std; 32 | int main() { 33 | // Write your code here 34 | int n; 35 | cin>>n; 36 | int arr[n]; 37 | for(int i=0;i>arr[i]; 39 | } 40 | sort(arr,arr+n); 41 | reverse(arr,arr+n); 42 | bool flag = false; 43 | int index = 0; 44 | for(int i=0;iarr[i]){ 46 | flag = true; 47 | index = i; 48 | break; 49 | } 50 | } 51 | if(flag){ 52 | cout< 21 | using namespace std; 22 | 23 | // Modifies the array by subtracting/adding 24 | // k to every element such that the difference 25 | // between maximum and minimum is minimized 26 | int getMinDiff(int arr[], int n, int k) 27 | { 28 | if (n == 1) 29 | return 0; 30 | 31 | // Sort all elements 32 | sort(arr, arr+n); 33 | 34 | // Initialize result 35 | int ans = arr[n-1] - arr[0]; 36 | 37 | // Handle corner elements 38 | int small = arr[0] + k; 39 | int big = arr[n-1] - k; 40 | if (small > big) 41 | swap(small, big); 42 | 43 | // Traverse middle elements 44 | for (int i = 1; i < n-1; i ++) 45 | { 46 | int subtract = arr[i] - k; 47 | int add = arr[i] + k; 48 | 49 | // If both subtraction and addition 50 | // do not change diff 51 | if (subtract >= small || add <= big) 52 | continue; 53 | 54 | // Either subtraction causes a smaller 55 | // number or addition causes a greater 56 | // number. Update small or big using 57 | // greedy approach (If big - subtract 58 | // causes smaller diff, update small 59 | // Else update big) 60 | if (big - subtract <= add - small) 61 | small = subtract; 62 | else 63 | big = add; 64 | } 65 | 66 | return min(ans, big - small); 67 | } 68 | 69 | // Driver function to test the above function 70 | int main() 71 | { 72 | int n,k; 73 | cin>>n>>k; 74 | int arr[n]; 75 | for(int i=0;i>arr[i]; 77 | } 78 | cout< 25 | #include 26 | using namespace std; 27 | 28 | struct Job 29 | { 30 | int start, finish, profit; 31 | }; 32 | 33 | bool myfunction(Job s1, Job s2) 34 | { 35 | return (s1.finish < s2.finish); 36 | } 37 | 38 | 39 | int binarySearch(Job jobs[], int index) 40 | { 41 | 42 | int lo = 0, hi = index - 1; 43 | 44 | while (lo <= hi) 45 | { 46 | int mid = (lo + hi) / 2; 47 | if (jobs[mid].finish <= jobs[index].start) 48 | { 49 | if (jobs[mid + 1].finish <= jobs[index].start) 50 | lo = mid + 1; 51 | else 52 | return mid; 53 | } 54 | else 55 | hi = mid - 1; 56 | } 57 | 58 | return -1; 59 | } 60 | 61 | 62 | int findMaxProfit(Job arr[], int n) 63 | { 64 | 65 | sort(arr, arr+n, myfunction); 66 | 67 | int *table = new int[n]; 68 | table[0] = arr[0].profit; 69 | 70 | 71 | for (int i=1; i> n; 93 | Job arr[n]; 94 | for(int i = 0; i < n; i++) 95 | cin >> arr[i].start >> arr[i].finish >> arr[i].profit; 96 | cout << findMaxProfit(arr, n) << endl; 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /greedy_problems/winning_lottery.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Harshit knows by his resources that this time the winning lottery number is the smallest number whose sum of the digits is S and the number of digits is D. You have to help Harshit and print the winning lottery number. 3 | Input Format 4 | The Input line contains two space-separated integers: S,D 5 | Output Format 6 | The output contains a single integer denoting the winning lottery number 7 | Constraints 8 | 1 <= D <= 1000 9 | 1 <= S <= 9*D 10 | Time Limit: 1 second 11 | Sample Input1: 12 | 9 2 13 | Sample Output1: 14 | 18 15 | Explanation 16 | There are many other possible numbers like 45, 54, 90, etc with the sum of digits as 9 and number of digits as 2. The smallest of them is 18. 17 | */ 18 | #include 19 | using namespace std; 20 | int main() { 21 | // Write your code here 22 | int s,d; 23 | cin>>s>>d; 24 | int arr[d]; 25 | s=s-1; 26 | for(int i=d-1;i>=0;i--){ 27 | if(i==0){ 28 | arr[0]=s+1; 29 | break; 30 | } 31 | if(s>=9){ 32 | arr[i]=9; 33 | s-=9; 34 | }else{ 35 | arr[i]=s; 36 | s=0; 37 | } 38 | } 39 | for(int i=0;i 23 | using namespace std; 24 | 25 | int main( int argc , char ** argv ) 26 | { 27 | string names; 28 | getline(cin, names); 29 | //cout << names << '\n'; 30 | 31 | stringstream iss(names); 32 | 33 | unordered_map m1; 34 | string temp; 35 | 36 | while(iss>>temp){ 37 | m1[temp]++; 38 | } 39 | 40 | unordered_map :: iterator it=m1.begin(); 41 | int count = 0; 42 | for (it; it != m1.end(); ++it) 43 | { 44 | if(it->second>1){ 45 | cout << it->first<<" "<< it->second << '\n'; 46 | count++; 47 | } 48 | } 49 | if (count == 0) 50 | { 51 | cout << -1 << '\n'; 52 | } 53 | 54 | return 0 ; 55 | 56 | 57 | } -------------------------------------------------------------------------------- /language_tools/different_names.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In Little Flowers Public School, there are many students with same first names. You are given a task to find the students with same names. You will be given a string comprising of all the names of students and you have to tell the name and count of those students having same. If all the names are unique, print -1 instead. 3 | Note: We don't have to mention names whose frequency is 1. 4 | Input Format: 5 | The only line of input will have a string ‘str’ with space separated first names of students. 6 | Output Format: 7 | Print the names of students along with their count if they are repeating. If no name is repeating, print -1 8 | Constraints: 9 | 1 <= |str| <= 10^5 10 | Time Limit: 1 second 11 | Sample Input 1: 12 | Abhishek harshit Ayush harshit Ayush Iti Deepak Ayush Iti 13 | Sample Output 1: 14 | harshit 2 15 | Ayush 3 16 | Iti 2 17 | Sample Input 2: 18 | Abhishek Harshit Ayush Iti 19 | Sample Output: 20 | -1 21 | ''' 22 | def differentNames(l): 23 | # Please add your code here 24 | m = {} 25 | for name in l: 26 | if name in m: 27 | m[name] += 1 28 | else: 29 | m[name] = 1 30 | m1 = {key:val for key, val in m.items() if val != 1} 31 | return m1 32 | 33 | # Main 34 | names=input().strip().split() 35 | m=differentNames(names) 36 | if m: 37 | for name in m: 38 | print(name, m[name]) 39 | else: 40 | print(-1) 41 | -------------------------------------------------------------------------------- /language_tools/extract_unique_characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should remain same. 3 | Input format : 4 | String S 5 | Output format : 6 | Output String 7 | Constraints : 8 | 0 <= Length of S <= 10^8 9 | Sample Input 1 : 10 | ababacd 11 | Sample Output 1 : 12 | abcd 13 | Sample Input 2 : 14 | abcde 15 | Sample Output 2 : 16 | abcde 17 | */ 18 | #include 19 | char* uniqueChar(char *s){ 20 | unordered_map m1; 21 | 22 | char *arr=new char [50000]; 23 | int j= 0; 24 | for (int i = 0; i < strlen(s); ++i) 25 | { 26 | m1[s[i]]++; 27 | if (m1[s[i]]==1) 28 | { 29 | arr[j] = s[i]; 30 | j++; 31 | } 32 | 33 | } 34 | arr[j]='\0'; 35 | return arr; 36 | 37 | } -------------------------------------------------------------------------------- /language_tools/extract_unique_characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should remain same. 3 | Input format : 4 | String S 5 | Output format : 6 | Output String 7 | Constraints : 8 | 0 <= Length of S <= 10^8 9 | Sample Input 1 : 10 | ababacd 11 | Sample Output 1 : 12 | abcd 13 | Sample Input 2 : 14 | abcde 15 | Sample Output 2 : 16 | abcde 17 | ''' 18 | def uniqueChars(string): 19 | # Please add your code here 20 | str = string[0] 21 | for i in range(1, len(string)): 22 | bool = False 23 | for c in str: 24 | if string[i] == c: 25 | bool = True 26 | if bool == False: 27 | str += string[i] 28 | return str 29 | 30 | # Main 31 | string = input() 32 | print(uniqueChars(string)) 33 | -------------------------------------------------------------------------------- /language_tools/love_for_characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Ayush loves the characters ‘a’, ‘s’, and ‘p’. He got a string of lowercase letters and he wants to find out how many times characters ‘a’, ‘s’, and ‘p’ occurs in the string respectively. Help him find it out. 3 | Input: 4 | First line contains an integer denoting length of the string. 5 | Next line contains the string. 6 | Constraints: 7 | 1<=n<=10^5 8 | ‘a’<= each character of string <= ‘z’ 9 | Output: 10 | Three space separated integers denoting the occurrence of letters ‘a’, ‘s’ and ‘p’ respectively. 11 | Sample Input: 12 | 6 13 | aabsas 14 | Sample output: 15 | 3 2 0 16 | ''' 17 | n = int(input()) 18 | 19 | str = input() 20 | 21 | ca , cs, cp = 0, 0, 0 22 | for c in str: 23 | if c == 'a': 24 | ca += 1 25 | 26 | elif c == 's': 27 | cs += 1 28 | 29 | elif c == 'p': 30 | cp += 1 31 | 32 | print(ca, end = " ") 33 | print(cs, end = " ") 34 | print(cp, end = " ") -------------------------------------------------------------------------------- /language_tools/tell_the_positions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | In a class there are ‘n’ number of students. They have three different subjects: Data Structures, Algorithm Design & Analysis and Operating Systems. Marks for each subject of all the students are provided to you. You have to tell the position of each student in the class. Print the names of each student according to their position in class. Tie is broken on the basis of their roll numbers. Between two students having same marks, the one with less roll number will have higher rank. The input is provided in order of roll number. 3 | Input Format: 4 | First line will have a single integer ‘n’, denoting the number of students in the class. 5 | Next ‘n’ lines each will have one string denoting the name of student and three space separated integers m1, m2, m3 denoting the marks in three subjects. 6 | Output Format: 7 | Print ‘n’ lines having two values: First, the position of student in the class and second his name. 8 | Constraints: 9 | 1 <= n <= 10^5 10 | 0 <= m1, m2, m3 <= 100 11 | Sample Input: 12 | 3 13 | Mohit 94 85 97 14 | Shubham 93 91 94 15 | Rishabh 95 81 99 16 | Sample Output: 17 | 1 Shubham 18 | 2 Mohit 19 | 3 Rishabh 20 | */ 21 | #include 22 | using namespace std; 23 | typedef pair pi; 24 | bool sortinrev(pair> &a, pair> &b) 25 | { 26 | if(a.second.first != b.second.first){ 27 | return (a.second.first > b.second.first); 28 | } 29 | return (a.first < b.first); 30 | } 31 | int main() 32 | { 33 | int n,m1,m2,m3; 34 | cin>>n; 35 | 36 | vector> mp; 37 | for(int i=0;i>str; 40 | cin>>m1; 41 | cin>>m2; 42 | cin>>m3; 43 | mp.push_back(make_pair(i, make_pair(m1+m2+m3, str))); 44 | } 45 | sort(mp.begin(),mp.end(), sortinrev); 46 | //reverse(mp.begin(),mp.end()); 47 | int i; 48 | for(i = 0;i < n; i++){ 49 | 50 | cout< 23 | using namespace std; 24 | int main() { 25 | 26 | // Write your code here 27 | int n; 28 | cin >> n; 29 | int arr[n], dep[n]; 30 | for(int i = 0; i < n; i++){ 31 | cin >> arr[i]; 32 | } 33 | for(int i = 0; i < n; i++){ 34 | cin >> dep[i]; 35 | } 36 | sort(arr, arr + n); 37 | sort(dep, dep + n); 38 | 39 | int i = 1, j = 0, chairs = 1, ans = 1; 40 | 41 | while(i < n && j < n){ 42 | if(arr[i] <= dep[j]){ 43 | i++; 44 | chairs++; 45 | if(ans < chairs){ 46 | ans = chairs; 47 | } 48 | } 49 | else{ 50 | j++; 51 | chairs--; 52 | } 53 | } 54 | cout << ans; 55 | } -------------------------------------------------------------------------------- /language_tools/warm_reception.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There is only one beauty parlour in the town CodingNinjasLand. The receptionist at the beauty parlor is flooded with appointment requests because the “Hakori” festival is round the corner and everyone wants to look good on it. 3 | She needs your help. The problem is they don’t have chairs in reception. They are ordering chairs from NinjasKart. They don’t want to order more than required. You have to tell the minimum number of chairs required such that none of the customers has to stand. 4 | Input Format : 5 | First line contains the number of customers that will come. Second line contains N space-separated integers which represent the arrival timings of the customer. Third line contains N space-separated integers which represent the departure timings of the customer. Arrival and departure timings are given in 24-hour clock. 6 | Constraints: 7 | 1<= N <= 100 8 | Arrival and departure timings lie in the range [0000 to 2359] 9 | Time Limit: 1 second 10 | Output Format : 11 | You have to print the minimum number of chairs required such that no customer has to wait standing. 12 | Sample Test Cases: 13 | Sample Input 1 : 14 | 5 15 | 900 1000 1100 1030 1600 16 | 1900 1300 1130 1130 1800 17 | Sample Output 1: 18 | 4 19 | Explanation: 20 | 4 because at 1100 hours, we will have maximum number of customers at the shop, throughout the day. And that maximum number is 4. 21 | ''' 22 | #Write your code here 23 | n = int(input()) 24 | arri = [int(x) for x in input().split()] 25 | dep = [int(x) for x in input().split()] 26 | arri.sort() 27 | dep.sort() 28 | chairs = 1 29 | ans = 1 30 | i, j = 1, 0 31 | while (i < n and j < n): 32 | if arri[i] <= dep[j]: 33 | chairs += 1 34 | i += 1 35 | if chairs > ans: 36 | ans = chairs 37 | 38 | else: 39 | chairs -= 1 40 | j += 1 41 | print(ans) 42 | -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/duplicate_in_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers of size n which contains numbers from 0 to n - 2. Each number is present at least once. That is, if n = 5, numbers from 0 to 3 is present in the given array at least once and one number is present twice. You need to find and return that duplicate number present in the array. 3 | Assume, duplicate number is always present in the array. 4 | Input format : 5 | Line 1 : Size of input array 6 | Line 2 : Array elements (separated by space) 7 | Output Format : 8 | Duplicate element 9 | Constraints : 10 | 1 <= n <= 10^6 11 | Sample Input: 12 | 9 13 | 0 7 2 5 4 7 1 3 6 14 | Sample Output: 15 | 7 16 | ''' 17 | def MissingNumber(arr): 18 | # Please add your code here 19 | arr.sort() 20 | if(arr[0] == arr[1]): 21 | return arr[0] 22 | 23 | if(arr[len(arr) - 2] == arr[len(arr) - 1]): 24 | return arr[len(arr) - 1] 25 | 26 | for i in range(2,len(arr) - 2): 27 | if(arr[i] == arr[i - 1] or arr[i] == arr[i + 1]): 28 | return arr[i] 29 | 30 | # Main 31 | n=int(input()) 32 | arr=list(int(i) for i in input().strip().split(' ')) 33 | ans=MissingNumber(arr) 34 | print(ans) 35 | -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/find_the_unique_element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array of size 2N + 1. In this given array, N numbers are present twice and one number is present only once in the array. 3 | You need to find and return that number which is unique in the array. 4 | Note : Given array will always contain odd number of elements. 5 | Input format : 6 | Line 1 : Array size i.e. 2N+1 7 | Line 2 : Array elements (separated by space) 8 | Output Format : 9 | Unique element present in the array 10 | Constraints : 11 | 1 <= N <= 10^6 12 | Sample Input : 13 | 7 14 | 2 3 1 6 3 6 2 15 | Sample Output : 16 | 1 17 | ''' 18 | def FindUnique(arr): 19 | # Please add your code here 20 | arr.sort() 21 | if(arr[0] != arr[1]): 22 | return arr[0] 23 | 24 | elif(arr[len(arr) - 2] != arr[len(arr) - 1]): 25 | return arr[len(arr) - 1] 26 | 27 | for i in range(2, len(arr) - 2): 28 | if(arr[i] != arr[i + 1] and arr[i] != arr[i - 1]): 29 | return arr[i] 30 | 31 | # Main 32 | n=int(input()) 33 | arr=list(int(i) for i in input().strip().split(' ')) 34 | unique=FindUnique(arr) 35 | print(unique) 36 | -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/longest_consecutive_sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of unique integers that contain numbers in random order. Write a program to find the longest possible sequence of consecutive numbers using the numbers from given array. 3 | You need to return the output array which contains consecutive elements. Order of elements in the output is not important. 4 | Best solution takes O(n) time. 5 | If two sequences are of equal length then return the sequence starting with the number whose occurrence is earlier in the array. 6 | Input Format : 7 | Line 1 : Integer n, Size of array 8 | Line 2 : Array elements (separated by space) 9 | Constraints : 10 | 0 <= n <= 10^8 11 | Sample Input 1 : 12 | 13 13 | 2 12 9 16 10 5 3 20 25 11 1 8 6 14 | Sample Output 1 : 15 | 8 16 | 9 17 | 10 18 | 11 19 | 12 20 | Sample Input 2 : 21 | 7 22 | 3 7 2 1 9 8 41 23 | Sample Output 2 : 24 | 7 25 | 8 26 | 9 27 | Explanation: Sequence should be of consecutive numbers. Here we have 2 sequences with same length i.e. [1, 2, 3] and [7, 8, 9], but output should be [7, 8, 9] because the starting point of [7, 8, 9] comes first in input array. 28 | Sample Input 3 : 29 | 7 30 | 15 24 23 12 19 11 16 31 | Sample Output 3 : 32 | 15 33 | 16 34 | */ 35 | #include 36 | using namespace std; 37 | 38 | vector longestConsecutiveIncreasingSequence(int *arr, int n){ 39 | //Your Code goes here 40 | //typedef pair p; 41 | unordered_map m; 42 | int maxlength = 0, start = 0; 43 | for(int i = 0; i < n; i++){ 44 | m[arr[i]] = 0; 45 | } 46 | 47 | for(int i = 0; i < n; i++){ 48 | int j = arr[i]; 49 | 50 | if (m.find(j - 1) == m.end()) 51 | { 52 | // Then check for next elements in the 53 | // sequence 54 | 55 | while (m.find(j) != m.end()){ 56 | j++; 57 | (m[arr[i]])++; 58 | } 59 | if(j - arr[i] > maxlength){ 60 | maxlength = m[arr[i]]; 61 | start = arr[i]; 62 | } 63 | } 64 | } 65 | 66 | 67 | vector ans; 68 | 69 | for(int i = 0; i < maxlength; i++){ 70 | ans.push_back(start); 71 | start++; 72 | } 73 | return ans; 74 | } -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/longest_consecutive_sequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an array of unique integers that contain numbers in random order. Write a program to find the longest possible sequence of consecutive numbers using the numbers from given array. 3 | You need to return the output array which contains consecutive elements. Order of elements in the output is not important. 4 | Best solution takes O(n) time. 5 | If two sequences are of equal length then return the sequence starting with the number whose occurrence is earlier in the array. 6 | Input Format : 7 | Line 1 : Integer n, Size of array 8 | Line 2 : Array elements (separated by space) 9 | Constraints : 10 | 0 <= n <= 10^8 11 | Sample Input 1 : 12 | 13 13 | 2 12 9 16 10 5 3 20 25 11 1 8 6 14 | Sample Output 1 : 15 | 8 16 | 9 17 | 10 18 | 11 19 | 12 20 | Sample Input 2 : 21 | 7 22 | 3 7 2 1 9 8 41 23 | Sample Output 2 : 24 | 7 25 | 8 26 | 9 27 | Explanation: Sequence should be of consecutive numbers. Here we have 2 sequences with same length i.e. [1, 2, 3] and [7, 8, 9], but output should be [7, 8, 9] because the starting point of [7, 8, 9] comes first in input array. 28 | Sample Input 3 : 29 | 7 30 | 15 24 23 12 19 11 16 31 | Sample Output 3 : 32 | 15 33 | 16 34 | ''' 35 | def longestConsecutiveSubsequence(l): 36 | #Implement Your Code Here 37 | #You have To Return the list of longestConsecutiveSubsequence 38 | ans = [] 39 | #l.sort() 40 | maxlength = 0 41 | start = 0 42 | d = {} 43 | for i in range(len(l)): 44 | d[l[i]] = [1, True] 45 | 46 | #print(d) 47 | for i in range(len(l)): 48 | j = l[i] 49 | #print("hello") 50 | while(d[l[i]][1] == True): 51 | if j + 1 in d: 52 | d[l[i]][0] += 1 53 | j += 1 54 | else: 55 | d[l[i]][1] = False 56 | 57 | if d[l[i]][0] > maxlength: 58 | maxlength = d[l[i]][0] 59 | start = l[i] 60 | #print(d) 61 | #print("max", maxlength) 62 | for i in range(maxlength): 63 | ans.append(start) 64 | start += 1 65 | return ans 66 | 67 | 68 | n=int(input()) 69 | l=list(int(i) for i in input().strip().split(' ')) 70 | final = longestConsecutiveSubsequence(l) 71 | for num in final: 72 | print(num) -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/pair_sum_to_0.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a random integer array A of size N. Find and print the pair of elements in the array which sum to 0. 3 | Array A can contain duplicate elements. 4 | While printing a pair, print the smaller element first. 5 | That is, if a valid pair is (6, -6) print "-6 6". There is no constraint that out of 5 pairs which have to be printed in 1st line. You can print pairs in any order, just be careful about the order of elements in a pair. 6 | Input format : 7 | Line 1 : Integer N (Array size) 8 | Line 2 : Array elements (separated by space) 9 | Output format : 10 | Line 1 : Pair 1 elements (separated by space) 11 | Line 2 : Pair 2 elements (separated by space) 12 | Line 3 : and so on 13 | Constraints : 14 | 0 <= N <= 10^4 15 | Sample Input: 16 | 5 17 | 2 1 -2 2 3 18 | Sample Output : 19 | -2 2 20 | -2 2 21 | ''' 22 | def pairSum0(l): 23 | #Implement Your Code Here 24 | d = {} 25 | for i in range(len(l)): 26 | if l[i] in d: 27 | d[l[i]] += 1 28 | else: 29 | d[l[i]] = 1 30 | 31 | for i in range(len(l)): 32 | if l[i] >= 0: 33 | if (-1 * l[i]) in d: 34 | for j in range((d[l[i]] * d[(-1 * l[i])])): 35 | print(-1 * l[i], l[i]) 36 | d[l[i]], d[(-1 * l[i])] = 0, 0 37 | 38 | n=int(input()) 39 | l=list(int(i) for i in input().strip().split(' ')) 40 | pairSum0(l) -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/rotate_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left). 3 | Note: 4 | Change in the input array/list itself. You don't need to return or print the elements. 5 | Input format : 6 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 7 | 8 | First line of each test case or query contains an integer 'N' representing the size of the array/list. 9 | 10 | Second line contains 'N' single space separated integers representing the elements in the array/list. 11 | 12 | Third line contains the value of 'D' by which the array/list needs to be rotated. 13 | Output Format : 14 | For each test case, print the rotated array/list in a row separated by a single space. 15 | 16 | Output for every test case will be printed in a separate line. 17 | Constraints : 18 | 1 <= t <= 10^4 19 | 0 <= N <= 10^6 20 | 0 <= D <= N 21 | Time Limit: 1 sec 22 | Sample Input 1: 23 | 1 24 | 7 25 | 1 2 3 4 5 6 7 26 | 2 27 | Sample Output 1: 28 | 3 4 5 6 7 1 2 29 | Sample Input 2: 30 | 2 31 | 7 32 | 1 2 3 4 5 6 7 33 | 0 34 | 4 35 | 1 2 3 4 36 | 2 37 | Sample Output 2: 38 | 1 2 3 4 5 6 7 39 | 3 4 1 2 40 | */ 41 | #include 42 | using namespace std; 43 | void rotate(int arr[], int d, int size) { 44 | /* Don't write main(). 45 | * Don't read input, it is passed as function argument. 46 | * No need to print or return the output. 47 | * Taking input and printing the output is handled automatically. 48 | */ 49 | reverse(arr,arr+size); 50 | reverse(arr+size-d,arr+size); 51 | reverse(arr,arr+size-d); 52 | } 53 | -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/rotate_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left). 3 | Note: 4 | Change in the input array/list itself. You don't need to return or print the elements. 5 | Input format : 6 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 7 | 8 | First line of each test case or query contains an integer 'N' representing the size of the array/list. 9 | 10 | Second line contains 'N' single space separated integers representing the elements in the array/list. 11 | 12 | Third line contains the value of 'D' by which the array/list needs to be rotated. 13 | Output Format : 14 | For each test case, print the rotated array/list in a row separated by a single space. 15 | 16 | Output for every test case will be printed in a separate line. 17 | Constraints : 18 | 1 <= t <= 10^4 19 | 0 <= N <= 10^6 20 | 0 <= D <= N 21 | Time Limit: 1 sec 22 | Sample Input 1: 23 | 1 24 | 7 25 | 1 2 3 4 5 6 7 26 | 2 27 | Sample Output 1: 28 | 3 4 5 6 7 1 2 29 | Sample Input 2: 30 | 2 31 | 7 32 | 1 2 3 4 5 6 7 33 | 0 34 | 4 35 | 1 2 3 4 36 | 2 37 | Sample Output 2: 38 | 1 2 3 4 5 6 7 39 | 3 4 1 2 40 | ''' 41 | def Rotate(arr, d): 42 | # Please add your code here 43 | arr1 = [] 44 | for i in range(d): 45 | arr1.append(arr[i]) 46 | 47 | for i in range(len(arr) - d): 48 | arr[i] = arr[i + d] 49 | 50 | j = 0 51 | for i in range(len(arr) - d, len(arr)): 52 | arr[i] = arr1[j] 53 | j += 1 54 | 55 | # Main 56 | n=int(input()) 57 | arr=list(int(i) for i in input().strip().split(' ')) 58 | d=int(input()) 59 | Rotate(arr, d) 60 | print(*arr) 61 | -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/sum_me_up.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There will be ‘t’ test cases having an integer. You have to sum up all the digits of this integer. For e.g. For 6754, the answer will be 6 + 7 + 5 + 4 = 22. 3 | Input Format: 4 | First line will have an integer ‘t’ denoting the number of test cases. 5 | Next ‘t’ lines will have an integer ‘val’ each. 6 | Output format: 7 | Print ‘t’ lines of output denoting the sum of all the digits of the number in each test case. 8 | Constraints: 9 | 1 <= t <= 10^5 10 | 0 <= val <= 10^18 11 | Sample Input: 12 | 2 13 | 1547 14 | 45876 15 | Sample Output: 16 | 17 17 | 30 18 | Explanation: 19 | 1 + 5 + 4 + 7 = 17 20 | 4 + 5 + 8 + 7 + 6 = 30 21 | ''' 22 | t = int(input()) 23 | for i in range(t): 24 | n = int(input()) 25 | sum = 0 26 | while(n != 0): 27 | sum += n % 10 28 | n = n//10 29 | print(sum) -------------------------------------------------------------------------------- /language_tools_+_time_and_compexity_assignment/triplet_sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x. 3 | While printing a triplet, print the smallest element first. 4 | That is, if a valid triplet is (6, 5, 10) print "5 6 10". There is no constraint that out of 5 triplets which have to be printed on 1st line. You can print triplets in any order, just be careful about the order of elements in a triplet. 5 | Input format : 6 | Line 1 : Integer N (Array Size) 7 | Line 2 : Array elements (separated by space) 8 | Line 3 : Integer x 9 | Output format : 10 | Line 1 : Triplet 1 elements (separated by space) 11 | Line 2 : Triplet 3 elements (separated by space) 12 | Line 3 : and so on 13 | Constraints : 14 | 1 <= N <= 1000 15 | 1 <= x <= 100 16 | Sample Input: 17 | 7 18 | 1 2 3 4 5 6 7 19 | 12 20 | Sample Output ; 21 | 1 4 7 22 | 1 5 6 23 | 2 3 7 24 | 2 4 6 25 | 3 4 5 26 | */ 27 | // arr - input array 28 | // size - size of array 29 | // x - sum of triplets 30 | 31 | void FindTriplet(int arr[], int size, int x) { 32 | /* Don't write main(). 33 | * Don't read input, it is passed as function argument. 34 | * Print output and don't return it. 35 | * Taking input is handled automatically. 36 | */ 37 | for(int i=0;i=arr[j] && arr[i]>=arr[k]) 48 | { 49 | if(arr[j]>=arr[k]) 50 | { 51 | cout << arr[k] << " " << arr[j] << " " << arr[i] << endl; 52 | } 53 | else 54 | { 55 | cout << arr[j] << " " << arr[k] << " " << arr[i] << endl; 56 | } 57 | } 58 | else if(arr[j]>=arr[i] && arr[j]>=arr[k]) 59 | { 60 | if(arr[i]>=arr[k]) 61 | { 62 | cout << arr[k] << " " << arr[i] << " " << arr[j] << endl; 63 | } 64 | else 65 | { 66 | cout << arr[i] << " " << arr[k] << " " << arr[j] << endl; 67 | } 68 | } 69 | else if(arr[k]>=arr[i] && arr[k]>=arr[j]) 70 | { 71 | if(arr[i]>=arr[j]) 72 | { 73 | cout << arr[j] << " " << arr[i] << " " << arr[k] << endl; 74 | } 75 | else 76 | { 77 | cout << arr[i] << " " << arr[j] << " " << arr[k] << endl; 78 | } 79 | } 80 | } 81 | } 82 | } 83 | } 84 | } 85 | } 86 | 87 | -------------------------------------------------------------------------------- /modulo_arithmetic/number_of_balanced_bts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer h, find the possible number of balanced binary trees of height h. You just need to return the count of possible binary trees which are balanced. 3 | This number can be huge, so return output modulus 10^9 + 7. 4 | Write a simple recursive solution. 5 | Input Format : 6 | Integer h 7 | Output Format : 8 | Count % 10^9 + 7 9 | Input Constraints : 10 | 1 <= h <= 40 11 | Sample Input 1: 12 | 3 13 | Sample Output 1: 14 | 15 15 | Sample Input 2: 16 | 4 17 | Sample Output 2: 18 | 315 19 | */ 20 | #define mod 1000000007 21 | int balancedBTs(int h) { 22 | /* Don't write main(). 23 | Don't read input, it is passed as function argument. 24 | Return the output and don’t print it. 25 | */ 26 | long long int dp[h + 1]; 27 | //base cases 28 | dp[0] = dp[1] = 1; 29 | for(int i = 2; i <= h; i++) { 30 | dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%mod + dp[i - 1])%mod) % mod; 31 | } 32 | return dp[h]; 33 | } 34 | -------------------------------------------------------------------------------- /prerequisites/chakri.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Diwali is here. While everyone here is busy texting "Happy Diwali" wishes to everybody else, NinjaCoder has some other plans and wants to earn some money this season. 3 | Now, the Apex court has allowed the sale of only green crackers this Diwali. Out of all green crackers, "Chakri" is most popular. Because of the irregular supply of "Chakri", the price of "Chakri" is oscillating daily. NinjaCoder saw a business opportunity in this. He/She got a price list for coming N days from an insider in the market union. Prices in the list are for 1 unit of a large packet of "Chakri". Each large packet contains 100 units of Chakri. 4 | Now, due to financial limitations, NinjaCoder can transact only 1 large packet (100 units of "Chakri") in the market. You have to tell maximum profit possible, given that he/she can transact atmost one time. 5 | Note: 1. Transaction refers to the act of buying and selling. 6 | 2. "Chakri" cannot be sold individually. NinjaCoder has to buy/sell the entire packet. 7 | Input Format 8 | First-line contains N - (Integer) 9 | Second-line contains N spaced integers. 10 | Constraints 11 | 1 <= N <= 10000 12 | 50 <= A(i) <= 100 13 | Output Format 14 | Print the maximum profit that can be generated by NinjaCoder. 15 | Sample Input 0: 16 | 7 17 | 62 63 70 66 64 68 61 18 | Sample Output 0: 19 | 8 20 | ''' 21 | def maxProfit(arr): 22 | ans = [] 23 | for i in range(len(arr)): 24 | if i + 1 < len(arr): 25 | arr1 = [arr[i] for i in range(i + 1, len(arr))] 26 | #print(arr1) 27 | ans.append(max(arr1) - arr[i]) 28 | #print(ans) 29 | return max(ans) 30 | 31 | 32 | n = int(input()) 33 | arr = [int(x) for x in input().split()] 34 | ans = maxProfit(arr) 35 | print(ans) -------------------------------------------------------------------------------- /prerequisites/even_and_odd_indexes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, print two integer values: 3 | First, the sum of all numbers which are even as well as whose index are even. 4 | Second, the sum of all numbers which are odd as well as whose index are odd. 5 | Print the two integers space separated. (Arrays is 0-indexed) 6 | Input: 7 | Given an integer denoting the size of array. 8 | Next line will have a line containing ‘n’ space separated integers. 9 | Constraints: 10 | 1<=n<=10^5 11 | 1 <= Ai <= 10^6 12 | Output: 13 | Two space separated integers denoting even and odd sums respectively. 14 | Sample Input: 15 | 5 16 | 2 3 5 1 4 17 | Sample Output: 18 | 6 4 19 | */ 20 | #include 21 | using namespace std; 22 | int main(){ 23 | int n; 24 | cin >> n; 25 | int arr[n]; 26 | for (int i = 0; i < n; i++) 27 | { 28 | cin >> arr[i]; 29 | } 30 | 31 | long long int os = 0, es = 0; 32 | 33 | for (int i = 0; i < n; i++) 34 | { 35 | if (i % 2 == 0 and arr[i] % 2 == 0) 36 | { 37 | es += arr[i]; 38 | } 39 | else if(i % 2 != 0 and arr[i] % 2 != 0) 40 | { 41 | os += arr[i]; 42 | } 43 | } 44 | cout << es << " " << os << "\n"; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /prerequisites/even_and_odd_indexes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, print two integer values: 3 | First, the sum of all numbers which are even as well as whose index are even. 4 | Second, the sum of all numbers which are odd as well as whose index are odd. 5 | Print the two integers space separated. (Arrays is 0-indexed) 6 | Input: 7 | Given an integer denoting the size of array. 8 | Next line will have a line containing ‘n’ space separated integers. 9 | Constraints: 10 | 1<=n<=10^5 11 | 1 <= Ai <= 10^6 12 | Output: 13 | Two space separated integers denoting even and odd sums respectively. 14 | Sample Input: 15 | 5 16 | 2 3 5 1 4 17 | Sample Output: 18 | 6 4 19 | ''' 20 | def even(x): 21 | if(x % 2 == 0): 22 | return True 23 | return False 24 | 25 | # Write your code here 26 | i = int(input()) 27 | arr = [int(x) for x in input().split()] 28 | os, es = 0, 0 29 | for j in range(i): 30 | if(even(j)): 31 | if(even(arr[j])): 32 | es += arr[j] 33 | else: 34 | if(even(arr[j]) == False): 35 | os += arr[j] 36 | print(es, end = " ") 37 | print(os) -------------------------------------------------------------------------------- /prerequisites/pre4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are ‘n’ number of villages. You are given an array of size ‘n’ representing the population of each village. Every year, there is a cricket competition between two teams and villagers who come to see the match. Villagers from ith village and (n-i)-1th village (0 <= i < n/2) are combined and then formed groups of 10 people each. For e.g. villagers from villages 0 and n-1, 1 and n-2, 2 and n-3 are combined. The number of villages is always even. So, clearly there will be n/2 combinations from all the villages. You have to tell how many groups will be formed in each combination and how many villagers will be left without the complete group of 10 peoples. 3 | Input Format: 4 | First-line will have a single integer ‘n’ denotes the number of villages. 5 | The second line will have ‘n’ space-separated integers denoting the population of villages. 6 | Output format: 7 | Print ‘n/2’ lines of two space-separated integers, first will be no. of groups and second will be villagers left without a group. The first line will have the result of a combination of 0 and n-1, second will have 1 and n-2 and so on. 8 | Constraints: 9 | 1 <= n <= 10^5 10 | 1 <= Ai <= 10^6 11 | ‘n’ will always be even 12 | Sample Input: 13 | 10 14 | 26 96 18 24 87 51 44 86 75 32 15 | Sample Output: 16 | 5 8 17 | 17 1 18 | 10 4 19 | 6 8 20 | 13 8 21 | */ 22 | #include 23 | using namespace std; 24 | int main() 25 | { 26 | int n; 27 | cin >> n; 28 | int arr[n]; 29 | for(int i = 0; i < n; i++){ 30 | cin >> arr[i]; 31 | } 32 | 33 | for(int i = 0; i < n/2; i++){ 34 | cout << ((arr[i] + arr[n - i - 1])/10) << " " << ((arr[i] + arr[n - i - 1])%10) << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /prerequisites/pre4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are ‘n’ number of villages. You are given an array of size ‘n’ representing the population of each village. Every year, there is a cricket competition between two teams and villagers who come to see the match. Villagers from ith village and (n-i)-1th village (0 <= i < n/2) are combined and then formed groups of 10 people each. For e.g. villagers from villages 0 and n-1, 1 and n-2, 2 and n-3 are combined. The number of villages is always even. So, clearly there will be n/2 combinations from all the villages. You have to tell how many groups will be formed in each combination and how many villagers will be left without the complete group of 10 peoples. 3 | Input Format: 4 | First-line will have a single integer ‘n’ denotes the number of villages. 5 | The second line will have ‘n’ space-separated integers denoting the population of villages. 6 | Output format: 7 | Print ‘n/2’ lines of two space-separated integers, first will be no. of groups and second will be villagers left without a group. The first line will have the result of a combination of 0 and n-1, second will have 1 and n-2 and so on. 8 | Constraints: 9 | 1 <= n <= 10^5 10 | 1 <= Ai <= 10^6 11 | ‘n’ will always be even 12 | Sample Input: 13 | 10 14 | 26 96 18 24 87 51 44 86 75 32 15 | Sample Output: 16 | 5 8 17 | 17 1 18 | 10 4 19 | 6 8 20 | 13 8 21 | ''' 22 | n = int(input()) 23 | arr = [int(x) for x in input().split()] 24 | for i in range(int(n/2)): 25 | print((arr[i] + arr[n - i - 1]) // 10, end = " ") 26 | print((arr[i] + arr[n - i - 1]) % 10) -------------------------------------------------------------------------------- /prerequisites/target_marbles.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | At CodingNinjas, we love to play with marbles. We have many marble games, but the most popular one is “Target Marbles”. Now, our marbles are unique. Each marble has a number on it. 3 | In Target Marbles, the player is given a number in the starting and this number is called target. The player is also given N number of marbles to play with. Now, player has to arrange the marbles in a specific way such that sum of the values of at least one of the continuous subset of the arrangement is equal to given target. 4 | Now, NinjaCoder came to play this game and made an arrangement of marbles. The judges of the game need your help. You have to determine if NinjaCoder has won it or not. 5 | Input Format : 6 | First line contains number of marbles(N) and target (target_number) that was assigned to NinjaCoder. Second line contains N space separated integers, which represent arrangement of the marbles and value written on that particular marble. 7 | Constraints: 8 | 1<= N <=100 9 | 1<=target_number<=10000 10 | Value on the marbles lies in the range [0, 1000]. 11 | Output Format : 12 | You have to print “true”, if the NinjaCoder wins with the given arrangement and you have to print the values of the continuous subsets. If there are more that one continuous subsets, then you have to print the values of first continuous subset. If the Ninjas coder is unable to win, you just have to print “false”. 13 | Sample Input 1 : 14 | 10 10 15 | 9 1 2 3 4 5 5 16 17 19 16 | Sample Output 1 : 17 | true 18 | 9 1 19 | Explanation: 20 | Here, if the NinjaCoder arranges the given 10 marbles in this arrangement, then he/she will win the game. Now, there are many continuous subsets of marbles that will win the game such as (9,1) or (1, 2, 3, 4). Out of these winning combinations, you have to print the first one which is (9,1). 21 | Sample Input 2 : 22 | 10 10 23 | 19 11 12 131 14 15 5 16 17 19 24 | Sample Output 2: 25 | false 26 | */ 27 | #include 28 | using namespace std; 29 | 30 | void sub_array_sum(int *arr, int n, int ans){ 31 | int curr_sum = arr[0]; 32 | int st = 0, i = 1; 33 | while(i <= n){ 34 | while((curr_sum > ans) && st < i - 1){ 35 | curr_sum -= arr[st]; 36 | st++; 37 | } 38 | if(curr_sum == ans){ 39 | cout << "true" << endl; 40 | for(int j = st; j < i; j++){ 41 | cout << arr[j] << " "; 42 | } 43 | return; 44 | } 45 | if(i < n) 46 | curr_sum += arr[i]; 47 | i++; 48 | } 49 | cout << "false"; 50 | } 51 | 52 | int main() { 53 | int n, ans; 54 | cin >> n >> ans; 55 | int arr[n]; 56 | for(int i = 0; i < n; i++) 57 | cin >> arr[i]; 58 | sub_array_sum(arr, n, ans); 59 | // Write your code here 60 | } -------------------------------------------------------------------------------- /prerequisites/target_marbles.py: -------------------------------------------------------------------------------- 1 | ''' 2 | At CodingNinjas, we love to play with marbles. We have many marble games, but the most popular one is “Target Marbles”. Now, our marbles are unique. Each marble has a number on it. 3 | In Target Marbles, the player is given a number in the starting and this number is called target. The player is also given N number of marbles to play with. Now, player has to arrange the marbles in a specific way such that sum of the values of at least one of the continuous subset of the arrangement is equal to given target. 4 | Now, NinjaCoder came to play this game and made an arrangement of marbles. The judges of the game need your help. You have to determine if NinjaCoder has won it or not. 5 | Input Format : 6 | First line contains number of marbles(N) and target (target_number) that was assigned to NinjaCoder. Second line contains N space separated integers, which represent arrangement of the marbles and value written on that particular marble. 7 | Constraints: 8 | 1<= N <=100 9 | 1<=target_number<=10000 10 | Value on the marbles lies in the range [0, 1000]. 11 | Output Format : 12 | You have to print “true”, if the NinjaCoder wins with the given arrangement and you have to print the values of the continuous subsets. If there are more that one continuous subsets, then you have to print the values of first continuous subset. If the Ninjas coder is unable to win, you just have to print “false”. 13 | Sample Input 1 : 14 | 10 10 15 | 9 1 2 3 4 5 5 16 17 19 16 | Sample Output 1 : 17 | true 18 | 9 1 19 | Explanation: 20 | Here, if the NinjaCoder arranges the given 10 marbles in this arrangement, then he/she will win the game. Now, there are many continuous subsets of marbles that will win the game such as (9,1) or (1, 2, 3, 4). Out of these winning combinations, you have to print the first one which is (9,1). 21 | Sample Input 2 : 22 | 10 10 23 | 19 11 12 131 14 15 5 16 17 19 24 | Sample Output 2: 25 | false 26 | ''' 27 | def SubarraySum(arr, n, ans): 28 | curr_sum = arr[0] 29 | st, i = 0, 1 30 | while i <= n: 31 | while curr_sum > ans and st < i-1: 32 | 33 | curr_sum = curr_sum - arr[st] 34 | st += 1 35 | if curr_sum == ans: 36 | print("true") 37 | for j in range(st, i): 38 | print(arr[j], end = " ") 39 | return 40 | if i < n: 41 | curr_sum += arr[i] 42 | i += 1 43 | print("false") 44 | 45 | 46 | n, ans = input().split() 47 | n = int(n) 48 | ans = int(ans) 49 | arr = [int(x) for x in input().split()] 50 | SubarraySum(arr, n, ans) -------------------------------------------------------------------------------- /prerequisites/total_sum_on_the_boundaries_and_diagonals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries. 3 | Input format: 4 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 5 | 6 | First line of each test case or query contains a single integer value, 'N' representing the 'rows' and 'columns' for the two-dimensional square matrix. 7 | 8 | Second line onwards, the next 'N' lines or rows represent the ith row values. 9 | 10 | Each of the ith row constitutes 'N' column values separated by a single space. 11 | Output format: 12 | For each test case, print the single integer denoting the sum. 13 | 14 | Output for every test case will be printed in a seperate line. 15 | Constraints: 16 | 1 <= t <= 10^2 17 | 0 <= N <= 10^3 18 | Time Limit: 1sec 19 | Sample input 1: 20 | 1 21 | 3 22 | 1 2 3 23 | 4 5 6 24 | 7 8 9 25 | Sample Output 1: 26 | 45 27 | Explanation for Sample Output 1: 28 | The boundary elements are 1, 2, 3, 6, 9, 8, 7 and 4. 29 | 30 | The first-diagonal elements are 1, 5 and 9. 31 | 32 | The second-diagonal elements are 3, 5 and 7. 33 | 34 | We just need to add all these numbers making sure that no number is added twice. For example, '1' is both a boundary element and a first-diagonal element similarly, '5' contributes to both the diagonals but they won't be added twice. 35 | 36 | Hence, we add up, [1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 + 5] to give 45 as the output. 37 | Sample input 2: 38 | 2 39 | 5 40 | 1 2 3 4 5 41 | 6 7 8 9 10 42 | 11 12 13 14 15 43 | 16 17 18 19 20 44 | 21 22 23 24 25 45 | 4 46 | 1 2 3 10 47 | 4 5 6 11 48 | 7 8 9 12 49 | 13 14 15 16 50 | Sample Output 2: 51 | 273 52 | 136 53 | */ 54 | #include 55 | using namespace std; 56 | int main() 57 | { 58 | int n; 59 | cin >> n; 60 | int arr[n][n]; 61 | for(int i = 0; i < n; i++){ 62 | for(int j = 0; j < n; j++){ 63 | cin >> arr[i][j]; 64 | } 65 | } 66 | 67 | int sum = 0; 68 | for(int i = 0; i < n; i++){ 69 | sum += arr[i][i]; 70 | sum += arr[i][n - i - 1]; 71 | sum += arr[0][i]; 72 | sum += arr[n - 1][i]; 73 | sum += arr[i][0]; 74 | sum += arr[i][n - 1]; 75 | } 76 | 77 | if(n % 2 != 0){ 78 | sum -= arr[n/2][n/2]; 79 | } 80 | 81 | cout << (sum - 2*arr[0][0] - 2*arr[0][n - 1] - 2*arr[n - 1][0] - 2*arr[n - 1][n - 1]) << endl; 82 | return 0; 83 | } -------------------------------------------------------------------------------- /prerequisites/total_sum_on_the_boundaries_and_diagonals.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries. 3 | Input format: 4 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 5 | 6 | First line of each test case or query contains a single integer value, 'N' representing the 'rows' and 'columns' for the two-dimensional square matrix. 7 | 8 | Second line onwards, the next 'N' lines or rows represent the ith row values. 9 | 10 | Each of the ith row constitutes 'N' column values separated by a single space. 11 | Output format: 12 | For each test case, print the single integer denoting the sum. 13 | 14 | Output for every test case will be printed in a seperate line. 15 | Constraints: 16 | 1 <= t <= 10^2 17 | 0 <= N <= 10^3 18 | Time Limit: 1sec 19 | Sample input 1: 20 | 1 21 | 3 22 | 1 2 3 23 | 4 5 6 24 | 7 8 9 25 | Sample Output 1: 26 | 45 27 | Explanation for Sample Output 1: 28 | The boundary elements are 1, 2, 3, 6, 9, 8, 7 and 4. 29 | 30 | The first-diagonal elements are 1, 5 and 9. 31 | 32 | The second-diagonal elements are 3, 5 and 7. 33 | 34 | We just need to add all these numbers making sure that no number is added twice. For example, '1' is both a boundary element and a first-diagonal element similarly, '5' contributes to both the diagonals but they won't be added twice. 35 | 36 | Hence, we add up, [1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 + 5] to give 45 as the output. 37 | Sample input 2: 38 | 2 39 | 5 40 | 1 2 3 4 5 41 | 6 7 8 9 10 42 | 11 12 13 14 15 43 | 16 17 18 19 20 44 | 21 22 23 24 25 45 | 4 46 | 1 2 3 10 47 | 4 5 6 11 48 | 7 8 9 12 49 | 13 14 15 16 50 | Sample Output 2: 51 | 273 52 | 136 53 | ''' 54 | n = int(input()) 55 | arr = [[int(x) for x in input().split()] for y in range(n)] 56 | sum = 0 57 | for i in range(n): 58 | for j in range(n): 59 | if(i == 0 or j == 0 or i == j or i == n - 1 or j == n - 1 or i + j == n - 1): 60 | sum += arr[i][j] 61 | print(sum) -------------------------------------------------------------------------------- /prerequisites/total_sum_on_the_boundaries_and_diagonals_2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries. 3 | Input format: 4 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 5 | 6 | First line of each test case or query contains a single integer value, 'N' representing the 'rows' and 'columns' for the two-dimensional square matrix. 7 | 8 | Second line onwards, the next 'N' lines or rows represent the ith row values. 9 | 10 | Each of the ith row constitutes 'N' column values separated by a single space. 11 | Output format: 12 | For each test case, print the single integer denoting the sum. 13 | 14 | Output for every test case will be printed in a seperate line. 15 | Constraints: 16 | 1 <= t <= 10^2 17 | 0 <= N <= 10^3 18 | Time Limit: 1sec 19 | Sample input 1: 20 | 1 21 | 3 22 | 1 2 3 23 | 4 5 6 24 | 7 8 9 25 | Sample Output 1: 26 | 45 27 | Explanation for Sample Output 1: 28 | The boundary elements are 1, 2, 3, 6, 9, 8, 7 and 4. 29 | 30 | The first-diagonal elements are 1, 5 and 9. 31 | 32 | The second-diagonal elements are 3, 5 and 7. 33 | 34 | We just need to add all these numbers making sure that no number is added twice. For example, '1' is both a boundary element and a first-diagonal element similarly, '5' contributes to both the diagonals but they won't be added twice. 35 | 36 | Hence, we add up, [1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 + 5] to give 45 as the output. 37 | Sample input 2: 38 | 2 39 | 5 40 | 1 2 3 4 5 41 | 6 7 8 9 10 42 | 11 12 13 14 15 43 | 16 17 18 19 20 44 | 21 22 23 24 25 45 | 4 46 | 1 2 3 10 47 | 4 5 6 11 48 | 7 8 9 12 49 | 13 14 15 16 50 | Sample Output 2: 51 | 273 52 | 136 53 | */ 54 | #include 55 | using namespace std; 56 | 57 | int main() 58 | { 59 | int t; 60 | cin >> t; 61 | while (t--) 62 | { 63 | int n; 64 | cin >> n; 65 | int arr[n][n]; 66 | for (int i = 0; i < n; i++) 67 | { 68 | for (int j = 0; j < n; j++) 69 | { 70 | cin >> arr[i][j]; 71 | } 72 | } 73 | 74 | int sum = 0; 75 | 76 | //boundaries 77 | for (int i = 1; i < n - 1; i++) 78 | { 79 | sum += arr[0][i]; //upper boundary 80 | sum += arr[n - 1][i]; //lower boundary 81 | sum += arr[i][0]; //left boundary 82 | sum += arr[i][n - 1]; //right boundary 83 | } 84 | 85 | //firstDiagonal 86 | for (int i = 0; i < n; i++) 87 | { 88 | sum += arr[i][i]; 89 | } 90 | 91 | //secondDiagonal 92 | for (int i = 0; i < n; i++) 93 | { 94 | sum += arr[i][n - i - 1]; 95 | } 96 | 97 | if(n % 2 != 0) 98 | { 99 | sum -= arr[n/2][n/2]; 100 | } 101 | 102 | cout << sum << "\n"; 103 | } 104 | return 0; 105 | } -------------------------------------------------------------------------------- /searching_&_sorting_applications/aggressive_cows_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000). 3 | His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance? 4 | Input 5 | t – the number of test cases, then t test cases follows. 6 | * Line 1: Two space-separated integers: N and C 7 | * Lines 2..N+1: Line i+1 contains an integer stall location, xi 8 | Output 9 | For each test case output one integer: the largest minimum distance. 10 | Sample Input : 11 | 1 12 | 5 3 13 | 1 14 | 2 15 | 8 16 | 4 17 | 9 18 | Sample Output: 19 | 3 20 | Output details: 21 | FJ can put his 3 cows in the stalls at positions 1, 4 and 8, 22 | resulting in a minimum distance of 3. 23 | */ 24 | #include 25 | using namespace std; 26 | 27 | bool check(int cows,long long positions[],int n,long long distance){ 28 | 29 | int count = 1; 30 | long long last_position = positions[0]; 31 | 32 | for(int i=1;i= distance){ 34 | last_position = positions[i]; 35 | count++; 36 | } 37 | 38 | if(count == cows){ 39 | return true; 40 | } 41 | } 42 | return false; 43 | } 44 | 45 | int main(){ 46 | int t; 47 | cin >> t; 48 | while(t--){ 49 | int n,c; 50 | cin >> n >> c; 51 | 52 | long long positions[n]; 53 | for(int i=0;i> positions[i]; 55 | } 56 | sort(positions,positions+n); 57 | long long start = 0; 58 | long long end = positions[n-1] - positions[0]; 59 | 60 | long long ans = -1; 61 | 62 | while(start<=end){ 63 | long long mid = start + (end-start)/2; 64 | 65 | if(check(c,positions,n,mid)){ 66 | ans = mid; 67 | start = mid+1; 68 | }else{ 69 | end = mid-1; 70 | } 71 | 72 | } 73 | cout << ans < 19 | using namespace std; 20 | int ans; 21 | 22 | bool check(int *arr, int min, int max, int n, int k){ 23 | int mid = (min + max)/2, person = 0; 24 | for(int i = 0; i < n; i++){ 25 | person += arr[i]/mid; 26 | //cout << person << " " << k << endl; 27 | if(person >= k){ 28 | return true; 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | int binsDC(int *arr, int min, int max, int n, int k){ 35 | int mid = (min + max)/2; 36 | if(mid == max || mid == min){ 37 | //cout << "hi1" << endl; 38 | return ans; 39 | } 40 | if(check(arr, min, max, n, k)){ 41 | if(mid > ans){ 42 | //cout << "hi2" << endl; 43 | ans = mid; 44 | } 45 | //cout << "hi3" << endl; 46 | return binsDC(arr, mid, max, n, k); 47 | } 48 | else{ 49 | //cout << "hi4" << endl; 50 | return binsDC(arr, min, mid, n, k); 51 | } 52 | } 53 | 54 | int main() { 55 | 56 | // Write your code here 57 | int t; 58 | cin >> t; 59 | while(t--){ 60 | ans = 0; 61 | int n, k; 62 | cin >> n >> k; 63 | int arr[n]; 64 | 65 | for(int i = 0; i < n; i++) 66 | cin >> arr[i]; 67 | 68 | cout << binsDC(arr, 0, *max_element(arr, arr + n), n, k) << endl; 69 | } 70 | } -------------------------------------------------------------------------------- /searching_&_sorting_applications/inversion_counts.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Let A[0 ... n-1] be an array of n distinct positive integers. If i < j and A[i] > A[j] then the pair (i, j) is called an inversion of A (where i and j are indexes of A). Given an integer array A, your task is to find the number of inversions in A. 3 | Input format : 4 | Line 1 : n, array size 5 | Line 2 : Array elements (separated by space). 6 | Output format : 7 | Count of inversions 8 | Constraints : 9 | 1 <= n <= 10^5 10 | 1 <= A[i] <= 10^9 11 | Sample Input 1 : 12 | 3 13 | 3 2 1 14 | Sample Output 1 : 15 | 3 16 | Sample Input 2 : 17 | 5 18 | 2 5 1 3 4 19 | Sample Output 1 : 20 | 4 21 | ''' 22 | ## Read input as specified in the question. 23 | ## Print output as specified in the question. 24 | def mergeSort(arr, n): 25 | temp_arr = [0]*n 26 | return _mergeSort(arr, temp_arr, 0, n-1) 27 | 28 | def _mergeSort(arr, temp_arr, left, right): 29 | 30 | inv_count = 0 31 | 32 | if left < right: 33 | 34 | mid = (left + right)//2 35 | inv_count = _mergeSort(arr, temp_arr, left, mid) 36 | inv_count += _mergeSort(arr, temp_arr, mid + 1, right) 37 | inv_count += merge(arr, temp_arr, left, mid, right) 38 | return inv_count 39 | 40 | def merge(arr, temp_arr, left, mid, right): 41 | i = left 42 | j = mid + 1 43 | k = left 44 | inv_count = 0 45 | 46 | while i <= mid and j <= right: 47 | 48 | 49 | 50 | if arr[i] <= arr[j]: 51 | temp_arr[k] = arr[i] 52 | k += 1 53 | i += 1 54 | else: 55 | 56 | temp_arr[k] = arr[j] 57 | inv_count += (mid-i + 1) 58 | k += 1 59 | j += 1 60 | 61 | while i <= mid: 62 | temp_arr[k] = arr[i] 63 | k += 1 64 | i += 1 65 | 66 | while j <= right: 67 | temp_arr[k] = arr[j] 68 | k += 1 69 | j += 1 70 | 71 | for loop_var in range(left, right + 1): 72 | arr[loop_var] = temp_arr[loop_var] 73 | 74 | return inv_count 75 | 76 | n = int(input()) 77 | arr = [int(x) for x in input().split()] 78 | print(mergeSort(arr, n)) 79 | -------------------------------------------------------------------------------- /searching_&_sorting_applications/momo_market.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Shreya loves to eat momos. Her mother gives her money to buy vegetables but she manages to save some money out of it daily. After buying vegetables, she goes to "Momos Market", where there are ‘n’ number of shops of momos. Each of the shops of momos has a rate per momo. She visits the market and starts buying momos (one from each shop) starting from the first shop. She will visit the market for ‘q’ days. You have to tell that how many momos she can buy each day if she starts buying from the first shop daily. She cannot use the remaining money of one day on some other day. But she will save them for other expenses in the future, so, you also need to tell the sum of money left with her at the end of each day. 3 | Input Format: 4 | First line will have an integer ‘n’ denoting the number of shops in market. 5 | Next line will have ‘n’ numbers denoting the price of one momo of each shop. 6 | Next line will have an integer ‘q’ denoting the number of days she will visit the market. 7 | Next ‘q’ lines will have one integer ‘X’ denoting the money she saved after buying vegetables. 8 | Constraints: 9 | 1 <= n <= 10^5 10 | 1 <= q <= 10^5 11 | 1 <= X <= 10^9 12 | Output: 13 | There will be ‘q’ lines of output each having two space separated integers denoting number of momos she can buy and amount of money she saved each day. 14 | Sample Input: 15 | 4 16 | 2 1 6 3 17 | 1 18 | 11 19 | Sample Output: 20 | 3 2 21 | Explanation: 22 | Shreya visits the "Momos Market" for only one day. She has 11 INR to spend. She can buy 3 momos, each from the first 3 shops. She would 9 INR (2 + 1 + 6) for the same and hence, she will save 2 INR. 23 | */ 24 | #include 25 | using namespace std; 26 | 27 | int binarySearch(int *arr, int n, int start, int end){ 28 | int mid = (start + end)/2; 29 | if(n >= arr[end - 1]) 30 | return (end - 1); 31 | if(n >= arr[mid]){ 32 | return binarySearch(arr, n, mid + 1, end); 33 | } 34 | return binarySearch(arr, n, start, mid); 35 | } 36 | 37 | int main() 38 | { 39 | int n; 40 | cin >> n; 41 | int arr[n]; 42 | 43 | for(int i = 0; i < n; i++) 44 | cin >> arr[i]; 45 | 46 | for(int i = 1; i < n; i++) 47 | arr[i] += arr[i - 1]; 48 | int t, left; 49 | cin >> t; 50 | 51 | while(t--){ 52 | int momos = 0, saved = 0; 53 | cin >> left; 54 | momos = binarySearch(arr, left, 0, n) + 1; 55 | saved = left - arr[momos - 1]; 56 | cout << momos << " " << saved << endl; 57 | } 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /searching_&_sorting_applications/murder.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Once detective Saikat was solving a murder case. While going to the crime scene he took the stairs and saw that a number is written on every stair. He found it suspicious and decides to remember all the numbers that he has seen till now. While remembering the numbers he found that he can find some pattern in those numbers. So he decides that for each number on the stairs he will note down the sum of all the numbers previously seen on the stairs which are smaller than the present number. Calculate the sum of all the numbers written on his notes diary. 3 | Answer may not fit in integer . You have to take long. 4 | Input 5 | First line gives T, number of test cases. 6 | 7 | 2T lines follow. 8 | 9 | First line gives you the number of stairs N 10 | 11 | Next line gives you N numbers written on the stairs. 12 | Output 13 | For each test case output one line giving the final sum for each test case. 14 | Constraints 15 | T<=10 16 | 17 | 1<=N<=10^5 18 | 19 | All numbers will be between 0 and 10^6. 20 | Sample Input: 21 | 1 22 | 5 23 | 1 5 3 6 4 24 | Sample Output: 25 | 15 26 | Explanation: 27 | For the first number, the contribution to the sum is 0. 28 | For the second number, the contribution to the sum is 1. 29 | For the third number, the contribution to the sum is 1. 30 | For the fourth number, the contribution to the sum is 9 (1+5+3). 31 | For the fifth number, the contribution to the sum is 4 (1+3). 32 | Hence the sum is 15 (0+1+1+9+4). 33 | ''' 34 | ## Read input as specified in the question. 35 | ## Print output as specified in the question. 36 | ## Read input as specified in the question. 37 | ## Print output as specified in the question. 38 | def mergeSort(arr, n): 39 | temp_arr = [0]*n 40 | return _mergeSort(arr, temp_arr, 0, n-1) 41 | 42 | def _mergeSort(arr, temp_arr, left, right): 43 | 44 | inv_count = 0 45 | 46 | if left < right: 47 | 48 | mid = (left + right)//2 49 | inv_count = _mergeSort(arr, temp_arr, left, mid) 50 | inv_count += _mergeSort(arr, temp_arr, mid + 1, right) 51 | inv_count += merge(arr, temp_arr, left, mid, right) 52 | return inv_count 53 | 54 | def merge(arr, temp_arr, left, mid, right): 55 | i = left 56 | j = mid + 1 57 | k = left 58 | inv_count = 0 59 | 60 | while i <= mid and j <= right: 61 | 62 | 63 | 64 | if arr[i] < arr[j]: 65 | temp_arr[k] = arr[i] 66 | inv_count += (arr[i]*(right - j + 1)) 67 | k += 1 68 | i += 1 69 | else: 70 | temp_arr[k] = arr[j] 71 | k += 1 72 | j += 1 73 | 74 | while i <= mid: 75 | temp_arr[k] = arr[i] 76 | k += 1 77 | i += 1 78 | 79 | while j <= right: 80 | temp_arr[k] = arr[j] 81 | k += 1 82 | j += 1 83 | 84 | for loop_var in range(left, right + 1): 85 | arr[loop_var] = temp_arr[loop_var] 86 | 87 | return inv_count 88 | 89 | t = int(input()) 90 | for i in range(t): 91 | n = int(input()) 92 | arr = [int(x) for x in input().split()] 93 | print(mergeSort(arr, n)) -------------------------------------------------------------------------------- /searching_&_sorting_applications/taj_mahal_entry.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Taj Mahal is one of the seven wonders of the world. Aahad loves to travel places and wants to visit Taj Mahal. He visited Agra to view Taj Mahal. There is a ticketing system at Taj Mahal. There are total ‘n’ windows which provide the tickets to get entry into Taj Mahal. There are ‘Ai’ people already present at each window to get the tickets. Each window gives ticket to one person in one minute. Initially, Aahad stands in front of the first window. After each minute, if he didn’t get the ticket, he moves on to the next window to get the ticket. If he is at window 1, he will move to 2. If at 2nd, he will move to 3rd. If he is at last window, he will move to 1st again and so on. Find the window number at which he will get the ticket. 3 | Input Format: 4 | First line contains a single integer ‘n’ denoting the no. of windows. 5 | Next line contains ‘n’ space separated integers denoting the no. of people already standing in front of the ith window. (1 <= i <= n) 6 | Output Format: 7 | Print a single integer denoting the window number that Aahad will get ticket from. 8 | Constraints: 9 | 1 <= n <= 10^5 10 | 1 <= Ai <= 10^9 11 | Sample Input: 12 | 4 13 | 2 3 2 0 14 | Sample Output: 15 | 3 16 | Explanation: 17 | Aahad at Window 1: [2, 3, 2, 0] 18 | Aahad at Window 2: [1, 2, 1, 0] 19 | Aahad at Window 3: [0, 1, 0, 0] 20 | So, when Aahad is at window 3, he got zero people before him. Hence, he will get the ticket at window 3. 21 | */ 22 | #include 23 | using namespace std; 24 | 25 | int main() 26 | { 27 | int n; 28 | cin >> n; 29 | int arr[n]; 30 | for(int i = 0; i < n; i++) 31 | cin >> arr[i]; 32 | 33 | int ans[n]; 34 | for(int i = 0; i < n; i++){ 35 | int t = 0; 36 | t = (arr[i] - i)/n; 37 | if(arr[i] - i > 0){ 38 | if((arr[i] - i)%n == 0){ 39 | ans[i] = i + t * n; 40 | //cout << i << "me" << endl; 41 | } 42 | else{ 43 | ans[i] = i + (t + 1) * n; 44 | // cout << i << "me2" << endl; 45 | } 46 | } 47 | else{ 48 | ans[i] = i; 49 | } 50 | } 51 | int index = 0; 52 | 53 | for(int i = 1; i < n; i++) 54 | { 55 | // cout << ans[i] << endl; 56 | if(ans[i] < ans[index]) 57 | index = i; 58 | } 59 | 60 | cout << index + 1; 61 | return 0; 62 | } 63 | --------------------------------------------------------------------------------