├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── LICENSE ├── README.md ├── algorithms ├── bit_manipulation │ ├── flipping_bits.php │ ├── lonely_integer.php │ └── maximizing_xor.php ├── dynamic_programming │ └── the_maximum_subarray.cpp ├── graph_theory │ └── journey_to_the_moon.py ├── greedy │ └── marcs_cakewalk.php ├── implementation │ ├── absolute_permutation.cpp │ ├── apple_and_orange.cpp │ ├── between_two_sets.cpp │ ├── birthday_chocolate.cpp │ ├── bon_appetit.php │ ├── breaking_best_and_worst_records.cpp │ ├── cats_and_a_mouse.py │ ├── climbing_the_leaderboard.py │ ├── counting_valleys.py │ ├── day_of_the_programmer.py │ ├── designer_pdf_viewer.php │ ├── divisible_sum_pairs.php │ ├── drawing_book.php │ ├── eletronics_shop.py │ ├── extra_long_factorials.py │ ├── find_digits.py │ ├── grading_students.cpp │ ├── grading_students.py │ ├── jumping_on_the_clouds.php │ ├── jumping_on_the_clouds_revisited.py │ ├── kangaroo.cpp │ ├── migratory_birds.php │ ├── minimum_distances.php │ ├── minimum_swaps_2.py │ ├── picking_numbers.php │ ├── sock_merchant.php │ ├── the_grid_search.cpp │ ├── the_hurdle_race.php │ └── utopian_tree.php ├── searching │ └── ice_cream_parlor.php ├── sorting │ ├── big_sorting.php │ ├── counting_sort_1.php │ ├── insertion_sort_part_1.php │ └── intro_to_tutorial_challenges.php ├── strings │ ├── alternating_characters.py │ ├── ashton_and_string.cpp │ ├── caesar_cipher.php │ ├── camel_case.php │ ├── camel_case.py │ ├── hacker_rank_is_a_string.py │ ├── mars_exploration.php │ ├── pangrams.php │ ├── pangrams.py │ ├── string_construction.php │ ├── strong_password.py │ ├── super_reduced_string.php │ ├── two_characters.php │ ├── two_strings.go │ ├── two_strings.php │ └── two_strings.py └── warmup │ ├── a_very_big_sum.cpp │ ├── a_very_big_sum.py │ ├── birthday_cake_candles.cpp │ ├── birthday_cake_candles.php │ ├── compare_the_triplets.cpp │ ├── compare_the_triplets.py │ ├── diagonal_difference.cpp │ ├── mini_max_sum.cpp │ ├── mini_max_sum.php │ ├── plus_minus.cpp │ ├── plus_minus.py │ ├── simple_array_sum.cpp │ ├── simple_array_sum.py │ ├── solve_me_first.cpp │ ├── solve_me_first.py │ ├── staircase.cpp │ ├── staircase.py │ ├── time_conversion.cpp │ ├── time_conversion.php │ └── time_conversion.py ├── cracking_the_coding_interview ├── algorithms │ ├── dfs_connected_cell_in_a_grid.py │ ├── hash_tables_ice_cream_parlor.py │ ├── sorting_bubble_sort.py │ └── sorting_comparator.py ├── data_structures │ ├── arrays_left_rotation.cpp │ ├── arrays_left_rotation.py │ ├── hash_tables_ransom_note.py │ ├── heaps_find_the_running_median.py │ ├── linked_lists_detect_a_cycle.py │ ├── queues_a_tale_of_two_stacks.py │ ├── reverse_a_doubly_linked_list.cpp │ ├── stacks_balanced_brackets.py │ ├── strings_making_anagrams.py │ └── tries_contacts.py └── techniques_concepts │ ├── bit_manipulation_lonely_integer.py │ ├── dp_coin_change.py │ ├── recursion_davis_staircase.py │ ├── recursion_fibonacci_numbers.py │ └── time_complexity_primality.py ├── data_structures ├── arrays │ ├── 2d_array_ds.php │ ├── arrays_ds.php │ └── left_rotation.py └── trees │ └── is_binary_search_tree.py ├── functional_programming └── introduction │ ├── array_of_n_elements.clj │ ├── filter_array.clj │ ├── filter_positions_in_a_list.clj │ ├── hello_world.clj │ ├── hello_world_n_times.clj │ ├── list_length.clj │ ├── list_replication.clj │ ├── reverse_a_list.clj │ ├── solve_me_first_fp.clj │ ├── sum_of_odd_elements.clj │ └── update_list.clj ├── olx_code_and_the_curious └── sell_statistics_query_system.py ├── sql └── basic_select │ ├── employee_names.sql │ ├── employee_salaries.sql │ ├── higher_than_75_marks.sql │ ├── japanese_cities_attributes.sql │ ├── japanese_cities_names.sql │ ├── revising_the_select_query_i.sql │ ├── revising_the_select_query_ii.sql │ ├── select_all.sql │ ├── select_by_id.sql │ ├── weather_observation_station_1.sql │ ├── weather_observation_station_10.sql │ ├── weather_observation_station_11.sql │ ├── weather_observation_station_12.sql │ ├── weather_observation_station_3.sql │ ├── weather_observation_station_4.sql │ ├── weather_observation_station_5.sql │ ├── weather_observation_station_6.sql │ ├── weather_observation_station_7.sql │ ├── weather_observation_station_8.sql │ └── weather_observation_station_9.sql └── week_of_code_37 ├── simple_language.py └── the_average_rating_of_top_employees.cpp /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute? :thinking: 2 | 3 | ## First :open_mouth: 4 | Fork this repo and create a branch with the name of the solution, something like this: ```git checkout -b obsinqsob01-bubble```. 5 | Then commit and push :arrow_up:. 6 | Open a pull request and merge :smile: 7 | 8 | ## Directory and Name standard :pencil2: 9 | In this section you have to follow the next: 10 | * Same name of Hackerrank problem 11 | * Always lowercase 12 | * Directories according to Hackerrank hierarchy 13 | 14 | ## Standard docs :pencil: 15 | To doc your code follow this: 16 | * Always add the problem name in the list of solutions of this repo, in README.md 17 | * When adding an solution in a language that was not used yet, create the column to it. 18 | * Add your name to CONTRIBUTORS.md, sorted alphabetically. 19 | 20 | #### Happy Coding :computer: 21 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | This is a list of contributors. 3 | Every name is sorted in alphabetically. 4 | 5 | - [arielmikiabraham](https://github.com/arielmikiabraham) 6 | - [BhanukaUOM](https://github.com/BhanukaUOM) 7 | - [damcclean](https://github.com/damcclean) 8 | - [danhenriquesc](https://github.com/danhenriquesc) 9 | - [hundredrab](https://github.com/hundredrab) 10 | - [jackey8616](https://github.com/jackey8616) 11 | - [mateusguerra](https://github.com/mateusguerra) 12 | - [mirianashvili](https://github.com/mirianashvili) 13 | - [Obsinqsob01](https://github.com/Obsinqsob01) 14 | - [PyPatel](https://github.com/PyPatel) 15 | - [Remya Vava](https://github.com/remyapv) 16 | - [RitvijSrivastava](https://github.com/RitvijSrivastava) 17 | - [sbz](https://github.com/sbz) 18 | - [shaurya uppal](https://github.com/shauryauppal) 19 | - [Ubamba98](https://github.com/ubamba98) 20 | - [vinayak42](https://github.com/vinayak42) 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Daniel Henrique 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HackerRank 2 | 3 | A collection of solutions and explanations of Hackerrank.com problems in many languages. 4 | 5 | Solved problems of HackerRank. 6 | www.hackerrank.com 7 | 8 | # Contributions 9 | To see every contributors, please reference at [here](https://github.com/hackerrank/hackerrank/blob/master/CONTRIBUTORS.md). 10 | 11 | # Solutions 12 | 13 | ## Cracking the Coding Interview (DEPRECATED) 14 | https://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview 15 | 16 | 17 | **Data Structures** 18 | 19 | | Problem | Python3 | C++ | PHP | 20 | | :---------------------------- | :--: | :--: | :--: | 21 | | Arrays: Left Rotation | ✓ | ✓ | | 22 | | Strings: Making Anagrams | ✓ | | | 23 | | Hash Tables: Ransom Note | ✓ | | | 24 | | Linked Lists: Detect a Cycle | ✓ | | | 25 | | Stacks: Balanced Brackets | ✓ | | | 26 | | Queues: A Tale of Two Stacks | ✓ | | | 27 | | Tries: Contacts | ✓ | | | 28 | 29 | **Algorithms** 30 | 31 | | Problem | Python3 | C++ | PHP | 32 | | :---------------------------- | :--: | :--: | :--: | 33 | | Sorting: Bubble Sort | ✓ | | | 34 | | Sorting: Comparator | ✓ | | | 35 | | Hash Tables: Ice Cream Parlor | ✓ | | | 36 | | DFS: Connected Cell in a Grid | ✓ | | | 37 | | Minimum Swaps 2 | ✓ | | | 38 | 39 | **Techniques/Concepts** 40 | 41 | | Problem | Python3 | C++ | PHP | 42 | | :---------------------------- | :--: | :--: | :--: | 43 | | Time Complexity: Primality | ✓ | | | 44 | | Recursion: Fibonacci Numbers | ✓ | | | 45 | | Recursion: Davis' Staircase | ✓ | | | 46 | | DP: Coin Change | ✓ | | | 47 | | Bit Manipulation: Lonely Integer | ✓ | | | 48 | 49 | 50 | ## Contest: OLX - Code and the Curious 51 | https://www.hackerrank.com/contests/code-and-the-curious/challenges 52 | 53 | 54 | | Problem | Python3 | C++ | PHP | 55 | | :---------------------------- | :--: | :--: | :--: | 56 | | Sell Statistics Query System | ✓ | | | 57 | 58 | ## Contest: Week of Code 37 59 | | Problem | Python3 | C++ | PHP | 60 | | :---------------------------- | :--: | :--: | :--: | 61 | | The Average Rating of Top Employees | | ✓ | | 62 | | Simple Language | ✓ | | | 63 | 64 | ## Algorithms 65 | 66 | **Warmup** 67 | 68 | | Problem | Python3 | C++ | PHP | 69 | | :-- | :--: | :--: | :--: | 70 | | Solve Me First | ✓ | ✓ | | 71 | | Simple Array Sum | ✓ | ✓ | | 72 | | Compare the Triplets | ✓ | ✓ | | 73 | | A Very Big Sum | ✓ | ✓ | | 74 | | Diagonal Difference | | ✓ | | 75 | | Plus Minus | ✓ | ✓ | | 76 | | Staircase | ✓ | ✓ | | 77 | | Mini-Max Sum | |✓ | ✓ | 78 | | Birthday Cake Candles | |✓ | ✓ | 79 | | Time Conversion | ✓ | ✓| ✓ | 80 | 81 | 82 | **Implementation** 83 | 84 | | Problem | Python3 | C++ | PHP | 85 | | :-- | :--: | :--: | :--: | 86 | | Grading Students | ✓ | ✓ | | 87 | | Apple and Orange | | ✓ | | 88 | | Kangaroo | | ✓ | | 89 | | Between Two Sets | | ✓ | | 90 | | Breaking the Records | | ✓ | | 91 | | Birthday Chocolate | | ✓ | | 92 | | Divisible Sum Pairs | | | ✓ | 93 | | Migratory Birds | | | ✓ | 94 | | Day of the Programmer | ✓ | | | 95 | | Bon Appétit | | | ✓ | 96 | | Sock Merchant | | | ✓ | 97 | | Drawing Book | | | ✓ | 98 | | Counting Valleys | ✓ | | | 99 | | Electronics Shop | ✓ | | | 100 | | Cats and a Mouse | ✓ | | | 101 | | Picking Numbers | | | ✓ | 102 | | Climbing the Leaderboard | ✓ | | | 103 | | The Hurdle Race | | | ✓ | 104 | | Designer PDF Viewer | | | ✓ | 105 | | Utopian Tree | | | ✓ | 106 | | Jumping on the Clouds: Revisited | ✓ | | | 107 | | Find Digits | ✓ | | | 108 | | Extra Long Factorials | ✓ | | | 109 | | Jumping on the Clouds | | | ✓ | 110 | | Minimum Distances | | | ✓ | 111 | | The Grid Search | | ✓ | | 112 | | Absolute Permutation | | ✓ | | 113 | 114 | **Strings** 115 | 116 | | Problem | Python3 | C++ | PHP | Go | 117 | | :-- | :--: | :--: | :--: | :--: | 118 | | Super Reduced String | | | ✓ | | 119 | | CamelCase | ✓ | | ✓ | | 120 | | Strong Password | ✓ | | | | 121 | | Two Characters | | | ✓ | | 122 | | Caesar Cipher | | | ✓ | | 123 | | Mars Exploration | | | ✓ | | 124 | | HackerRank in a String! | ✓ | | | | 125 | | Pangrams | ✓ | | ✓ | | 126 | | Alternating Characters | ✓ | | | | 127 | | String Construction | | | ✓ | | 128 | | Ashton and String | | ✓ | | | 129 | | Two Strings | ✓ | | ✓ | ✓ | 130 | 131 | **Sorting** 132 | 133 | | Problem | Python3 | C++ | PHP | 134 | | :-- | :--: | :--: | :--: | 135 | | Big Sorting | | | ✓ | 136 | | Intro to Tutorial Challenges | | | ✓ | 137 | | Insertion Sort - Part 1 | | | ✓ | 138 | | Counting Sort 1 | | | ✓ | 139 | 140 | **Searching** 141 | 142 | | Problem | Python3 | C++ | PHP | 143 | | :-- | :--: | :--: | :--: | 144 | | Ice Cream Parlor | | | ✓ | 145 | 146 | **Graph Theory** 147 | 148 | | Problem | Python3 | C++ | PHP | 149 | | :-- | :--: | :--: | :--: | 150 | | Journey to the Moon | ✓ | | | 151 | 152 | **Greedy** 153 | 154 | | Problem | Python3 | C++ | PHP | 155 | | :-- | :--: | :--: | :--: | 156 | | Marc's Cakewalk | | | ✓ | 157 | 158 | **Dynamic Programming** 159 | 160 | | Problem | Python3 | C++ | PHP | 161 | | :-- | :--: | :--: | :--: | 162 | | The Maximum Subarray | | ✓ | | 163 | 164 | **Bit Manipulation** 165 | 166 | | Problem | Python3 | C++ | PHP | 167 | | :-- | :--: | :--: | :--: | 168 | | Lonely Integer | | | ✓ | 169 | | Maximizing XOR | | | ✓ | 170 | | Flipping bits | | | ✓ | 171 | 172 | ## Data Structures 173 | 174 | **Arrays** 175 | 176 | | Problem | Python3 | C++ | PHP | 177 | | :-- | :--: | :--: | :--: | 178 | | Arrays - DS | | | ✓ | 179 | | 2D Array - DS | | | ✓ | 180 | | Left Rotation | ✓ | | | 181 | | Is This a Binary Search Tree? | ✓ | | | 182 | 183 | **Linked Lists** 184 | 185 | | Problem | Python3 | C++ | PHP | 186 | | :-- | :--: | :--: | :--: | 187 | | Reverse a doubly linked list | | ✓ | | 188 | 189 | ## Functional Programming 190 | 191 | **Introduction** 192 | 193 | | Problem | Clojure | 194 | | :-- | :--: | 195 | | Solve Me First FP | ✓ | 196 | | Hello World | ✓ | 197 | | Hello World N Times | ✓ | 198 | | List Replication | ✓ | 199 | | Filter Array | ✓ | 200 | | Filter Positions in a List | ✓ | 201 | | Array Of N Elements | ✓ | 202 | | Reverse a List | ✓ | 203 | | Sum of Odd Elements | ✓ | 204 | | List Length | ✓ | 205 | | Update List | ✓ | 206 | | Evaluating e^x | ✓ | 207 | 208 | ## SQL 209 | 210 | **Basic Select** 211 | 212 | | Problem | MySQL | 213 | | :-- | :--: | 214 | | Revising the Select Query I | ✓ | 215 | | Revising the Select Query II | ✓ | 216 | | Select All | ✓ | 217 | | Select By ID | ✓ | 218 | | Japanese Cities' Attributes | ✓ | 219 | | Japanese Cities' Names | ✓ | 220 | | Weather Observation Station 1 | ✓ | 221 | | Weather Observation Station 3 | ✓ | 222 | | Weather Observation Station 4 | ✓ | 223 | | Weather Observation Station 5 | ✓ | 224 | | Weather Observation Station 6 | ✓ | 225 | | Weather Observation Station 7 | ✓ | 226 | | Weather Observation Station 8 | ✓ | 227 | | Weather Observation Station 9 | ✓ | 228 | | Weather Observation Station 10 | ✓ | 229 | | Weather Observation Station 11 | ✓ | 230 | | Weather Observation Station 12 | ✓ | 231 | | Higher Than 75 Marks | ✓ | 232 | | Employee Names | ✓ | 233 | | Employee Salaries | ✓ | 234 | -------------------------------------------------------------------------------- /algorithms/bit_manipulation/flipping_bits.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/bit_manipulation/lonely_integer.php: -------------------------------------------------------------------------------- 1 | $value){ 7 | if($value == 1) return $key; 8 | } 9 | } 10 | 11 | fscanf($handle, "%i",$n); 12 | $a_temp = fgets($handle); 13 | $a = explode(" ",$a_temp); 14 | $a = array_map('intval', $a); 15 | $result = lonelyinteger($a); 16 | echo $result . "\n"; 17 | 18 | ?> -------------------------------------------------------------------------------- /algorithms/bit_manipulation/maximizing_xor.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/the_maximum_subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void kadane(int *v, int n, int & x, int &y , int & max_total){ 6 | int max_atual; 7 | int xtemp; 8 | int i; 9 | max_atual = 0; 10 | max_total = -1; 11 | xtemp = 0; 12 | for(i=0;i max_total){ 19 | max_total = max_atual; 20 | x = xtemp; 21 | y = i; 22 | } 23 | } 24 | } 25 | 26 | int main() { 27 | int x,y,max,count; 28 | 29 | int T,C, v[200000]; 30 | cin >> T; 31 | while (T--){ 32 | cin >> C; 33 | count = 0; 34 | for(int i = 0; i> v[i]; 36 | if(v[i] > 0) count += v[i]; 37 | } 38 | if(count == 0){ 39 | count = v[0]; 40 | for(int i = 1; i count) count = v[i]; 42 | } 43 | cout << count << " " << count << endl; 44 | }else{ 45 | kadane(v,C,x,y,max); 46 | cout << max << " " << count << endl; 47 | } 48 | } 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/graph_theory/journey_to_the_moon.py: -------------------------------------------------------------------------------- 1 | def combination(n): 2 | return (n * (n - 1)) / 2 3 | 4 | 5 | def find_set(a): 6 | k = 0 7 | for it in l: 8 | if(a in it): 9 | return k 10 | k += 1 11 | 12 | 13 | (n, i) = (int(i) for i in input().strip().split()) 14 | l = [set([i]) for i in range(n)] 15 | 16 | for j in range(i): 17 | f = 0 18 | (a, b) = (int(i) for i in input().strip().split()) 19 | a = find_set(a) 20 | b = find_set(b) 21 | if(a != b): 22 | l[a] = l[a].union(l[b]) 23 | l.pop(b) 24 | 25 | m = combination(n) 26 | for it in l: 27 | m -= combination(len(it)) 28 | 29 | print(int(m)) 30 | -------------------------------------------------------------------------------- /algorithms/greedy/marcs_cakewalk.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/absolute_permutation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int solve(int n,int k){ 5 | if(k == 0){ 6 | for(int i = 1 ; i <= n ; i++){ 7 | cout << i << " "; 8 | } 9 | cout << endl; 10 | return 0; 11 | } 12 | 13 | if(n % (2 * k) == 0){ 14 | int t = k; 15 | for(int i = 1 ; i <= n ; i++){ 16 | cout << i + t << " "; 17 | if(i % k == 0){ 18 | t *= -1; 19 | } 20 | } 21 | cout << endl; 22 | return 0; 23 | } 24 | 25 | cout << -1 << endl; 26 | return 0; 27 | } 28 | 29 | int main(){ 30 | int t,n,k; 31 | cin >> t; 32 | while(t--){ 33 | cin >> n >> k; 34 | solve(n,k); 35 | } 36 | } -------------------------------------------------------------------------------- /algorithms/implementation/apple_and_orange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | int main(){ 8 | int s; 9 | int t; 10 | cin >> s >> t; 11 | int a; 12 | int b; 13 | cin >> a >> b; 14 | int m; 15 | int n; 16 | cin >> m >> n; 17 | int tot_apple = 0, tot_orange = 0; 18 | vector apple(m); 19 | for(int apple_i = 0;apple_i < m;apple_i++){ 20 | cin >> apple[apple_i]; 21 | if( (apple[apple_i]+a >= s) && (apple[apple_i]+a <= t)){ 22 | tot_apple++; 23 | } 24 | } 25 | vector orange(n); 26 | for(int orange_i = 0;orange_i < n;orange_i++){ 27 | cin >> orange[orange_i]; 28 | if( (orange[orange_i]+b >= s) && (orange[orange_i]+b <= t)){ 29 | tot_orange++; 30 | } 31 | } 32 | 33 | cout << tot_apple << endl << tot_orange << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /algorithms/implementation/between_two_sets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int getTotalX(vector a, vector b) { 6 | int tot = 0; 7 | 8 | if(b.front() % a.back() != 0) return 0; 9 | 10 | for(int i = a.back(); i <= b.front(); i += a.back()){ 11 | bool status = true; 12 | 13 | for(int j = 0; j < a.size(); j++){ 14 | if(i%a[j]){ 15 | status = false; 16 | break; 17 | } 18 | } 19 | 20 | if(status){ 21 | for(int j = 0; j < b.size(); j++){ 22 | if(b[j]%i){ 23 | status = false; 24 | break; 25 | } 26 | } 27 | } 28 | 29 | if(status) tot++; 30 | } 31 | 32 | return tot; 33 | } 34 | 35 | int main() { 36 | int n; 37 | int m; 38 | cin >> n >> m; 39 | vector a(n); 40 | for(int a_i = 0; a_i < n; a_i++){ 41 | cin >> a[a_i]; 42 | } 43 | vector b(m); 44 | for(int b_i = 0; b_i < m; b_i++){ 45 | cin >> b[b_i]; 46 | } 47 | int total = getTotalX(a, b); 48 | cout << total << endl; 49 | return 0; 50 | } -------------------------------------------------------------------------------- /algorithms/implementation/birthday_chocolate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int solve(int n, vector < int > s, int d, int m){ 6 | int alltot = 0; 7 | for(int i = 0; i < s.size() - m+1; i++){ 8 | int tot = 0; 9 | for(int j = 0; j < m; j++){ 10 | tot += s[i+j]; 11 | } 12 | 13 | if(tot == d) alltot++; 14 | } 15 | 16 | return alltot; 17 | } 18 | 19 | int main() { 20 | int n; 21 | cin >> n; 22 | vector s(n); 23 | for(int s_i = 0; s_i < n; s_i++){ 24 | cin >> s[s_i]; 25 | } 26 | int d; 27 | int m; 28 | cin >> d >> m; 29 | int result = solve(n, s, d, m); 30 | cout << result << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /algorithms/implementation/bon_appetit.php: -------------------------------------------------------------------------------- 1 | 18 | -------------------------------------------------------------------------------- /algorithms/implementation/breaking_best_and_worst_records.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector < int > getRecord(vector < int > s){ 6 | vector r; 7 | int bmin = 0, bmax = 0, min = s.front(), max = s.front(); 8 | 9 | for (int i = 1; i < s.size(); i++) 10 | { 11 | if(s[i] > max){ 12 | max = s[i]; bmax++; 13 | } 14 | 15 | if(s[i] < min){ 16 | min = s[i]; bmin++; 17 | } 18 | } 19 | 20 | r.push_back(bmax); 21 | r.push_back(bmin); 22 | 23 | return r; 24 | } 25 | 26 | int main() { 27 | int n; 28 | cin >> n; 29 | vector s(n); 30 | for(int s_i = 0; s_i < n; s_i++){ 31 | cin >> s[s_i]; 32 | } 33 | vector < int > result = getRecord(s); 34 | string separator = "", delimiter = " "; 35 | for(auto val: result) { 36 | cout<= scores[i]: 14 | i += 1 15 | else: 16 | results.append(len(scores) + 1 - i) 17 | break 18 | except: 19 | results.append(1) 20 | 21 | return results 22 | 23 | 24 | if __name__ == '__main__': 25 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 26 | scores_count = int(input()) 27 | scores = list(map(int, input().rstrip().split())) 28 | alice_count = int(input()) 29 | alice = list(map(int, input().rstrip().split())) 30 | result = climbingLeaderboard(scores, alice) 31 | fptr.write('\n'.join(map(str, result))) 32 | fptr.write('\n') 33 | fptr.close() 34 | -------------------------------------------------------------------------------- /algorithms/implementation/counting_valleys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def countingValleys(n, s): 5 | level = 0 6 | old_level = 0 7 | valleys = 0 8 | for step in s: 9 | old_level = level 10 | if step == 'D': 11 | level -= 1 12 | else: 13 | level += 1 14 | 15 | if level >= 0: 16 | if old_level < 0: 17 | valleys += 1 18 | 19 | return valleys 20 | 21 | 22 | if __name__ == "__main__": 23 | n = int(input().strip()) 24 | s = input().strip() 25 | result = countingValleys(n, s) 26 | print(result) 27 | -------------------------------------------------------------------------------- /algorithms/implementation/day_of_the_programmer.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def leapJulian(year): 5 | return year % 4 == 0 6 | 7 | 8 | def leapGregorian(year): 9 | return (year % 4 == 0 and year % 100 > 0) or year % 400 == 0 10 | 11 | 12 | def solve(year): 13 | if year >= 1919: 14 | if(leapGregorian(year)): 15 | return "12.09." + str(year) 16 | else: 17 | return "13.09." + str(year) 18 | 19 | elif year <= 1917: 20 | if(leapJulian(year)): 21 | return "12.09." + str(year) 22 | else: 23 | return "13.09." + str(year) 24 | else: 25 | return "26.09." + str(year) 26 | 27 | 28 | year = int(input().strip()) 29 | result = solve(year) 30 | print(result) 31 | -------------------------------------------------------------------------------- /algorithms/implementation/designer_pdf_viewer.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/divisible_sum_pairs.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/drawing_book.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/eletronics_shop.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def getMoneySpent(keyboards, drives, s): 5 | maxV = -1 6 | selectedKb = -1 7 | selectedD = -1 8 | for keyboard in keyboards: 9 | for drive in drives: 10 | if drive + keyboard <= s and drive + keyboard > maxV: 11 | maxV = drive + keyboard 12 | selectedD = drive 13 | selectedKb = keyboard 14 | 15 | maxKD = max(selectedD, selectedKb) 16 | minKD = min(selectedD, selectedKb) 17 | 18 | if maxV > -1: 19 | while maxV + maxKD <= maxV: 20 | maxV = maxV + maxKD 21 | 22 | while maxV + minKD <= maxV: 23 | maxV = maxV + minKD 24 | 25 | return maxV 26 | 27 | 28 | s, n, m = input().strip().split(' ') 29 | s, n, m = [int(s), int(n), int(m)] 30 | keyboards = list(map(int, input().strip().split(' '))) 31 | drives = list(map(int, input().strip().split(' '))) 32 | moneySpent = getMoneySpent(keyboards, drives, s) 33 | print(moneySpent) 34 | -------------------------------------------------------------------------------- /algorithms/implementation/extra_long_factorials.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def extraLongFactorials(n): 5 | if (n == 1): 6 | return 1 7 | else: 8 | return n * extraLongFactorials(n - 1) 9 | 10 | 11 | if __name__ == "__main__": 12 | n = int(input().strip()) 13 | print(extraLongFactorials(n)) 14 | -------------------------------------------------------------------------------- /algorithms/implementation/find_digits.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def findDigits(n): 5 | count = 0 6 | for c in str(n): 7 | if c != "0": 8 | count += not (n % int(c)) 9 | return count 10 | 11 | 12 | if __name__ == "__main__": 13 | t = int(input().strip()) 14 | for a0 in range(t): 15 | n = int(input().strip()) 16 | result = findDigits(n) 17 | print(result) 18 | -------------------------------------------------------------------------------- /algorithms/implementation/grading_students.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector < int > solve(vector < int > grades){ 7 | vector result; 8 | for(int i = 0; i < grades.size(); i++){ 9 | if(grades[i] < 38) result.push_back(grades[i]); 10 | else{ 11 | int dif = (floor(grades[i]/5) + 1)*5; 12 | if(dif - grades[i] < 3) 13 | result.push_back(dif); 14 | else 15 | result.push_back(grades[i]); 16 | } 17 | } 18 | return result; 19 | } 20 | 21 | int main() { 22 | int n; 23 | cin >> n; 24 | vector grades(n); 25 | for(int grades_i = 0; grades_i < n; grades_i++){ 26 | cin >> grades[grades_i]; 27 | } 28 | vector < int > result = solve(grades); 29 | for (ssize_t i = 0; i < result.size(); i++) { 30 | cout << result[i] << (i != result.size() - 1 ? "\n" : ""); 31 | } 32 | cout << endl; 33 | 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /algorithms/implementation/grading_students.py: -------------------------------------------------------------------------------- 1 | #Python3 solution for HackerRank problem - Grading Students 2 | 3 | def gradingStudents(grades): 4 | length = len(grades) 5 | result = [] 6 | 7 | for i in range(length): 8 | if grades[i]>37: 9 | if grades[i]%5 >= 3: 10 | grades[i] += (5 - grades[i]%5) 11 | 12 | result.append(grades[i]) 13 | 14 | return result 15 | 16 | if __name__ == '__main__': 17 | 18 | n = int(input()) 19 | grades = [] 20 | 21 | for _ in range(n): 22 | grades_item = int(input()) 23 | grades.append(grades_item) 24 | 25 | result = gradingStudents(grades) 26 | 27 | for _ in range(n): 28 | print(result[_]) -------------------------------------------------------------------------------- /algorithms/implementation/jumping_on_the_clouds.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/jumping_on_the_clouds_revisited.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def jumpingOnClouds(n, c, k): 5 | current = 0 6 | E = 100 7 | 8 | while (True): 9 | E -= 1 10 | current = (current + k) % n 11 | if (c[current] == 1): 12 | E -= 2 13 | 14 | if not current: 15 | break 16 | 17 | return E 18 | 19 | 20 | if __name__ == "__main__": 21 | n, k = input().strip().split(' ') 22 | n, k = [int(n), int(k)] 23 | c = list(map(int, input().strip().split(' '))) 24 | result = jumpingOnClouds(n, c, k) 25 | print(result) 26 | -------------------------------------------------------------------------------- /algorithms/implementation/kangaroo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string kangaroo(int x1, int v1, int x2, int v2) { 6 | int min, vmin, max, vmax; 7 | if(x1>x2){ 8 | min = x2; 9 | vmin = v2; 10 | max=x1; 11 | vmax=v1; 12 | }else{ 13 | min = x1; 14 | vmin = v1; 15 | max=x2; 16 | vmax=v2; 17 | } 18 | 19 | while(min < max){ 20 | min += vmin; 21 | max += vmax; 22 | } 23 | 24 | return (min == max) ? "YES" : "NO"; 25 | } 26 | 27 | int main() { 28 | int x1; 29 | int v1; 30 | int x2; 31 | int v2; 32 | cin >> x1 >> v1 >> x2 >> v2; 33 | string result = kangaroo(x1, v1, x2, v2); 34 | cout << result << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /algorithms/implementation/migratory_birds.php: -------------------------------------------------------------------------------- 1 | $value) return $key; 10 | } 11 | 12 | fscanf($handle, "%i",$n); 13 | $ar_temp = fgets($handle); 14 | $ar = explode(" ",$ar_temp); 15 | $ar = array_map('intval', $ar); 16 | $result = migratoryBirds($n, $ar); 17 | echo $result . "\n"; 18 | 19 | ?> -------------------------------------------------------------------------------- /algorithms/implementation/minimum_distances.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/minimum_swaps_2.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import random 4 | import re 5 | import sys 6 | 7 | n = int(input()) 8 | 9 | arr = list(map(int, input().rstrip().split())) 10 | 11 | numSwaps = 0 12 | i = 0 13 | while(i < len(arr)-1): 14 | if arr[i] != i+1: 15 | tmp = arr[i] 16 | arr[i], arr[tmp-1] = arr[tmp-1], arr[i] 17 | numSwaps += 1 18 | else: 19 | i += 1 20 | 21 | print(numSwaps) 22 | -------------------------------------------------------------------------------- /algorithms/implementation/picking_numbers.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/sock_merchant.php: -------------------------------------------------------------------------------- 1 | $value){ 8 | $tot += floor($value/2); 9 | } 10 | return $tot; 11 | } 12 | 13 | fscanf($handle, "%i",$n); 14 | $ar_temp = fgets($handle); 15 | $ar = explode(" ",$ar_temp); 16 | $ar = array_map('intval', $ar); 17 | $result = sockMerchant($n, $ar); 18 | echo $result . "\n"; 19 | 20 | ?> -------------------------------------------------------------------------------- /algorithms/implementation/the_grid_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string solve(vector a,vector b,int R,int r,int C,int c) { 7 | bool found = false; 8 | 9 | for(int i = 0 ; i <= R - r ; i++){ 10 | for(int j = 0 ; j <= C - c ; j++){ 11 | int p = 0,k = i; 12 | while(a[k].substr(j,c) == b[p].substr(0,c)){ 13 | if(k - i + 1 == b.size()){ 14 | found = true; 15 | break; 16 | } 17 | k++;p++; 18 | } 19 | } 20 | } 21 | 22 | if(found == true){ 23 | return "YES"; 24 | }else{ 25 | return "NO"; 26 | } 27 | } 28 | 29 | int main() { 30 | int t; 31 | cin >> t; 32 | while (t--) { 33 | int R, C, r, c; 34 | vector a; 35 | vector b; 36 | string s; 37 | cin >> R >> C; 38 | 39 | for (int i = 0; i < R; i++) { 40 | cin >> s; 41 | a.push_back(s); 42 | } 43 | 44 | cin >> r >> c; 45 | 46 | for (int i = 0; i < r; i++) { 47 | cin >> s; 48 | b.push_back(s); 49 | } 50 | 51 | cout << solve(a,b,R,r,C,c) << endl; 52 | } 53 | } -------------------------------------------------------------------------------- /algorithms/implementation/the_hurdle_race.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/implementation/utopian_tree.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/searching/ice_cream_parlor.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/sorting/big_sorting.php: -------------------------------------------------------------------------------- 1 | $b[$i]; 17 | } 18 | $i++; 19 | } 20 | }else{ 21 | return (strlen($a) > strlen($b)); 22 | } 23 | 24 | } 25 | 26 | usort($unsorted, "cmp"); 27 | echo(implode("\n",$unsorted)); 28 | 29 | ?> -------------------------------------------------------------------------------- /algorithms/sorting/counting_sort_1.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/sorting/insertion_sort_part_1.php: -------------------------------------------------------------------------------- 1 | 0; $i--){ 4 | $cur = $ar[$i]; 5 | $j = $i - 1; 6 | while($cur < $ar[$j]){ 7 | $ar[$j+1] = $ar[$j]; 8 | $j--; 9 | echo implode(" ", $ar)."\n"; 10 | } 11 | $ar[$j+1] = $cur; 12 | } 13 | echo implode(" ", $ar)."\n"; 14 | 15 | } 16 | $fp = fopen("php://stdin", "r"); 17 | fscanf($fp, "%d", $m); 18 | $ar = array(); 19 | $s=fgets($fp); 20 | $ar = explode(" ", $s); 21 | for($i=0;$i < count($ar);$ar[$i++]+=0); 22 | insertionSort($ar); 23 | ?> -------------------------------------------------------------------------------- /algorithms/sorting/intro_to_tutorial_challenges.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/alternating_characters.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def alternatingCharacters(s): 5 | i = 0 6 | for j in range(len(s) - 1): 7 | if s[j] == s[j + 1]: 8 | i += 1 9 | return i 10 | 11 | 12 | q = int(input().strip()) 13 | for a0 in range(q): 14 | s = input().strip() 15 | result = alternatingCharacters(s) 16 | print(result) 17 | -------------------------------------------------------------------------------- /algorithms/strings/ashton_and_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | for(int j=0; j> s >> k; 15 | 16 | int i; 17 | vector> vv; 18 | auto it = vv.begin(); 19 | for(char c='a'; c<= 'z' && k>0; ++c) 20 | { 21 | vv.clear(); 22 | for (int j = 0; j(j, s.length() - j)); 26 | } 27 | 28 | sort(vv.begin(), vv.end(), [&](pair &a, pair &b){return s.substr(a.first, a.second) < s.substr(b.first, b.second);}); 29 | 30 | for (it = vv.begin(); it != vv.end() && k >= 0; ++it) 31 | { 32 | i=1; 33 | while(it != vv.begin() && s[prev(it)->first+i-1] == s[it->first+i-1]) 34 | ++i; 35 | 36 | while(i <= it->second && k>0) 37 | k -= i++; 38 | } 39 | } 40 | cout << s[prev(it)->first + k + i-2] << '\n'; 41 | } 42 | return 0; 43 | } -------------------------------------------------------------------------------- /algorithms/strings/caesar_cipher.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/camel_case.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/camel_case.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def camelcase(s): 5 | return len(list(filter(lambda x: x, map(lambda x: x != x.lower(), s)))) + 1 6 | 7 | 8 | if __name__ == "__main__": 9 | s = input().strip() 10 | result = camelcase(s) 11 | print(result) 12 | -------------------------------------------------------------------------------- /algorithms/strings/hacker_rank_is_a_string.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def hackerrankInString(s): 5 | find = "hackerrank" 6 | i = 0 7 | 8 | for c in s: 9 | if find[i] == c: 10 | i += 1 11 | if i >= len(find): 12 | return("YES") 13 | 14 | return("NO") 15 | 16 | 17 | if __name__ == "__main__": 18 | q = int(input().strip()) 19 | for a0 in range(q): 20 | s = input().strip() 21 | result = hackerrankInString(s) 22 | print(result) 23 | -------------------------------------------------------------------------------- /algorithms/strings/mars_exploration.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/pangrams.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/pangrams.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import os 3 | 4 | 5 | def pangrams(s): 6 | return "{}pangram".format( 7 | "not " if (len(set(s.lower().replace(" ", ""))) != 26) else "" 8 | ) 9 | 10 | 11 | if __name__ == '__main__': 12 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 13 | s = input() 14 | result = pangrams(s) 15 | fptr.write(result + '\n') 16 | fptr.close() 17 | -------------------------------------------------------------------------------- /algorithms/strings/string_construction.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /algorithms/strings/strong_password.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | def minimumNumber(n, password): 5 | numbers = "0123456789" 6 | lower_case = "abcdefghijklmnopqrstuvwxyz" 7 | upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 8 | special_characters = "!@#$%^&*()-+" 9 | 10 | digit = 1 11 | lower = 1 12 | upper = 1 13 | special = 1 14 | 15 | for c in password: 16 | if c in numbers: 17 | digit = 0 18 | if c in lower_case: 19 | lower = 0 20 | if c in upper_case: 21 | upper = 0 22 | if c in special_characters: 23 | special = 0 24 | 25 | missing = digit + lower + upper + special 26 | 27 | return max(missing, 6 - len(password)) 28 | 29 | 30 | if __name__ == "__main__": 31 | n = int(input().strip()) 32 | password = input().strip() 33 | answer = minimumNumber(n, password) 34 | print(answer) 35 | -------------------------------------------------------------------------------- /algorithms/strings/super_reduced_string.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/two_characters.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/strings/two_strings.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "os" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | // Complete the twoStrings function below. 13 | func twoStrings(s1 string, s2 string) string { 14 | if strings.ContainsAny(s1, s2) || strings.ContainsAny(s2, s1) { 15 | return "YES" 16 | } 17 | return "NO" 18 | } 19 | 20 | func main() { 21 | reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024) 22 | 23 | stdout, err := os.Create(os.Getenv("OUTPUT_PATH")) 24 | checkError(err) 25 | 26 | defer stdout.Close() 27 | 28 | writer := bufio.NewWriterSize(stdout, 1024 * 1024) 29 | 30 | qTemp, err := strconv.ParseInt(readLine(reader), 10, 64) 31 | checkError(err) 32 | q := int32(qTemp) 33 | 34 | for qItr := 0; qItr < int(q); qItr++ { 35 | s1 := readLine(reader) 36 | 37 | s2 := readLine(reader) 38 | 39 | result := twoStrings(s1, s2) 40 | 41 | fmt.Fprintf(writer, "%s\n", result) 42 | } 43 | 44 | writer.Flush() 45 | } 46 | 47 | func readLine(reader *bufio.Reader) string { 48 | str, _, err := reader.ReadLine() 49 | if err == io.EOF { 50 | return "" 51 | } 52 | 53 | return strings.TrimRight(string(str), "\r\n") 54 | } 55 | 56 | func checkError(err error) { 57 | if err != nil { 58 | panic(err) 59 | } 60 | } -------------------------------------------------------------------------------- /algorithms/strings/two_strings.php: -------------------------------------------------------------------------------- 1 | 0: 9 | return "YES" 10 | return "NO" 11 | 12 | 13 | if __name__ == '__main__': 14 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 15 | 16 | q = int(input()) 17 | 18 | for q_itr in range(q): 19 | s1 = input() 20 | 21 | s2 = input() 22 | 23 | result = twoStrings(s1, s2) 24 | 25 | fptr.write(result + '\n') 26 | 27 | fptr.close() 28 | -------------------------------------------------------------------------------- /algorithms/warmup/a_very_big_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main(){ 7 | int n; 8 | long long int sum = 0; 9 | cin >> n; 10 | vector arr(n); 11 | for(int arr_i = 0;arr_i < n;arr_i++){ 12 | cin >> arr[arr_i]; 13 | sum += arr[arr_i]; 14 | } 15 | 16 | cout << sum; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /algorithms/warmup/a_very_big_sum.py: -------------------------------------------------------------------------------- 1 | print(sum([int(input()) for i in range(int(input()))])) 2 | -------------------------------------------------------------------------------- /algorithms/warmup/birthday_cake_candles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int birthdayCakeCandles(unsigned long int n, vector ar) { 6 | sort(ar.begin(),ar.end()); 7 | unsigned long int x=0; 8 | for(long int ar_i = n-1; ar_i > -1; ar_i--){ 9 | if(ar[n-1]==ar[ar_i]) x++; 10 | else break; 11 | } 12 | return x; 13 | } 14 | 15 | int main() { 16 | unsigned long int n; 17 | cin >> n; 18 | vector ar(n); 19 | for(unsigned long int ar_i = 0; ar_i < n; ar_i++){ 20 | cin >> ar[ar_i]; 21 | } 22 | unsigned long int result = birthdayCakeCandles(n, ar); 23 | cout << result << endl; 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /algorithms/warmup/birthday_cake_candles.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/warmup/compare_the_triplets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int a0; 7 | int a1; 8 | int a2; 9 | cin >> a0 >> a1 >> a2; 10 | int b0; 11 | int b1; 12 | int b2; 13 | cin >> b0 >> b1 >> b2; 14 | 15 | int p1 = 0, p2 = 0; 16 | if(a0>b0) p1++; 17 | else if(b0>a0) p2++; 18 | 19 | if(a1>b1) p1++; 20 | else if(b1>a1) p2++; 21 | 22 | if(a2>b2) p1++; 23 | else if(b2>a2) p2++; 24 | 25 | cout << p1 << " " << p2; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/warmup/compare_the_triplets.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def solve(a0, a1, a2, b0, b1, b2): 7 | # Complete this function 8 | a = [a0, a1, a2] 9 | b = [b0, b1, b2] 10 | res = [0, 0] 11 | for i in range(3): 12 | if(a[i] > b[i]): 13 | res[0] += 1 14 | if(a[i] < b[i]): 15 | res[1] += 1 16 | return res 17 | 18 | 19 | a0, a1, a2 = input().strip().split(' ') 20 | a0, a1, a2 = [int(a0), int(a1), int(a2)] 21 | b0, b1, b2 = input().strip().split(' ') 22 | b0, b1, b2 = [int(b0), int(b1), int(b2)] 23 | result = solve(a0, a1, a2, b0, b1, b2) 24 | print(" ".join(map(str, result))) 25 | -------------------------------------------------------------------------------- /algorithms/warmup/diagonal_difference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int n; 7 | int s1=0,s2=0; 8 | cin >> n; 9 | vector< vector > a(n,vector(n)); 10 | for(int a_i = 0;a_i < n;a_i++){ 11 | for(int a_j = 0;a_j < n;a_j++){ 12 | cin >> a[a_i][a_j]; 13 | 14 | if(a_i == a_j) s1+=a[a_i][a_j]; 15 | if(a_i == n-1-a_j) s2+=a[a_i][a_j]; 16 | 17 | } 18 | } 19 | 20 | cout << abs(s1-s2); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/warmup/mini_max_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void miniMaxSum(vector arr) { 6 | sort(arr.begin(), arr.end()); 7 | cout< arr(5); 12 | for(int arr_i = 0; arr_i < 5; arr_i++){ 13 | cin >> arr[arr_i]; 14 | } 15 | miniMaxSum(arr); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /algorithms/warmup/mini_max_sum.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/warmup/plus_minus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main(){ 7 | int n; 8 | cin >> n; 9 | int p=0, neg=0, z=0; 10 | vector arr(n); 11 | for(int arr_i = 0;arr_i < n;arr_i++){ 12 | cin >> arr[arr_i]; 13 | if (arr[arr_i] > 0) 14 | p++; 15 | else if (arr[arr_i] == 0) 16 | z++; 17 | else if (arr[arr_i] < 0) 18 | neg++; 19 | } 20 | cout << fixed; 21 | cout.precision(6); 22 | cout << ((float)p/(float)n) << endl << ((float)neg/(float)n) << endl << ((float)z/(float)n); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /algorithms/warmup/plus_minus.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the plusMinus function below. 10 | def plusMinus(arr): 11 | 12 | n = len(arr) 13 | 14 | neg = pos = zero = 0 15 | for i in arr: 16 | if i == 0: 17 | zero+=1 18 | elif i>0: 19 | pos+=1 20 | elif i<0: 21 | neg+=1 22 | 23 | print("%.6f" % ((pos/n))) 24 | print("%.6f" % ((neg/n))) 25 | print("%.6f" % ((zero/n))) 26 | 27 | if __name__ == '__main__': 28 | n = int(input()) 29 | 30 | arr = list(map(int, input().rstrip().split())) 31 | 32 | plusMinus(arr) 33 | -------------------------------------------------------------------------------- /algorithms/warmup/simple_array_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int n, sum = 0; 7 | cin >> n; 8 | vector arr(n); 9 | for(int arr_i = 0;arr_i < n;arr_i++){ 10 | cin >> arr[arr_i]; 11 | sum += arr[arr_i]; 12 | } 13 | 14 | cout << sum; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /algorithms/warmup/simple_array_sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | import os 3 | 4 | 5 | def simpleArraySum(ar): 6 | return sum(ar) 7 | 8 | 9 | if __name__ == '__main__': 10 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 11 | ar_count = int(input()) 12 | ar = list(map(int, input().rstrip().split())) 13 | result = simpleArraySum(ar) 14 | fptr.write(str(result) + '\n') 15 | fptr.close() 16 | -------------------------------------------------------------------------------- /algorithms/warmup/solve_me_first.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int a, b; 6 | cin >> a >> b; 7 | cout << a+b << endl; 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /algorithms/warmup/solve_me_first.py: -------------------------------------------------------------------------------- 1 | print(int(input()) + int(input())) 2 | -------------------------------------------------------------------------------- /algorithms/warmup/staircase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main(){ 6 | int n, j; 7 | cin >> n; 8 | 9 | for(int i = 1; i<=n; i++){ 10 | for (j=0; j<(n-i);j++) cout<<" "; 11 | for (j;j 2 | 3 | using namespace std; 4 | 5 | string timeConversion(string s) { 6 | if(s[s.length()-2]=='P'){ 7 | if(s[1]=='2' && s[0]=='1'){ 8 | s.erase(s.begin()+8);s.erase(s.begin()+8); 9 | return s; 10 | } 11 | int time=((int)s[0]-48)*10+(int)s[1]-48+12; 12 | if(time==24) time=00; 13 | s[0] = time/10+48; 14 | s[1] = time%10+48; 15 | 16 | s.erase(s.begin()+8);s.erase(s.begin()+8); 17 | return s; 18 | } 19 | else{ 20 | if(s[1]=='2' && s[0]=='1') { 21 | s[1]='0'; 22 | s[0]='0'; 23 | } 24 | s.erase(s.begin()+8);s.erase(s.begin()+8); 25 | return s; 26 | } 27 | } 28 | 29 | int main() { 30 | string s; 31 | cin >> s; 32 | string result = timeConversion(s); 33 | cout << result << endl; 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /algorithms/warmup/time_conversion.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/warmup/time_conversion.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def timeConversion(s): 6 | if s.endswith("AM"): 7 | s = s.strip("AM") 8 | h, m, ss = s.split(":") 9 | if int(h) == 12: 10 | h = int(0) 11 | return "{:02}:{}:{}".format(int(h), m, ss) 12 | else: 13 | s = s.strip("PM") 14 | h, m, ss = s.split(":") 15 | if int(h) == 12: 16 | h = int(h) 17 | else: 18 | h = (int(h) + 12) % 24 19 | return "{:02}:{}:{}".format(h, m, ss) 20 | 21 | s = input().strip() 22 | result = timeConversion(s) 23 | print(result) 24 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/algorithms/dfs_connected_cell_in_a_grid.py: -------------------------------------------------------------------------------- 1 | def dfs(graph, start): 2 | visited, stack = set(), [start] 3 | while stack: 4 | vertex = stack.pop() 5 | if vertex not in visited: 6 | visited.add(vertex) 7 | stack.extend(graph[vertex] - visited) 8 | return visited 9 | 10 | 11 | def make_graph_alias(i, j): 12 | return '{}_{}'.format(i, j) 13 | 14 | 15 | def getBiggestRegion(grid): 16 | graph = {} 17 | 18 | for i, line in enumerate(grid): 19 | for j, value in enumerate(line): 20 | if value: 21 | connections = [] 22 | 23 | for k in [-1, 0, 1]: 24 | for l in [-1, 0, 1]: 25 | try: 26 | if (k != 0 or l != 0) and (i + k) >=0 and (j + l) >=0 and grid[i + k][j + l]: 27 | connections.append(make_graph_alias(i + k, j + l)) 28 | except: 29 | pass 30 | 31 | graph.update({make_graph_alias(i, j): set(connections)}) 32 | 33 | longest = -1 34 | for i, line in enumerate(grid): 35 | for j, value in enumerate(line): 36 | if value: 37 | longest = max(longest, len(dfs(graph, make_graph_alias(i, j)))) 38 | return longest 39 | 40 | 41 | n = int(input().strip()) 42 | m = int(input().strip()) 43 | grid = [] 44 | for grid_i in range(n): 45 | grid_t = list(map(int, input().strip().split(' '))) 46 | grid.append(grid_t) 47 | 48 | print(getBiggestRegion(grid)) 49 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/algorithms/hash_tables_ice_cream_parlor.py: -------------------------------------------------------------------------------- 1 | def solve(arr, money): 2 | htable = {} 3 | 4 | for i, value in enumerate(arr, 1): 5 | if value in htable: 6 | htable[value].append(i) 7 | else: 8 | htable[value] = [i] 9 | 10 | arr = sorted(arr) 11 | 12 | init = 0 13 | end = len(arr) - 1 14 | 15 | while init <= end: 16 | while arr[init] + arr[end] > money: 17 | end -= 1 18 | 19 | if arr[init] + arr[end] == money: 20 | s1, s2 = htable[arr[init]].pop(0), htable[arr[end]].pop() 21 | print(min(s1, s2), max(s1, s2)) 22 | break 23 | 24 | init += 1 25 | end = len(arr) - 1 26 | 27 | 28 | if __name__ == "__main__": 29 | t = int(input().strip()) 30 | for a0 in range(t): 31 | money = int(input().strip()) 32 | n = int(input().strip()) 33 | arr = list(map(int, input().strip().split(' '))) 34 | solve(arr, money) 35 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/algorithms/sorting_bubble_sort.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | a = list(map(int, input().strip().split(' '))) 3 | 4 | swaps = 0 5 | for i in range(n): 6 | for j in range(n - 1): 7 | if(a[j] > a[j + 1]): 8 | a[j], a[j + 1] = a[j + 1], a[j] 9 | swaps += 1 10 | 11 | print('Array is sorted in {} swaps.'.format(swaps)) 12 | print('First Element: {}'.format(a.pop(0))) 13 | print('Last Element: {}'.format(a.pop())) 14 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/algorithms/sorting_comparator.py: -------------------------------------------------------------------------------- 1 | from functools import cmp_to_key 2 | 3 | 4 | class Player: 5 | def __init__(self, name, score): 6 | self.name = name 7 | self.score = score 8 | 9 | def __repr__(self): 10 | return str(self.score) 11 | 12 | def comparator(a, b): 13 | if (a.score != b.score): 14 | return (int(b.score) - int(a.score)) 15 | else: 16 | return -1 if a.name < b.name else 1 17 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/arrays_left_rotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int n, k; 8 | cin >> n >> k; 9 | vector a(n); 10 | 11 | for(int i = 0;i < n;++i) cin >> a[i]; 12 | rotate(a.begin(),a.begin()+k,a.end()); 13 | for(const auto& e : a) cout << e << " "; 14 | cout << endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/arrays_left_rotation.py: -------------------------------------------------------------------------------- 1 | _, k = list(map(int, input().strip().split(' '))) 2 | a = list(input().strip().split(' ')) 3 | 4 | result = a[k:] + a[:k] 5 | print(' '.join(result)) 6 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/hash_tables_ransom_note.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def ransom_note(magazine, ransom): 5 | c_m = Counter(magazine) 6 | c_r = Counter(ransom) 7 | 8 | for word in c_r.keys(): 9 | if c_r.get(word, 0) > c_m.get(word, 0): 10 | return False 11 | 12 | return True 13 | 14 | 15 | m, n = map(int, input().strip().split(' ')) 16 | magazine = input().strip().split(' ') 17 | ransom = input().strip().split(' ') 18 | answer = ransom_note(magazine, ransom) 19 | if(answer): 20 | print("Yes") 21 | else: 22 | print("No") 23 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/heaps_find_the_running_median.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | number = '' 3 | counter = 1 4 | left = None 5 | right = None 6 | 7 | def __init__(self, number): 8 | self.number = number 9 | 10 | def add_counter(self, count): 11 | self.counter += count 12 | 13 | def __str__(self): 14 | return '(Number: {} - Counter: {} - Left: {} - Right: {})'.format(self.number, self.counter, self.left, self.right) 15 | 16 | __repr__ = __str__ 17 | 18 | 19 | n = int(input().strip()) 20 | number = int(input().strip()) 21 | 22 | root = Node(number) 23 | 24 | 25 | for i in range(n-1): 26 | number = int(input().strip()) 27 | 28 | cur_node = root 29 | while cur_node is not None: 30 | previous_node = cur_node 31 | 32 | if number >= cur_node.number: 33 | dir = 'right' 34 | else: 35 | dir = 'left' 36 | 37 | cur_node.add_counter(1) 38 | cur_node = getattr(cur_node, dir) 39 | 40 | setattr(previous_node, dir, Node(number)) 41 | 42 | print(root) 43 | # c = root 44 | # find = (i + 1) // 2 45 | # left = 0 46 | 47 | # while True: 48 | # l = c.get('l', {}).get('c', 0) 49 | # r = c.get('r', {}).get('c', 0) 50 | # print(c) 51 | # print(find, l, r) 52 | # if l >= find: 53 | # c = c.get('l') 54 | # elif r > find: 55 | # left += l 56 | # c = c.get('r') 57 | 58 | # if left == find - 1 or left == find: 59 | # break 60 | 61 | # print(find, left, c) 62 | 63 | 64 | #print('{:.1f}'.format(o_c.get('n'))) 65 | 66 | from heapq import heappush, heappop 67 | 68 | n = int(input().strip()) 69 | heaps = [[] for _ in range(n)] 70 | 71 | for i in range(n): 72 | number = int(input().strip()) 73 | median = 0 74 | 75 | for j in range(i, n): 76 | heappush(heaps[j], number) 77 | 78 | if (i + 1) % 2: 79 | needed = (i + 1) // 2 + 1 80 | for j in range(needed): 81 | median = heappop(heaps[i]) 82 | 83 | else: 84 | needed = (i + 1) // 2 85 | for j in range(needed): 86 | median = heappop(heaps[i]) 87 | 88 | median += heappop(heaps[i]) 89 | median /= 2 90 | 91 | print('{:.1f}'.format(median)) 92 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/linked_lists_detect_a_cycle.py: -------------------------------------------------------------------------------- 1 | def has_cycle(head): 2 | nodes = [] 3 | while head is not None: 4 | if head.data in nodes: 5 | return True 6 | 7 | nodes.append(head.data) 8 | 9 | head = head.next 10 | 11 | return False 12 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/queues_a_tale_of_two_stacks.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def peek(self): 6 | return self.items[0] 7 | 8 | def pop(self): 9 | self.items.pop(0) 10 | 11 | def put(self, value): 12 | self.items.append(value) 13 | 14 | 15 | queue = MyQueue() 16 | t = int(input()) 17 | for line in range(t): 18 | values = map(int, input().split()) 19 | values = list(values) 20 | if values[0] == 1: 21 | queue.put(values[1]) 22 | elif values[0] == 2: 23 | queue.pop() 24 | else: 25 | print(queue.peek()) 26 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/reverse_a_doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // Complete the reverse function below. 2 | 3 | /* 4 | * For your reference: 5 | * 6 | * DoublyLinkedListNode { 7 | * int data; 8 | * DoublyLinkedListNode* next; 9 | * DoublyLinkedListNode* prev; 10 | * }; 11 | * 12 | */ 13 | DoublyLinkedListNode* reverse(DoublyLinkedListNode* head) { 14 | DoublyLinkedListNode* ptr = head, *next, *prev = head->prev; 15 | while(ptr) 16 | { 17 | next = ptr->next; 18 | ptr->next = prev; 19 | ptr->prev = next; 20 | prev = ptr; 21 | ptr = next; 22 | } 23 | return prev; 24 | } 25 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/stacks_balanced_brackets.py: -------------------------------------------------------------------------------- 1 | def is_matched(expression): 2 | ok = ['()', '[]', '{}'] 3 | 4 | for i in range(75): 5 | for item in ok: 6 | expression = expression.replace(item, '') 7 | 8 | return len(expression) == 0 9 | 10 | 11 | t = int(input().strip()) 12 | for a0 in range(t): 13 | expression = str(input()) 14 | if is_matched(expression) is True: 15 | print("YES") 16 | else: 17 | print("NO") 18 | 19 | ################################################################################################# 20 | # A correct stack approach would be the below, but, that approach have a problem with timeout # 21 | ################################################################################################# 22 | 23 | # MAPPER = { 24 | # '}': '{', 25 | # ']': '[', 26 | # ')': '(', 27 | # } 28 | 29 | # OPENING_BRACKETS = MAPPER.values() 30 | # CLOSING_BRACKETS = MAPPER.keys() 31 | 32 | 33 | # def is_matched(expression): 34 | # if len(expression) % 2: 35 | # return False 36 | 37 | # stack = [] 38 | # for bracket in expression: 39 | # if bracket in OPENING_BRACKETS: 40 | # stack.append(bracket) 41 | # else: 42 | # last_item = stack.pop() 43 | 44 | # if last_item != MAPPER[bracket]: 45 | # return False 46 | 47 | # return len(stack) == 0 48 | 49 | 50 | # t = int(input().strip()) 51 | # for a0 in range(t): 52 | # expression = input().strip() 53 | # if is_matched(expression) is True: 54 | # print("YES") 55 | # else: 56 | # print("NO") 57 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/strings_making_anagrams.py: -------------------------------------------------------------------------------- 1 | import string 2 | from collections import Counter 3 | 4 | 5 | def number_needed(a, b): 6 | letters = list(string.ascii_lowercase) 7 | 8 | a_freq = Counter(a.strip()) 9 | b_freq = Counter(b.strip()) 10 | 11 | count = 0 12 | for letter in letters: 13 | count += abs(a_freq.get(letter, 0) - b_freq.get(letter, 0)) 14 | 15 | return count 16 | 17 | 18 | a = input().strip() 19 | b = input().strip() 20 | 21 | print(number_needed(a, b)) 22 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/data_structures/tries_contacts.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | 3 | contacts = {} 4 | 5 | for a0 in range(n): 6 | op, contact = input().strip().split(' ') 7 | 8 | if op == 'add': 9 | for i in range(len(contact) + 1): 10 | suffix = contact[:i] 11 | if suffix in contacts: 12 | contacts[suffix] += 1 13 | else: 14 | contacts[suffix] = 1 15 | else: 16 | print(contacts.get(contact, 0)) 17 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/techniques_concepts/bit_manipulation_lonely_integer.py: -------------------------------------------------------------------------------- 1 | def lonely_integer(a): 2 | bits = [0 for _ in range(100)] 3 | 4 | for i in a: 5 | bits[i] ^= i 6 | 7 | return list(filter(lambda x: x, bits)).pop() 8 | 9 | 10 | n = int(input().strip()) 11 | a = [int(a_temp) for a_temp in input().strip().split(' ')] 12 | print(lonely_integer(a)) 13 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/techniques_concepts/dp_coin_change.py: -------------------------------------------------------------------------------- 1 | #Dynamic Programming 2 | n, m = input().strip().split(' ') 3 | n, m = [int(n), int(m)] 4 | coins = [int(coins_temp) for coins_temp in input().strip().split(' ')] 5 | coins = [0] + coins 6 | 7 | T = [[-1 for _ in range(n + 1)] for _ in range(m + 1)] 8 | 9 | for p in range(1, m + 1): 10 | T[p][0] = 1 11 | for i in range(1, n + 1): 12 | tot = 0 13 | for k in range(1, p + 1): 14 | if i - coins[k] >= 0: 15 | tot += T[k][i - coins[k]] 16 | T[p][i] = tot 17 | 18 | print(T[m][n]) 19 | 20 | 21 | # Recursive with memoization 22 | n, m = input().strip().split(' ') 23 | n, m = [int(n), int(m)] 24 | coins = [int(coins_temp) for coins_temp in input().strip().split(' ')] 25 | coins = [0] + sorted(coins) 26 | 27 | memo = [[-1 for _ in range(275)] for _ in range(55)] 28 | 29 | 30 | def charge(m, n): 31 | if n < 0 or m == 0: 32 | return 0 33 | elif n == 0: 34 | return 1 35 | else: 36 | tot = 0 37 | i = 1 38 | while i <= m: 39 | t = n - coins[i] 40 | if memo[i][t] == -1: 41 | memo[i][t] = charge(i, t) 42 | 43 | tot += memo[i][t] 44 | i += 1 45 | return tot 46 | 47 | 48 | print(charge(m, n)) 49 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/techniques_concepts/recursion_davis_staircase.py: -------------------------------------------------------------------------------- 1 | memo = {1: 1, 2: 2, 3: 4} 2 | 3 | 4 | def climb(n): 5 | if n == 1: 6 | return 1 7 | elif n == 2: 8 | return 2 9 | elif n == 3: 10 | return 4 11 | else: 12 | c = 0 13 | 14 | for i in [1, 2, 3]: 15 | t = memo.get(n - i) 16 | if not t: 17 | memo[n - 1] = climb(n - 1) 18 | 19 | c += memo.get(n - i) 20 | 21 | return c 22 | 23 | 24 | s = int(input().strip()) 25 | for a0 in range(s): 26 | n = int(input().strip()) 27 | 28 | print(climb(n)) 29 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/techniques_concepts/recursion_fibonacci_numbers.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n <= 1: 3 | return n 4 | else: 5 | return fibonacci(n - 1) + fibonacci(n - 2) 6 | 7 | 8 | n = int(input()) 9 | print(fibonacci(n)) 10 | -------------------------------------------------------------------------------- /cracking_the_coding_interview/techniques_concepts/time_complexity_primality.py: -------------------------------------------------------------------------------- 1 | from math import sqrt, floor 2 | 3 | 4 | def is_prime(n): 5 | if n <= 1: 6 | return False 7 | elif n == 2: 8 | return True 9 | elif not n % 2 or not n % 3: 10 | return False 11 | else: 12 | r = True 13 | 14 | for i in range(5, floor(sqrt(n)) + 1, 2): 15 | if not n % i: 16 | r = False 17 | 18 | return r 19 | 20 | 21 | p = int(input().strip()) 22 | for a0 in range(p): 23 | n = int(input().strip()) 24 | 25 | print('{}'.format('Prime' if is_prime(n) else 'Not prime')) 26 | -------------------------------------------------------------------------------- /data_structures/arrays/2d_array_ds.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/arrays/arrays_ds.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /data_structures/arrays/left_rotation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | def array_left_rotation(a, n, d): 4 | return a if n == d else a[d:] + a[:d] 5 | 6 | n, d = map(int, input().strip().split(' ')) 7 | a = list(map(int, input().strip().split(' '))) 8 | result = array_left_rotation(a, n, d) 9 | print(*result, sep=' ') 10 | -------------------------------------------------------------------------------- /data_structures/trees/is_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | 4 | class node: 5 | def __init__(self, data): 6 | self.data = data 7 | self.left = None 8 | self.right = None 9 | 10 | 11 | def in_order_array(root, arr): 12 | if root.left is not None: 13 | in_order_array(root.left, arr) 14 | arr.append(root.data) 15 | if root.right is not None: 16 | in_order_array(root.right, arr) 17 | 18 | return arr 19 | 20 | 21 | def checkBST(root): 22 | array = in_order_array(root, []) 23 | size = len(array) 24 | for i in range(size - 1): 25 | if array[i + 1] <= array[i]: 26 | return False 27 | 28 | return True 29 | -------------------------------------------------------------------------------- /functional_programming/introduction/array_of_n_elements.clj: -------------------------------------------------------------------------------- 1 | (fn[n] 2 | (range n) 3 | ) -------------------------------------------------------------------------------- /functional_programming/introduction/filter_array.clj: -------------------------------------------------------------------------------- 1 | (use '[clojure.string :only (split triml)]) 2 | 3 | ( 4 | let [ 5 | n_t (read-line) 6 | n (Integer/parseInt n_t) 7 | ] 8 | 9 | ( 10 | loop [a0 n] 11 | (when (> a0 0) 12 | ( 13 | let [ 14 | x_t (read-line) 15 | x (Float/parseFloat x_t) 16 | ] 17 | 18 | (println 19 | (format "%.4f" 20 | (reduce + 21 | (map 22 | (fn[i] (/ (reduce * (repeat i x)) (reduce * (range 1 (+ i 1))))) 23 | (range 10) 24 | ) 25 | ) 26 | ) 27 | ) 28 | ) 29 | (recur (- a0 1) ) ) 30 | ) 31 | 32 | ) 33 | -------------------------------------------------------------------------------- /functional_programming/introduction/filter_positions_in_a_list.clj: -------------------------------------------------------------------------------- 1 | (fn[lst] 2 | (take-nth 2 (rest lst)) 3 | ) -------------------------------------------------------------------------------- /functional_programming/introduction/hello_world.clj: -------------------------------------------------------------------------------- 1 | (print "Hello World") -------------------------------------------------------------------------------- /functional_programming/introduction/hello_world_n_times.clj: -------------------------------------------------------------------------------- 1 | (defn hello_word_n_times[n] 2 | (when (> n 0) 3 | (println "Hello World") 4 | (recur (- n 1)) 5 | ) 6 | ) -------------------------------------------------------------------------------- /functional_programming/introduction/list_length.clj: -------------------------------------------------------------------------------- 1 | (fn[lst] 2 | (reduce + (map (fn[x] 1) lst)) 3 | ) 4 | -------------------------------------------------------------------------------- /functional_programming/introduction/list_replication.clj: -------------------------------------------------------------------------------- 1 | (fn[num lst] 2 | (mapcat (partial repeat num) lst) 3 | ) 4 | -------------------------------------------------------------------------------- /functional_programming/introduction/reverse_a_list.clj: -------------------------------------------------------------------------------- 1 | (fn[lst] (reverse lst)) -------------------------------------------------------------------------------- /functional_programming/introduction/solve_me_first_fp.clj: -------------------------------------------------------------------------------- 1 | (defn solveMeFirst [x y] 2 | (+ x y)) 3 | 4 | 5 | (def a (read-line)) 6 | (def b (read-line)) 7 | 8 | (println (solveMeFirst (Integer/parseInt a) (Integer/parseInt b))) -------------------------------------------------------------------------------- /functional_programming/introduction/sum_of_odd_elements.clj: -------------------------------------------------------------------------------- 1 | (fn[lst] 2 | (reduce + (filter odd? lst)) 3 | ) 4 | -------------------------------------------------------------------------------- /functional_programming/introduction/update_list.clj: -------------------------------------------------------------------------------- 1 | (fn[lst] 2 | (map (fn[x] (Math/abs x)) lst) 3 | ) 4 | -------------------------------------------------------------------------------- /olx_code_and_the_curious/sell_statistics_query_system.py: -------------------------------------------------------------------------------- 1 | T = input() 2 | 3 | sells = {} 4 | queries = [] 5 | states = {} 6 | 7 | 8 | def feed_sell(d, p, s): 9 | key = "p{}".format(p) 10 | if not sells[d].get(key): 11 | sells[d][key] = {} 12 | 13 | key2 = "s{}".format(s) 14 | if not sells[d][key].get(key2): 15 | sells[d][key][key2] = 0 16 | 17 | sells[d][key][key2] += 1 18 | 19 | 20 | def add_sell(d, p, s): 21 | if not sells.get(d): 22 | sells[d] = {} 23 | 24 | p1 = None 25 | s1 = None 26 | 27 | pp = p.split(".") 28 | if len(pp) == 1: 29 | p = "{}.0".format(p) 30 | else: 31 | p1 = "{}.0".format(pp[0]) 32 | 33 | ss = s.split(".") 34 | if len(ss) == 1: 35 | s = "{}.0".format(s) 36 | else: 37 | s1 = "{}.0".format(ss[0]) 38 | 39 | feed_sell(d, p, s) 40 | feed_sell(d, p, "-1.0") 41 | feed_sell(d, "-1.0", s) 42 | feed_sell(d, "-1.0", "-1.0") 43 | 44 | if p1 and s1: 45 | feed_sell(d, p1, s1) 46 | 47 | if p1: 48 | feed_sell(d, p1, s) 49 | feed_sell(d, p1, "-1.0") 50 | 51 | if s1: 52 | feed_sell(d, p, s1) 53 | feed_sell(d, "-1.0", s1) 54 | 55 | 56 | line = 1 57 | for l in range(int(T)): 58 | C, d, p, s = input().strip().split(" ") 59 | if C == "S": 60 | add_sell(d, p, s) 61 | elif C == "Q": 62 | days = d.split(".") 63 | 64 | pp = p.split(".") 65 | if len(pp) == 1: 66 | p = "p{}.0".format(p) 67 | else: 68 | p = "p{}".format(p) 69 | 70 | ss = s.split(".") 71 | if len(ss) == 1: 72 | s = "s{}.0".format(s) 73 | else: 74 | s = "s{}".format(s) 75 | 76 | if(len(days) == 1): 77 | result = 0 78 | result += sells.get(d, {}).get(p, {}).get(s, 0) 79 | else: 80 | result = 0 81 | 82 | for i in range(int(days[0]), int(days[1]) + 1): 83 | result += sells.get(str(i), {}).get(p, {}).get(s, 0) 84 | 85 | print(result) 86 | -------------------------------------------------------------------------------- /sql/basic_select/employee_names.sql: -------------------------------------------------------------------------------- 1 | select name from employee order by name asc -------------------------------------------------------------------------------- /sql/basic_select/employee_salaries.sql: -------------------------------------------------------------------------------- 1 | SELECT name from employee where salary>2000 and months<10 -------------------------------------------------------------------------------- /sql/basic_select/higher_than_75_marks.sql: -------------------------------------------------------------------------------- 1 | select name from students where marks>75 order by right(name,3) asc, id asc -------------------------------------------------------------------------------- /sql/basic_select/japanese_cities_attributes.sql: -------------------------------------------------------------------------------- 1 | select * from city where COUNTRYCODE = 'JPN' -------------------------------------------------------------------------------- /sql/basic_select/japanese_cities_names.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY WHERE COUNTRYCODE = 'JPN' -------------------------------------------------------------------------------- /sql/basic_select/revising_the_select_query_i.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY WHERE POPULATION > 100000 AND COUNTRYCODE = 'USA' -------------------------------------------------------------------------------- /sql/basic_select/revising_the_select_query_ii.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY WHERE POPULATION > 120000 AND COUNTRYCODE = 'USA' -------------------------------------------------------------------------------- /sql/basic_select/select_all.sql: -------------------------------------------------------------------------------- 1 | select * FROM CITY -------------------------------------------------------------------------------- /sql/basic_select/select_by_id.sql: -------------------------------------------------------------------------------- 1 | select * from city where id = 1661 -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_1.sql: -------------------------------------------------------------------------------- 1 | SELECT CITY, STATE FROM STATION -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_10.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT(CITY) FROM STATION WHERE substr(CITY,-1,1) NOT in ('A','E','I','O','U') -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_11.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT(CITY) FROM STATION WHERE substr(CITY,1,1) NOT in ('A','E','I','O','U') OR substr(CITY,-1,1) NOT in ('A','E','I','O','U') -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_12.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '^[^aeiou]' AND CITY REGEXP '[^aeiou]$'; -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_3.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT(CITY) FROM STATION WHERE MOD(ID,2)=0 -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_4.sql: -------------------------------------------------------------------------------- 1 | SELECT COUNT(CITY)-COUNT(DISTINCT(CITY)) FROM STATION -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_5.sql: -------------------------------------------------------------------------------- 1 | (SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY (LENGTH(CITY)) ASC LIMIT 1) 2 | UNION 3 | (SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY (LENGTH(CITY)) DESC LIMIT 1) -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_6.sql: -------------------------------------------------------------------------------- 1 | select DISTINCT(CITY) from STATION where CITY like "A%" or CITY like "E%" or CITY like "I%" or CITY like "O%" or CITY like "U%" -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_7.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT(CITY) FROM STATION WHERE CITY LIKE '%a' OR CITY LIKE '%e' OR CITY LIKE '%i' OR CITY LIKE '%o' OR CITY LIKE '%u' -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_8.sql: -------------------------------------------------------------------------------- 1 | select city from STATION WHERE substr(CITY,1,1) in ('A','E','I','O','U') and substr(CITY,-1,1) in ('A','E','I','O','U'); -------------------------------------------------------------------------------- /sql/basic_select/weather_observation_station_9.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT(CITY) FROM STATION WHERE substr(CITY,1,1) NOT in ('A','E','I','O','U') -------------------------------------------------------------------------------- /week_of_code_37/simple_language.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def maximumProgramValue(n): 5 | total = 0 6 | 7 | for _ in range(n): 8 | cmd, val = input().split(' ') 9 | val = int(val) 10 | 11 | if cmd == 'add': 12 | if val > 0: 13 | total += val 14 | else: 15 | if val > total: 16 | total = val 17 | 18 | return total 19 | 20 | 21 | if __name__ == '__main__': 22 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 23 | n = int(input()) 24 | result = maximumProgramValue(n) 25 | fptr.write(str(result) + '\n') 26 | fptr.close() 27 | -------------------------------------------------------------------------------- /week_of_code_37/the_average_rating_of_top_employees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Complete the averageOfTopEmployees function below. 7 | void averageOfTopEmployees(vector rating) { 8 | float sum = 0; 9 | float total = 0; 10 | 11 | for(int i = 0; i < rating.size(); i++){ 12 | if(rating[i] >= 90){ 13 | sum += rating[i]; 14 | total++; 15 | } 16 | } 17 | 18 | cout << fixed << setprecision(2) << sum/total + 0.001; 19 | 20 | } 21 | 22 | int main() 23 | { 24 | int n; 25 | cin >> n; 26 | cin.ignore(numeric_limits::max(), '\n'); 27 | 28 | vector rating(n); 29 | 30 | for (int rating_itr = 0; rating_itr < n; rating_itr++) { 31 | int rating_item; 32 | cin >> rating_item; 33 | cin.ignore(numeric_limits::max(), '\n'); 34 | 35 | rating[rating_itr] = rating_item; 36 | } 37 | 38 | averageOfTopEmployees(rating); 39 | 40 | return 0; 41 | } --------------------------------------------------------------------------------