├── 01matrix.py ├── 132_pattern.cpp ├── 30-days-of-code-july ├── 01.arrangeCoins.cpp ├── 02.levelOrderTraversal-II.cpp ├── 03.prisonAfterNDays.cpp ├── 04.uglyNumberII.cpp ├── 05.hammingDistance.cpp ├── 06.plusOne.cpp ├── 08.3sum.cpp ├── 09.maxWidthOfBinaryTree.cpp ├── 10.flattenMultilevelDLL.cpp ├── 11.subsets.cpp ├── 12.reverseBits.cpp ├── 13.isSameTree.cpp ├── 14.minAngleBetweenHourMinutes.cpp ├── 15.reverseWordsOfString.cpp ├── 16.pow.cpp ├── 17.topKFreqElements.cpp ├── 19.addBinary.cpp ├── 20.removeLLElements.cpp ├── 21.wordSearch.cpp ├── 22.zigzagLevelOrderTraversal.cpp ├── 24.allPathsSourceTarget.cpp ├── 25.minInRotatedSorted.cpp ├── 26.addDigits.cpp └── 27.constructTreeFromInOrderPostOrder.cpp ├── 30-days-of-code-june ├── 01.invertTree.cpp ├── 02.deleteNodeInLinkedList.cpp ├── 03.twoCityScheduling.cpp ├── 04.reverseString.cpp ├── 05.randomPickWithWeights.cpp ├── 06.queueReconstructionByHeight.cpp ├── 07.coinChange2.cpp ├── 08.isPowerOf2.cpp ├── 09.isSubsequence.cpp ├── 10.searchInsertPosition.cpp ├── 11.sortColors.cpp ├── 12.insertDeleteGetRandom.cpp ├── 13.largestDivisibleSubset.cpp ├── 14.cheapestFlightsWithKStops.cpp ├── 15.searchInBST.cpp ├── 17.surroundedRegions.cpp ├── 18.hIndex-ii.cpp ├── 19.longestDuplicateSubstring.cpp ├── 20.permutationSequence.cpp ├── 21.dungeonGame.cpp ├── 22.singleNumberII.cpp ├── 23.countCompleteTreeNodes.cpp ├── 24.uniqueBST.cpp ├── 25.findDuplicateNumber.cpp ├── 26.sumRootToLeafNumbers.cpp ├── 28.reconstructItinerary.cpp ├── 29.uniquePaths.cpp └── 30.wordSearchII.cpp ├── 30-days-of-code-may ├── 01.firstBadVersion.cpp ├── 02.jewelAndStones.cpp ├── 03.ransomNote.cpp ├── 04.numberComplement.cpp ├── 05.firstUniqueCharString.cpp ├── 06.majorityElement.cpp ├── 07.cousinsInBinaryTree.cpp ├── 08.checkPointsOnLine.cpp ├── 09.townJudege.cpp ├── 10.floodFill.cpp ├── 11.singleElementInSortedArray.cpp ├── 13.triePrefixInsertSearch.cpp ├── 14.maxCircularSumArray.cpp ├── 15.oddEvenNodes.cpp ├── 16.findAllAnagramInString.cpp ├── 17.permutationsInString.cpp ├── 19.onlineStockSpan.cpp ├── 20.kthSmallestElementBST.cpp ├── 21.countSubmatricesWith0.cpp ├── 22.sortCharsByFrequency.cpp ├── 23.intervalListIntersections.cpp ├── 24.bstFromPreorder.cpp ├── 25.uncrossedLines.cpp ├── 26.contiguousArray.cpp ├── 27.possibleBipartitions.cpp ├── 28.countingBits.cpp ├── 29.courseSchedule.cpp ├── 30.kClosestPointsToOrigin.cpp └── 31.editDistance.cpp ├── 3_sum.cpp ├── 3_sum_closest.py ├── 3sum_multiplicity.cpp ├── 4_sum.cpp ├── README.md ├── add_and_search_word.cpp ├── add_one_row_to_tree.cpp ├── add_two_number_ii.cpp ├── add_two_numbers.cpp ├── all_ancestors_of_node_binary_tree.cpp ├── all_elements_in_bst.cpp ├── allocate_minimum_number_of_pages.cpp ├── alphabet_to_integer_mapping.cpp ├── alternatingCharacters.py ├── amazon ├── almost_sorted_sequence.cpp ├── area_under_histogram.cpp ├── bottom_view_binary_tree.cpp ├── clone_tree.cpp ├── count_2s.py ├── count_bstnodes_within_range.cpp ├── count_pairs.cpp ├── diagonal_sum.cpp ├── diagonal_traversal.cpp ├── highest_value_palindrome.cpp ├── is_valid_string_variant.py ├── longest_string_without_3_consecutive_chars.py ├── max_sum_across_levels_binary_tree.cpp ├── min_operations_palindrome_array.cpp ├── minimum_characters_to_make_two_strings_palindrome.cpp ├── minimum_distance_between_nodes.cpp ├── minimum_distance_between_nodes_binary_tree.cpp ├── mirror_tree.cpp ├── nge_in_same_order.cpp ├── print_extreme_nodes_binary_tree.cpp ├── right_view_binary_tree.cpp ├── root_to_leaf_path_sum_variant.cpp ├── smallest_window_in_string_containing_another_pattern.cpp ├── strong_password.py ├── twice_counter.py ├── vertical_sum.cpp └── zero_sum_subarrays.cpp ├── arrangeCoins.cpp ├── array_of_doubled_pairs.cpp ├── as_far_from_land_as_possible.cpp ├── atoi.cpp ├── atoi.py ├── average_of_levels.py ├── backspace_compare_strings.py ├── best_time_to_buy_sell_stock_ii.cpp ├── best_time_to_buy_sell_stock_iii.cpp ├── best_time_to_buy_sell_stock_iv.cpp ├── binary_tree_all_paths.cpp ├── binary_tree_tilt.py ├── boats_to_rescue.py ├── boats_to_save_people.cpp ├── bottom-most_left_val_binary_tree.cpp ├── bottom_view_binary_tree.cpp ├── boundaryOfBinaryTree.cpp ├── browser_history.cpp ├── bst_iterator.cpp ├── bst_to_greater_tree.cpp ├── buddy_strings.cpp ├── bulls_and_cows.py ├── burst_balloons.cpp ├── buy_sell_with_cooldown_dp.cpp ├── buy_sell_with_transaction_fee.cpp ├── can_make_palin_substr.cpp ├── candy_swap.py ├── capacity_to_ship_within_d_days.cpp ├── car_pooling.cpp ├── celebrity_problem.cpp ├── cheapest_flights_with_k_stops.cpp ├── check_completeness_of_binary_tree.cpp ├── check_ugly.py ├── cherry_pickup_ii.cpp ├── cinema_seat_allocation.py ├── climbing_stairs.cpp ├── clone_graph.cpp ├── closest_value_in_bst.cpp ├── coinChangeMinimumNumberOfCoins.cpp ├── coinChangeNumberOfWays.cpp ├── combination_sum.cpp ├── combination_sum3.cpp ├── combination_sum_ii.cpp ├── combination_sum_iii.cpp ├── combinations.cpp ├── common_characters.py ├── compare_version_numbers.cpp ├── complement_of_base_10.cpp ├── constructStringFromBinaryTree.cpp ├── construct_bst_from_preorder_traversal.cpp ├── construct_tree_from_inorder_levelorder.cpp ├── construct_tree_from_inorder_postorder.cpp ├── construct_tree_from_inorder_preorder.cpp ├── container_with_max_water.py ├── contains_duplicate_ii.cpp ├── continuous_subarray_sum.cpp ├── convert_ binary_tree_to_doubly_linked_list.cpp ├── convert_binary_tree_to_circular_doubly_linked_list.cpp ├── convert_binary_tree_to_linked_list.cpp ├── convert_bst_to_greater_tree.cpp ├── convert_ll_to_binary_number.cpp ├── convert_sorted_array_to_binary_search_tree.cpp ├── copy_list_with_random_ptr.cpp ├── countConsistentStrings.cpp ├── count_and_say.cpp ├── count_good_meals.cpp ├── count_negative_in_2d.cpp ├── count_number_of_teams.cpp ├── count_palindromic_substrings.py ├── count_substrings_k_distinct_characters.py ├── counting_bits.cpp ├── course_schedule.cpp ├── course_schedule_ii.cpp ├── course_schedule_iv.cpp ├── cousins_binary_tree.cpp ├── daily_temperatures.cpp ├── decode_str.py ├── decode_string.cpp ├── decode_ways.cpp ├── deepest_sum_leaves.cpp ├── defragmenting_ip_address.cpp ├── delete_and_earn.py ├── demolition_robot_amazonq1.py ├── design_front_middle_back_queue.cpp ├── design_hashset.py ├── design_stack_with_increment_operation.cpp ├── design_twitter.cpp ├── detect_capital.cpp ├── diagonal_traversal_binary_tree.py ├── diagonal_traverse.cpp ├── diameter_0f_binary_tree.cpp ├── distant_barcodes.cpp ├── distribute_candies_to_people.cpp ├── distribute_coins_binary_tree.cpp ├── duplicate_zeros.py ├── evaluate_reverse_polish_notation.cpp ├── excel_sheet_column_number.cpp ├── find_all_anagrams_of_substring.cpp ├── find_all_pairs_that_satisfy_four_element_sum.cpp ├── find_critical_connections_in_network.cpp ├── find_disappeared_number.py ├── find_duplicate_number.cpp ├── find_duplicates_file_system.py ├── find_elements_in_contaminated_binary_tree.py ├── find_first_missing_positive.cpp ├── find_median_from_stream.cpp ├── find_mode_binary_search_tree.cpp ├── find_next_right_node_binary_tree.cpp ├── find_next_right_ptr_ii.cpp ├── find_original_array_from_doubled_array.cpp ├── find_peak_element.cpp ├── find_right_interval.cpp ├── find_smallest_set_of_vertices.cpp ├── find_the_difference.py ├── find_words_formed_by_characters.cpp ├── first_and_last_element_of_target.cpp ├── first_bad_version.cpp ├── flatten_binary_tree.py ├── flatten_nested_list_iterator.cpp ├── flip_equivalent.cpp ├── flippin_an_image.py ├── flipping_matrix.cpp ├── floodfill_bfs.cpp ├── furthest_building_reach_possible.cpp ├── game_of_life.cpp ├── gas_station.cpp ├── generate_parentheses.cpp ├── gride_search.cpp ├── group_anagrams.py ├── hamming_distance.cpp ├── happy_numbers.cpp ├── hashcode_2020.py ├── hashcode_more_pizza.cpp ├── heaters.cpp ├── height_checker.py ├── hello_world.cpp ├── hello_world.py ├── house_robbers.cpp ├── house_robbers_a2.cpp ├── implement_own_iota.cpp ├── implement_trie_prefix_tree.cpp ├── increasing_triplet_subsequence.cpp ├── inorder_binary_traversal_variant.cpp ├── inorder_predecessor_in_bst.cpp ├── inorder_successor_in_bst.cpp ├── insertDeleteGetRand.cpp ├── insert_interval.cpp ├── insert_into_bst.cpp ├── integer_to_roman.cpp ├── interleaving_string.py ├── intersection_of_2_arrays.py ├── is_graph_bipartite.cpp ├── is_stretchy.cpp ├── is_subtree.cpp ├── is_valid_bst.cpp ├── island_perimeter.cpp ├── isomorphic_strings.py ├── iterator_for_combination.cpp ├── jewels_and_stones.cpp ├── jump_game.cpp ├── jump_game_ii.cpp ├── jump_game_iv.cpp ├── jumpy_game.cpp ├── k_closest_elements.cpp ├── k_pairs_with_smallest_sums.cpp ├── k_weakest_rows_in_matrix.cpp ├── keys_and_rooms.cpp ├── koko_eating_bananas.cpp ├── kth_closest_point_to_origin.cpp ├── kth_grammar.py ├── kth_largest_element_in_array.cpp ├── kth_largest_element_in_stream.cpp ├── kth_smallest_bst.cpp ├── kth_smallest_element_in_sorted_matrix.cpp ├── kth_smallest_in_multiplication.cpp ├── largest_area_under_histogram.cpp ├── largest_merge_of_two_strings.cpp ├── largest_odd_number_in_string.py ├── largest_subarray_with_zero_sum.cpp ├── last_stone_weight.cpp ├── lca_binarytree.py ├── lca_in_bst.py ├── leaf_similar_trees.py ├── leaves_to_dll.cpp ├── left_view_of_binary_tree.cpp ├── length_of_last_word.cpp ├── letter_case_permutations.cpp ├── letter_combinations_of_phone_number.py ├── linkedlist_components.cpp ├── ll_random_node.cpp ├── long_pressed_name.cpp ├── longest_common_prefix.cpp ├── longest_common_sequence.py ├── longest_common_subsequence.cpp ├── longest_happy_strings.cpp ├── longest_harmonic_sequence.cpp ├── longest_increasing_path_in_matrix.cpp ├── longest_increasing_subsequence.cpp ├── longest_k_unique_chars.py ├── longest_palindrome.py ├── longest_palindromic_subsequence.cpp ├── longest_palindromic_substring.cpp ├── longest_repeated_character_replacement.py ├── longest_string_chain.cpp ├── longest_substr_with_k_distinct_chars.cpp ├── longest_substr_without_repeating.py ├── longest_valid_parentheses.py ├── lowest_common_subsequence(common_child).cpp ├── lru_cache.cpp ├── majority_element.cpp ├── majority_element.py ├── majority_element_ii.cpp ├── making_a_large_island.cpp ├── matchsticks_to_squares.cpp ├── max_are_under_histogram.cpp ├── max_area_of_island.cpp ├── max_chunks_to_make_sorted.cpp ├── max_chunks_to_make_sorted_ii.cpp ├── max_consecutive_ones.cpp ├── max_depth.py ├── max_depth_nary_tree.cpp ├── max_distance_to_closest_person.cpp ├── max_increase_to_keep_city_skyline.cpp ├── max_length_of_repeated_subarray.cpp ├── max_level_sum_binary_tree.cpp ├── max_network_rank.cpp ├── max_path_sum.cpp ├── max_product_of_length_of_two_palindromic_sequences.py ├── max_product_subarray.cpp ├── max_product_two_elements_in_array.cpp ├── max_products_word_length.py ├── max_score_from_removing_stones.cpp ├── max_value_after_insertion.cpp ├── maximal_rectangle.cpp ├── maximal_square.cpp ├── maximum_binary_tree.cpp ├── maximum_binary_tree_2.cpp ├── maximum_of_minimum_for_every_window_size.cpp ├── maximum_width_of_binary_tree.py ├── meeting_rooms.cpp ├── merge_2_binary_trees.cpp ├── merge_2_sorted_lists.cpp ├── merge_in_between_linked_lists.cpp ├── merge_intervals.cpp ├── merge_k_sorted_lists_vectorised.cpp ├── minCostClimbingStairs.cpp ├── min_absolute_difference.cpp ├── min_cost_to_reach_stones.cpp ├── min_deletions_to_make_frequencies_unique.cpp ├── min_index_sum.py ├── min_index_sum_of_two_lists.py ├── min_operations_reduce_x_to_zero.cpp ├── min_stack_o(1).cpp ├── min_steps_to_reach_destination_knight.cpp ├── min_time_taken_to_burn_tree.cpp ├── min_time_visiting_all_points.cpp ├── min_window_substring.cpp ├── minimum_absolute_difference_bst.cpp ├── minimum_add_to_make_parantheses_valid.cpp ├── minimum_costs_for_tickets.cpp ├── minimum_days_to_make_m_bouquets.cpp ├── minimum_depth_binary_tree.cpp ├── minimum_distance_between_nodes.cpp ├── minimum_domino_rotations.cpp ├── minimum_edit_distance.cpp ├── minimum_operations_to_convert_number.cpp ├── minimum_path_sum.cpp ├── minimum_steps_to_reach_target.cpp ├── minimum_steps_to_treasure_island.py ├── monotone_increasing_digits.cpp ├── monotonic_array.cpp ├── most_stones_removed_with_same_row_or_column.cpp ├── move_zeros.cpp ├── multiply_strings.cpp ├── n-ary_level_order_traversal.cpp ├── n-ary_preorder_traversal.cpp ├── network_delay_time.cpp ├── next_greater_element_i.cpp ├── next_greater_element_ii.cpp ├── next_greater_element_iii.cpp ├── no_of_subarr_with_bounded_max.cpp ├── non_decreasing_array.cpp ├── non_overlapping_intervals.cpp ├── nqueens.cpp ├── nth_ugly.py ├── number-of-dice-rolls-with-target-sum.py ├── numberOfLIS.cpp ├── numberOfOccurrencesOfX.cpp ├── number_of_islands.cpp ├── number_of_provices.cpp ├── numbers_with_equal_digit_sum.cpp ├── occurrences_in_bigrams.cpp ├── oddValueCellsInMatrix.cpp ├── odd_even_linked_list.cpp ├── online_stock_span.cpp ├── pacific_atlantic_water_flow.cpp ├── pair-of-songs-divisible-by-60.cpp ├── palindrome_linkedlist.cpp ├── palindrome_number.py ├── palindrome_partition.cpp ├── palindrome_partition_ii.cpp ├── partition_equal_subset.cpp ├── partition_list.cpp ├── partition_to_k_equal_subsets.cpp ├── pascal_triangle.cpp ├── pascal_triangle_ii.cpp ├── patch_array.cpp ├── path_sum.cpp ├── path_sum_ii.cpp ├── path_sum_iii.cpp ├── path_with_min_effort.py ├── permutations-ii.cpp ├── permutations.cpp ├── plus_one.py ├── populate_next_right_ptr.cpp ├── power_of_four.cpp ├── prime_order_prioritization_amazonq2.py ├── prison_cells_after_n_days.cpp ├── product_of_all_except_self.cpp ├── profitable_schemes.cpp ├── random_point_in_nonoverlapping_rect.cpp ├── range_sum_in_bst.cpp ├── range_sum_query.cpp ├── recursive_digit_sum.py ├── reduce_array_size_to_half.cpp ├── reduce_operations_to_make_equal.cpp ├── regular_expression_matching.py ├── removeComments.cpp ├── remove_all_adjacent_from_string.cpp ├── remove_all_adjacent_from_string_ii.cpp ├── remove_duplicates_from_sorted_array.cpp ├── remove_duplicates_from_sorted_array_ii.cpp ├── remove_k_digits.cpp ├── remove_nth_node.py ├── reorder_data_in_log.py ├── reorder_data_in_log_files.py ├── reorder_linkedList_alternate_deque.cpp ├── reorder_list.cpp ├── reorder_routes_with_all_paths_to_city_zero.cpp ├── repeated_dna_sequences.py ├── replace_words.py ├── restore_ip_addresses.cpp ├── reverse-only-letters.cpp ├── reverse_in_groups_of_k.cpp ├── reverse_in_size_of_k.cpp ├── reverse_integer.py ├── reverse_level_order_traversal.cpp ├── reverse_linkedList_ii.cpp ├── reverse_words_in_string.cpp ├── reverse_words_in_string.py ├── right_view_binary_tree.cpp ├── robot_bounded_in_circle.cpp ├── robot_return_to_origin.cpp ├── roman_to_int.cpp ├── root_to_leaf_sum_binary_numbers.cpp ├── root_to_leaf_sum_binary_numbers.py ├── rotate_array.cpp ├── rotate_function.py ├── rotate_image.cpp ├── rotate_list.cpp ├── rotting_oranges.cpp ├── russian_doll_envelopes.cpp ├── score_of_parentheses.cpp ├── score_of_parentheses.py ├── search_a_2d_matrix.py ├── search_in_bst.cpp ├── search_in_rotated_sorted_array.cpp ├── search_in_rotated_sorted_array.py ├── search_in_rotated_sorted_array_ii.cpp ├── serialise_deserialise_bst.cpp ├── set_matrix_zeros.cpp ├── shifting_letters.cpp ├── shorted_unsorted_continuos_subarray.cpp ├── shortest_distance_between_points.cpp ├── shortest_path_binary_matrix.cpp ├── sieve_of_eranthoses.cpp ├── simple_text_editor.cpp ├── simplify_path.py ├── single_number.cpp ├── single_number_ii.cpp ├── skyline_problem.cpp ├── sliding_window_maximum.py ├── smallest_positive_missing_integer.cpp ├── smallest_string_from_leaf.cpp ├── smallest_string_with_swaps.py ├── snakes_and_ladders.cpp ├── snapshot_array.cpp ├── snapshot_array.py ├── sort_by_bits.cpp ├── sort_char_by_frequency.cpp ├── special_palindrome_again.py ├── spiral_matrix_ii.cpp ├── spiral_order_traversal.py ├── split_arary_into_3_arrays.py ├── split_array_consecutive_subsequences.cpp ├── split_array_consecutive_subsequences.py ├── split_linked_list_in_parts.py ├── sqrt.cpp ├── squares_of_sorted_array.cpp ├── stack_using_queue.cpp ├── stream_of_characters.cpp ├── string_compression.cpp ├── string_compression_ii.cpp ├── subarray_sum_equals_k.cpp ├── subsetSumDP.cpp ├── subsets.cpp ├── subsets_ii.cpp ├── substring_with_concatenation_of_all_words.py ├── sum_of_left_leaves.py ├── sum_of_mutated_array_closest_to_target.cpp ├── sum_of_nodes_with_even_valued.py ├── sum_root_to_leaf_numbers.py ├── super_egg_drop.cpp ├── super_washing_machines.cpp ├── surrounded_regions.py ├── swap_adjacent_in_LR_string.py ├── swap_nodes_algo.cpp ├── swap_nodes_in_pairs.py ├── swapping_nodes_in_linked_list.cpp ├── symmetric_tree.cpp ├── tallest_billboard.cpp ├── target_sum.cpp ├── task_scheduler.cpp ├── toeplitz_matrix.cpp ├── top_k_frequent_elements.py ├── top_k_frequent_words.cpp ├── top_view_binary_tree.cpp ├── topological_sort.py ├── topological_sort_using_dfs.py ├── transition_point.cpp ├── trapping_rain_water.cpp ├── trapping_rain_water_ii.cpp ├── two_sum_ii.cpp ├── two_sum_in_bst_iv.cpp ├── ugly_numbers_ii.cpp ├── unique-paths-ii.cpp ├── uniqueTwitterUserIdSet.cpp ├── unique_paths.cpp ├── validPalindrome.cpp ├── valid_anagram.cpp ├── valid_boomerang.py ├── valid_mountain_array.cpp ├── valid_number.cpp ├── valid_palindrome.py ├── valid_parantheses.py ├── valid_parentheses_string_3chars.cpp ├── valid_sudoku.cpp ├── valid_tic_tac_toe_state.py ├── validate_binary_tree_nodes.cpp ├── verify_alien_dict.cpp ├── vertical_order_traversal.cpp ├── water_and_jug.cpp ├── wiggle_subsequence.py ├── wildcard_matching.py ├── word_break.cpp ├── word_break_ii.cpp ├── word_ladder.cpp ├── word_ladder_ii.cpp ├── word_pattern.py ├── word_search.cpp ├── zigzag_conversion.py └── zigzag_traversal_binary_tree_dequeue.cpp /30-days-of-code-july/01.arrangeCoins.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrangeCoins(int n) { 4 | long start = 0, end = n; 5 | long k, curr; 6 | while(start <= end) { 7 | k = start + (end - start) / 2; 8 | curr = k * (k + 1) / 2; 9 | if(curr == n) return (int) k; 10 | if(n < curr) end = k - 1; 11 | else start = k + 1; 12 | } 13 | return (int)end; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /30-days-of-code-july/03.prisonAfterNDays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void prison(vector& cells, int n) { 4 | while(n--) { 5 | vector prev(8, 0); 6 | for(int k=1; k<7; k++) { 7 | if(cells[k-1] == cells[k+1]) { 8 | prev[k] = 1; 9 | } else { 10 | prev[k] = 0; 11 | } 12 | } 13 | cells = prev; 14 | } 15 | } 16 | vector prisonAfterNDays(vector& cells, int N) { 17 | int n = cells.size(); 18 | if(n == 0) return cells; 19 | prison(cells, 1); 20 | prison(cells, (N-1) % 14); 21 | return cells; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /30-days-of-code-july/04.uglyNumberII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | if(n == 1) 5 | return 1; 6 | vector uglies(n); 7 | uglies[0] = 1; 8 | int l2 = 0, l3 = 0, l5 = 0; //indexes for respective list 9 | for(int i=1; i 0 || y > 0){ 7 | op1 = x % 2; 8 | op2 = y % 2; 9 | distance += (op1 ^ op2); 10 | x /= 2; 11 | y /= 2; 12 | } 13 | cout<> threeSum(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | int n=nums.size(); 6 | vector> res; 7 | for(int i=0;i0 && (nums[i]==nums[i-1]) )continue; 9 | int l=i+1, r= n-1; 10 | while(l0)r--; 15 | else { 16 | res.push_back(vector{nums[i],nums[l],nums[r]}); 17 | while(l+1next) 16 | { 17 | if(h->child) 18 | { 19 | Node* next = h->next; 20 | h->next = h->child; 21 | h->next->prev = h; 22 | h->child = NULL;ac 23 | 24 | auto p = h->next; 25 | while(p->next) 26 | p = p->next; 27 | p->next = next; 28 | if(next) next->prev = p; 29 | } 30 | } 31 | return head; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /30-days-of-code-july/11.subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | vector> subs; 5 | vector sub; 6 | subsets(nums, 0, sub, subs); 7 | return subs; 8 | } 9 | void subsets(vector& nums, int i, vector& sub, vector>& subs) { 10 | subs.push_back(sub); 11 | for (int j = i; j < nums.size(); j++) { 12 | sub.push_back(nums[j]); 13 | subsets(nums, j + 1, sub, subs); 14 | sub.pop_back(); 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /30-days-of-code-july/12.reverseBits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | uint32_t result= 0; 5 | for(int i=0; i<32; i++) 6 | result = (result<<1) + (n>>i &1); 7 | 8 | return result; 9 | 10 | /* 11 | bitset<32> bit_set(n); 12 | for (int i = 0; i < 32 / 2; ++i) { 13 | bool temp = bit_set[i]; 14 | bit_set[i] = bit_set[bit_set.size() - 1 - i]; 15 | bit_set[bit_set.size() - 1 - i] = temp; 16 | } 17 | return (uint32_t) bit_set.to_ulong(); 18 | */ 19 | /* 20 | bitset<32> bs{n}; 21 | int l{0}, r{31}; 22 | while(l < r) { 23 | bool tmp = bs[l]; 24 | bs[l++] = bs[r]; 25 | bs[r--] = tmp; 26 | } 27 | return bs.to_ulong(); 28 | */ 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /30-days-of-code-july/13.isSameTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | if(!p and !q) return true; 16 | if(!p or !q) return false; 17 | return (p->val == q->val and isSameTree(p->left, q->left) and isSameTree(p->right, q->right)); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /30-days-of-code-july/14.minAngleBetweenHourMinutes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double angleClock(int hour, int minutes) { 4 | if(hour < 0 or minutes < 0 or hour > 12 or minutes > 60) return 0.0; 5 | 6 | if(hour == 12) hour = 0; 7 | if(minutes == 60) { 8 | minutes = 0; 9 | hour += 1; 10 | if(hour > 12) hour -= 12; 11 | } 12 | 13 | /* 14 | Minute hand moves => 6 degree per minute 15 | Hour hand moves => 0.5 degree per minute 16 | 17 | In h hour and m minutes; 18 | Hour hand moves => (hour * 60 + minutes) * 0.5 19 | Minute hand moves => (hour * 60 + minutes) * 6 20 | */ 21 | auto hour_angle = 0.5 * (hour * 60 + minutes); 22 | auto minute_angle = 6 * minutes; 23 | auto angle = abs(hour_angle - minute_angle); 24 | 25 | return min(360 - angle, angle); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /30-days-of-code-july/15.reverseWordsOfString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | if(s.empty()) return ""; 5 | int sz = s.size(); 6 | int l=0; 7 | for(int i=0;i0&&s[i-1]!= ' ')) 9 | s[l++] = s[i]; 10 | } 11 | if(l>0 && s[l-1] == ' ')--l; 12 | s = s.substr(0,l); 13 | if(s.empty()) return ""; 14 | reverse(s.begin(), s.end()); 15 | l = 0; 16 | for(int i=0;i 0 ? x : 1 / x; n; n /= 2, x *= x) { 6 | if (n & 1) { 7 | p *= x; 8 | } 9 | } 10 | return p; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /30-days-of-code-july/17.topKFreqElements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | priority_queue, vector>, greater>> pq; 5 | unordered_map cnt; 6 | for (auto num : nums) cnt[num]++; 7 | for (auto kv : cnt) { 8 | pq.push({kv.second, kv.first}); 9 | while (pq.size() > k) pq.pop(); 10 | } 11 | vector res; 12 | while (!pq.empty()) { 13 | res.push_back(pq.top().second); 14 | pq.pop(); 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /30-days-of-code-july/19.addBinary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | int la= a.size(); 5 | int lb=b.size(); 6 | string res=""; 7 | int carry=0; 8 | while(la>0 || lb >0) 9 | { 10 | int sum = carry; 11 | if(la > 0) 12 | sum += (a[--la] - '0'); 13 | 14 | if(lb > 0) 15 | sum += (b[--lb] - '0'); 16 | 17 | res.insert(res.begin(), sum % 2 + '0'); 18 | carry = sum / 2; 19 | } 20 | if(carry > 0) 21 | res.insert(res.begin(), '1'); 22 | 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /30-days-of-code-july/25.minInRotatedSorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | return *min_element(begin(nums),end(nums)); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /30-days-of-code-july/26.addDigits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | int mod = num%9; 5 | if(num==0) 6 | return 0; 7 | if(mod==0) 8 | return 9; 9 | return mod; 10 | } 11 | };`` 12 | -------------------------------------------------------------------------------- /30-days-of-code-july/27.constructTreeFromInOrderPostOrder.cpp: -------------------------------------------------------------------------------- 1 | TreeNode *Tree(vector& in, int x, int y,vector& po,int a,int b){ 2 | if(x > y || a > b)return nullptr; 3 | TreeNode *node = new TreeNode(po[b]); 4 | int SI = x; 5 | while(node->val != in[SI])SI++; 6 | node->left = Tree(in,x,SI-1,po,a,a+SI-x-1); 7 | node->right = Tree(in,SI+1,y,po,a+SI-x,b-1); 8 | return node; 9 | } 10 | TreeNode* buildTree(vector& in, vector& po){ 11 | return Tree(in,0,in.size()-1,po,0,po.size()-1); 12 | } 13 | -------------------------------------------------------------------------------- /30-days-of-code-june/02.deleteNodeInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | *node = *(node->next); 13 | } 14 | }; -------------------------------------------------------------------------------- /30-days-of-code-june/04.reverseString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | if(s.size() == 0) return; 5 | 6 | int i=0, j = s.size()-1; 7 | 8 | while(i<=j){ 9 | swap(s[i], s[j]); 10 | i++; j--; 11 | } 12 | return; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /30-days-of-code-june/05.randomPickWithWeights.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector s; 4 | Solution(vector& w) { 5 | for (int ind : w){ 6 | if(s.empty()) 7 | s.push_back(ind); 8 | else 9 | s.push_back(ind + s.back()); 10 | } 11 | } 12 | 13 | int pickIndex() { 14 | int x = s.back(); 15 | int index = rand() % x; 16 | auto it = upper_bound(s.begin(), s.end(),index); 17 | return it - s.begin(); 18 | } 19 | }; 20 | 21 | /** 22 | * Your Solution object will be instantiated and called as such: 23 | * Solution* obj = new Solution(w); 24 | * int param_1 = obj->pickIndex(); 25 | */ 26 | -------------------------------------------------------------------------------- /30-days-of-code-june/07.coinChange2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int amount, vector& coins) { 4 | 5 | vector> dp(coins.size() + 1, vector(amount + 1, 0)); 6 | dp[0][0] = 1; 7 | for (int i = 1; i <= coins.size(); ++i) { 8 | dp[i][0] = 1; 9 | for (int j = 1; j <= amount; ++j) { 10 | dp[i][j] = dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0); 11 | } 12 | } 13 | return dp[coins.size()][amount]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /30-days-of-code-june/08.isPowerOf2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if (n == 0) 5 | return 0; 6 | while (n != 1) 7 | { 8 | if (n%2 != 0) 9 | return 0; 10 | n = n/2; 11 | } 12 | return 1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /30-days-of-code-june/09.isSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | int i = 0, j = 0; 5 | while (i < s.size() and j < t.size()) { 6 | if (s[i] == t[j]) i++; 7 | j++; 8 | } 9 | return i == s.size(); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /30-days-of-code-june/10.searchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | if(nums.size() == 0) return -1; 5 | 6 | int left = 0, right = nums.size() - 1; 7 | int mid, index; 8 | 9 | while(left <= right){ 10 | mid = left + (right - left) / 2; 11 | if(nums[mid] == target) return mid; 12 | else if(nums[mid] > target){ 13 | right = mid - 1; 14 | //index = mid - 1; 15 | } 16 | else{ 17 | left = mid + 1; 18 | //index = mid + 1; 19 | } 20 | } 21 | return left; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /30-days-of-code-june/11.sortColors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void swap(int &a, int &b){ 4 | int temp = a; 5 | a = b; 6 | b = temp; 7 | } 8 | void sortColors(vector& nums) { 9 | int start = 0, mid = 0, end = nums.size() - 1; 10 | 11 | int pivot = 1; 12 | while (mid <= end) 13 | { 14 | if (nums[mid] < pivot) // current element is 0 15 | swap(nums[start++], nums[mid++]); 16 | else if (nums[mid] > pivot) // current element is 2 17 | swap(nums[mid], nums[end--]); 18 | else mid++; 19 | } 20 | } 21 | 22 | }; 23 | -------------------------------------------------------------------------------- /30-days-of-code-june/15.searchInBST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* searchBST(TreeNode* root, int val) { 15 | if(!root) return nullptr; 16 | 17 | if(val == root->val) return root; 18 | 19 | if(val < root->val) return searchBST(root->left, val); 20 | return searchBST(root->right, val); 21 | } 22 | }; -------------------------------------------------------------------------------- /30-days-of-code-june/18.hIndex-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | const int size_c = citations.size(); 5 | int left = 0, right = size_c - 1; 6 | while (left <= right) { 7 | int mid = left + (right - left) / 2; 8 | if (citations[mid] < size_c - mid) left = mid + 1; 9 | else right = mid - 1; 10 | } 11 | return size_c - left; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /30-days-of-code-june/20.permutationSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getPermutation(int n, int k) { 4 | string res; 5 | string nums = "123456789"; 6 | int f[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; 7 | --k; 8 | for (int i = n; i >= 1; --i) { 9 | int j = k / f[i - 1]; 10 | k %= f[i - 1]; 11 | res.push_back(nums[j]); 12 | nums.erase(nums.begin() + j); 13 | } 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /30-days-of-code-june/22.singleNumberII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | 5 | int n=nums.size(); 6 | long ans; 7 | int x, t; 8 | ans=0; 9 | int p=0; 10 | // We have 32 bits integers as input 11 | for(int i=0;i<32;i++) 12 | { 13 | t=0; 14 | //calculate sum of ith bit for all numbers in nums 15 | for(int j=0;j>1; 20 | } 21 | t=t%3; 22 | //the bit that does not occur as multiple of 3 is left as a remainder 23 | ans=ans+t*pow(2,p); 24 | p++; 25 | } 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /30-days-of-code-june/23.countCompleteTreeNodes.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int countNodes(TreeNode* root) { 15 | if(!root) return 0; 16 | 17 | int hl=0, hr=0; 18 | auto l=root, r=root; 19 | 20 | while(l){ 21 | hl++; 22 | l=l->left; 23 | } 24 | 25 | while(r){ 26 | hr++; 27 | r=r->right; 28 | } 29 | 30 | if(hl==hr) return pow(2,hl)-1; 31 | 32 | return 1+countNodes(root->left)+countNodes(root->right); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /30-days-of-code-june/24.uniqueBST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | vector nums(n+1, 0); 5 | nums[0]=1; nums[1]=1; 6 | for(int i=2;i<=n;i++){ 7 | for(int j=0;j& nums) { 4 | int slow=0; 5 | int fast=0; 6 | while(true){ 7 | slow=nums[slow]; 8 | fast=nums[nums[fast]]; 9 | if(slow==fast) break; 10 | } 11 | int find=0; 12 | while(slow!=find){ 13 | slow=nums[slow]; 14 | find=nums[find]; 15 | } 16 | return find; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /30-days-of-code-june/29.uniquePaths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | 5 | 6 | int dp[m+1][n+1]; 7 | 8 | 9 | for(int i=0; i stones; 7 | 8 | for(int i=0; i mp; 7 | 8 | for(char m : magazine) 9 | mp[m-'a']++; 10 | 11 | for(char r : ransomNote){ 12 | if(--mp[r-'a'] < 0) 13 | return false; 14 | 15 | } 16 | return true; 17 | } 18 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/05.firstUniqueCharString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | 5 | if(s.size() == 0) return -1; 6 | 7 | map mp; 8 | for(auto ch : s) 9 | mp[ch]++; 10 | 11 | for(int i=0; i& nums) { 4 | if(nums.size() == 0) return 0; 5 | 6 | map hash; 7 | for(auto num : nums) 8 | hash[num]++; 9 | int sz = nums.size(); 10 | 11 | for(auto const& p : hash){ 12 | if(p.second > sz/2){ 13 | return p.first; 14 | } 15 | } 16 | return -1; 17 | } 18 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/08.checkPointsOnLine.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkStraightLine(vector>& coordinates) { 4 | 5 | if(coordinates.size() <= 2) return true; 6 | int x1 = coordinates[0][0]; 7 | int y1 = coordinates[0][1]; 8 | int x2 = coordinates[1][0]; 9 | int y2 = coordinates[1][1]; 10 | for(int i=2;i>& trust) { 4 | vector count(N + 1, 0); 5 | for (auto& t : trust) 6 | count[t[0]]--, count[t[1]]++; 7 | for (int i = 1; i <= N; ++i) { 8 | if (count[i] == N - 1) return i; 9 | } 10 | return -1; 11 | } 12 | 13 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/10.floodFill.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 4 | if (image[sr][sc] != newColor) 5 | dfs(image, sr, sc, image[sr][sc], newColor); 6 | return image; 7 | } 8 | 9 | private: 10 | void dfs(vector>& image, int i, int j, int c0, int c1) { 11 | if (i < 0 || j < 0 || i >= image.size() || j >= image[0].size() || image[i][j] != c0) return; 12 | image[i][j] = c1; 13 | dfs(image, i, j - 1, c0, c1); 14 | dfs(image, i, j + 1, c0, c1); 15 | dfs(image, i - 1, j, c0, c1); 16 | dfs(image, i + 1, j, c0, c1); 17 | } 18 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/11.singleElementInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& nums) { 4 | 5 | int start = 0, end = nums.size() - 1, mid; 6 | while(start < end){ 7 | mid = start + (end - start) / 2; 8 | if(mid % 2 == 0){ 9 | if(nums[mid] == nums[mid+1]) start = mid + 2; 10 | else if(nums[mid] == nums[mid-1]) end = mid - 2; 11 | else return nums[mid]; 12 | } 13 | else{ 14 | if(nums[mid] == nums[mid-1]) start = mid + 1; 15 | if(nums[mid] == nums[mid+1]) end = mid - 1; 16 | } 17 | } 18 | return nums[start]; 19 | } 20 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/14.maxCircularSumArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubarraySumCircular(vector& A) { 4 | if(A.size() == 0) return 0; 5 | 6 | int nocircle = helper(A), sum = 0; 7 | if(nocircle < 0) return nocircle; 8 | 9 | auto t = A; 10 | for(auto &n : t){ 11 | sum += n; 12 | n *= -1; 13 | } 14 | 15 | int circle = sum + helper(t); 16 | return max(circle, nocircle); 17 | } 18 | 19 | int helper(vector& A){ 20 | if(A.size() == 0) return 0; 21 | 22 | int max_seen_so_far = INT_MIN, max_positive_seen = 0; 23 | for(auto num : A){ 24 | if(max_positive_seen < 0) 25 | max_positive_seen = num; 26 | else 27 | max_positive_seen += num; 28 | max_seen_so_far = max(max_seen_so_far, max_positive_seen); 29 | } 30 | return max_seen_so_far; 31 | } 32 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/15.oddEvenNodes.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* oddEvenList(ListNode* head) { 12 | if(!head) return NULL; 13 | 14 | auto odd = head, even_head = odd->next, even = even_head; 15 | 16 | while(even && even->next){ 17 | odd->next = odd->next->next; 18 | even->next = even->next->next; 19 | odd = odd->next; 20 | even = even->next; 21 | } 22 | odd->next = even_head; 23 | return head; 24 | } 25 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/17.permutationsInString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | if(s2.size() < s1.size()) return false; 5 | 6 | std::vector vs1(26, 0); 7 | 8 | for(const auto &el: s1) 9 | { 10 | vs1[el - 'a']++; 11 | } 12 | 13 | std::vector vtmp(26, 0); 14 | const std::string tmp = s2.substr(0, s1.size()); 15 | 16 | for(const auto &el: tmp) 17 | { 18 | vtmp[el - 'a']++; 19 | } 20 | 21 | if(vtmp == vs1) 22 | { 23 | return true; 24 | } 25 | 26 | for(size_t i = 1; i <= s2.size() - s1.size(); i++) 27 | { 28 | const auto c1 = s2[i-1]; 29 | const auto c2 = s2[i+s1.size()-1]; 30 | 31 | vtmp[c1 - 'a']--; 32 | vtmp[c2 - 'a']++; 33 | 34 | if(vtmp == vs1) 35 | { 36 | return true; 37 | } 38 | } 39 | 40 | return false; 41 | } 42 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/19.onlineStockSpan.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | 4 | stack> st; 5 | int index = 0; 6 | 7 | StockSpanner() { 8 | 9 | } 10 | 11 | int next(int price) { 12 | 13 | if(st.empty()){ 14 | st.push({price, index++}); 15 | return 1; 16 | } 17 | 18 | else{ 19 | 20 | while(!st.empty() && st.top().first <= price){ 21 | st.pop(); 22 | } 23 | 24 | int res = st.empty()? index + 1 : index - st.top().second; 25 | st.push({price, index++}); 26 | return res; 27 | } 28 | return -1; 29 | } 30 | }; 31 | 32 | /** 33 | * Your StockSpanner object will be instantiated and called as such: 34 | * StockSpanner* obj = new StockSpanner(); 35 | * int param_1 = obj->next(price); 36 | */ -------------------------------------------------------------------------------- /30-days-of-code-may/21.countSubmatricesWith0.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int min(int a, int b){ 4 | if(a>& matrix) { 9 | if(matrix.size() == 0) return 0; 10 | 11 | int res = 0; 12 | 13 | for(int i=0; i m; 6 | for(auto c : s) m[c]++; 7 | vector> values(m.begin(),m.end()); 8 | 9 | sort(values.begin(),values.end(),[](const pair& a, const pair& b){ 10 | return a.second > b.second; 11 | }); 12 | 13 | string result = ""; 14 | for(auto [k, v] : values){ 15 | while(v--){ 16 | result.push_back(k); 17 | } 18 | } 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/23.intervalListIntersections.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> intervalIntersection(vector>& A, vector>& B) { 4 | vector> res; 5 | for(int i = 0, j = 0; i < A.size() && j < B.size();) { 6 | int lo = max(A[i][0], B[j][0]), hi = min(A[i][1], B[j][1]); 7 | if(lo <= hi) res.push_back({lo, hi}); 8 | if(hi == A[i][1]) i++; 9 | else j++; 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/25.uncrossedLines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUncrossedLines(vector& A, vector& B) { 4 | int n=A.size(); 5 | int m=B.size(); 6 | 7 | int dp[n+1][m+1]; 8 | 9 | 10 | for(int i=0;i<=n;++i) 11 | { 12 | for(int j=0;j<=m;++j) 13 | { 14 | if(i==0 || j==0) 15 | dp[i][j]=0; 16 | else if(A[i-1]==B[j-1]) 17 | dp[i][j]=dp[i-1][j-1]+1; 18 | else 19 | dp[i][j]=max(dp[i][j-1],dp[i-1][j]); 20 | } 21 | } 22 | return dp[n][m]; 23 | } 24 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/26.contiguousArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector& nums) { 4 | int sum=0; 5 | unordered_map m; 6 | unsigned int longestContArray = 0; 7 | 8 | for(int i=0;isecond) 19 | longestContArray = i-it->second; 20 | } 21 | else if(it == m.end()) 22 | m.insert({sum,i}); 23 | } 24 | return longestContArray; 25 | } 26 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/28.countingBits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int num) { 4 | vector bits(num+1, 0); 5 | for(int i = 1; i <= num; i++) bits[i] += bits[i>>1] + i&1; 6 | return bits; 7 | } 8 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/30.kClosestPointsToOrigin.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> kClosest(vector>& points, int K) { 4 | 5 | nth_element(points.begin(), points.begin() + K - 1, points.end(), [](vector& p, vector& q) { 6 | return p[0] * p[0] + p[1] * p[1] < q[0] * q[0] + q[1] * q[1]; 7 | }); 8 | return vector>(points.begin(), points.begin() + K); 9 | } 10 | }; -------------------------------------------------------------------------------- /30-days-of-code-may/31.editDistance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | 5 | int M = word1.size(), N = word2.size(); 6 | 7 | vector> dp(M + 1, vector (N + 1, 0)); 8 | 9 | for(int i=1; i<=M; i++) 10 | dp[i][0] = i; 11 | 12 | for(int j=1; j<=N; j++) 13 | dp[0][j] = j; 14 | 15 | 16 | for(int i=1; i<=M; i++){ 17 | for(int j=1; j<=N; j++){ 18 | 19 | if(word1[i-1] == word2[j-1]) 20 | dp[i][j] = dp[i-1][j-1]; 21 | else{ 22 | dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])) + 1; 23 | } 24 | 25 | } 26 | } 27 | return dp[M][N]; 28 | } 29 | }; -------------------------------------------------------------------------------- /3_sum_closest.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumClosest(self, nums: List[int], target: int) -> int: 3 | length = len(nums) 4 | if length <= 2: return 0 5 | nums.sort() 6 | result = sum(nums[:3]) 7 | 8 | for i in range(length - 2): 9 | a_ptr = i + 1 #second sum 10 | b_ptr = length - 1 #third sum 11 | 12 | while a_ptr < b_ptr: #normal two pointer technique 13 | current_sum = nums[i] + nums[a_ptr] + nums[b_ptr] 14 | if current_sum > target: b_ptr -= 1 15 | else: a_ptr += 1 16 | 17 | if abs(current_sum - target) < abs(result - target): 18 | result = current_sum 19 | return result 20 | -------------------------------------------------------------------------------- /3sum_multiplicity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumMulti(vector& A, int target) { 4 | int mod = 1e9+7; 5 | unordered_map ump; 6 | long res = 0; 7 | 8 | for(int i=0; i tp; 13 | 14 | void traverse(TreeNode *root){ 15 | if(!root) return; 16 | traverse(root->left); 17 | tp.push_back(root->val); 18 | traverse(root->right); 19 | } 20 | public: 21 | vector getAllElements(TreeNode* root1, TreeNode* root2) { 22 | traverse(root1); 23 | traverse(root2); 24 | sort(tp.begin(), tp.end()); 25 | return tp; 26 | 27 | } 28 | }; -------------------------------------------------------------------------------- /alphabet_to_integer_mapping.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string freqAlphabets(string s) { 4 | 5 | string res; 6 | unordered_map h = { 7 | {"1","a"},{"2","b"},{"3","c"},{"4","d"},{"5","e"},{"6","f"},{"7","g"},{"8","h"},{"9","i"},{"10","j"} 8 | ,{"11","k"},{"12","l"},{"13","m"},{"14","n"},{"15","o"},{"16","p"},{"17","q"},{"18","r"},{"19","s"} 9 | ,{"20","t"},{"21","u"},{"22","v"},{"23","w"},{"24","x"},{"25","y"},{"26","z"} 10 | }; 11 | 12 | int i = s.length()-1; 13 | while(i>-1){ 14 | if(s[i]=='#'){ 15 | i-=2; 16 | string p = s.substr(i,2); 17 | res=h[p]+res; 18 | } 19 | else{ 20 | res=h[s.substr(i,1)]+res; 21 | } 22 | i--; 23 | } 24 | return res; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /alternatingCharacters.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the alternatingCharacters function below. 10 | def alternatingCharacters(s): 11 | st, i, dupCnt = [], 0, 0 12 | for c in s: 13 | if not st: 14 | st.append(c) 15 | elif st[-1] == c: 16 | dupCnt += 1 17 | else: 18 | st.append(c) 19 | return dupCnt 20 | 21 | ''' 22 | dupCnt = 0 23 | for i in range(len(s) - 1): 24 | if s[i] == s[i+1]: 25 | dupCnt += 1 26 | return dupCnt 27 | ''' 28 | 29 | if __name__ == '__main__': 30 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 31 | 32 | q = int(input()) 33 | 34 | for q_itr in range(q): 35 | s = input() 36 | 37 | result = alternatingCharacters(s) 38 | 39 | fptr.write(str(result) + '\n') 40 | 41 | fptr.close() 42 | -------------------------------------------------------------------------------- /amazon/count_2s.py: -------------------------------------------------------------------------------- 1 | { 2 | #Initial Template for Python 3 3 | if __name__ == "__main__": 4 | t=int(input()) 5 | for i in range(t): 6 | n=int(input()) 7 | print(numberOf2sinRange(n)) 8 | } 9 | ''' This is a function problem.You only need to complete the function given below ''' 10 | #User function Template for python3 11 | def number0f2s(n): 12 | curr = str(n) 13 | return curr.count('2') 14 | #add Code here 15 | 16 | def numberOf2sinRange(n): 17 | res = 0 18 | for i in range(1, n+1): 19 | res += number0f2s(i) 20 | return res 21 | #add code here -------------------------------------------------------------------------------- /amazon/diagonal_sum.cpp: -------------------------------------------------------------------------------- 1 | void dSumUtil(Node *root, int d, map &mp){ 2 | if(!root) return; 3 | mp[d] += root->data; 4 | dSumUtil(root->left, d + 1, mp); 5 | dSumUtil(root->right, d, mp); 6 | } 7 | void diagonalSum(Node* root) 8 | { 9 | // Add your code here 10 | if(!root) return; 11 | map mp; 12 | dSumUtil(root, 0, mp); 13 | 14 | for(auto it = mp.begin(); it != mp.end(); it++) 15 | cout<second<<" "; 16 | cout<<"\n"; 17 | } -------------------------------------------------------------------------------- /amazon/diagonal_traversal.cpp: -------------------------------------------------------------------------------- 1 | multimap m; 2 | void inorder(Node * root,int hd) { 3 | if(!root) return; 4 | 5 | m.insert({hd, root->data}); 6 | inorder(root->left, hd+1); 7 | inorder(root->right, hd); 8 | 9 | } 10 | 11 | void diagonalPrint(Node *root) { 12 | 13 | inorder(root,0); 14 | for(auto it=m.begin();it!=m.end();it++) 15 | cout<second<<" "; 16 | m.clear(); 17 | 18 | } 19 | 20 | /*void diagonalPrint(Node *root) 21 | { 22 | // your code here 23 | queue q; 24 | q.push(root); 25 | while(!q.empty()){ 26 | Node *t=q.front(); 27 | while(t){ 28 | cout<data<<" "; 29 | if(t->left) 30 | q.push(t->left); 31 | t=t->right; 32 | } 33 | q.pop(); 34 | } 35 | }*/ -------------------------------------------------------------------------------- /amazon/longest_string_without_3_consecutive_chars.py: -------------------------------------------------------------------------------- 1 | def ls3(A, B, C): 2 | pq = [] 3 | res = "" 4 | for k, v in ('a', A), ('b', B), ('c', C): 5 | heapq.heappush(pq, (-v, k)) 6 | preV, preK = 0, '' 7 | while pq: 8 | v, k = heapq.heappop(pq) 9 | if preV: 10 | heapq.heappush(pq, (preV, preK)) 11 | preV, preK = 0, '' 12 | if res[-2:] == k * 2: 13 | preV, preK = v, k 14 | else: 15 | res += k 16 | if v != -1: 17 | heapq.heappush(pq, (v + 1, k)) 18 | return res 19 | A, B, C = 1, 1, 6 20 | print(ls3(A, B, C)) 21 | A, B, C = 1, 2, 3 22 | print(ls3(A, B, C)) -------------------------------------------------------------------------------- /amazon/minimum_characters_to_make_two_strings_palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int makeAnagram(string a, string b) { 5 | 6 | char hashmap[26] = {0}; 7 | 8 | for(auto& c: a)hashmap[c-'a']++; 9 | for(auto& c: b)hashmap[c-'a']--; //all repeated characters get 0 as their count in the freq 10 | 11 | int count = 0; 12 | for(auto& x : hashmap)count += abs(x); 13 | 14 | return count; 15 | } 16 | 17 | int main() 18 | { 19 | ofstream fout(getenv("OUTPUT_PATH")); 20 | string a; 21 | getline(cin, a); 22 | string b; 23 | getline(cin, b); 24 | int res = makeAnagram(a, b); 25 | fout << res << "\n"; 26 | fout.close(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /amazon/twice_counter.py: -------------------------------------------------------------------------------- 1 | #code 2 | from collections import Counter 3 | n = int(input()) 4 | 5 | for i in range(n): 6 | _ = int(input()) 7 | tc = list(map(str, input().split(' '))) 8 | counter = Counter() 9 | for i in range(len(tc)): 10 | counter[tc[i]] += 1 11 | cn = 0 12 | for k,v in counter.items(): 13 | if v == 2: 14 | cn += 1 15 | print(cn) -------------------------------------------------------------------------------- /arrangeCoins.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrangeCoins(int n) { 4 | long start = 0, end = n; 5 | long k, curr; 6 | while(start <= end) { 7 | k = start + (end - start) / 2; 8 | curr = k * (k + 1) / 2; 9 | if(curr == n) return (int) k; 10 | if(n < curr) end = k - 1; 11 | else start = k + 1; 12 | } 13 | return (int)end; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /array_of_doubled_pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canReorderDoubled(vector& arr) { 4 | if(arr.size() == 0) return true; 5 | 6 | unordered_map ump; //element to count 7 | sort(arr.begin(), arr.end()); 8 | 9 | for(auto element : arr) { 10 | ump[element]++; 11 | } 12 | 13 | for(auto element: arr) { 14 | if (ump[element] == 0) { 15 | continue; 16 | } 17 | if (element < 0 && element % 2 != 0) { //for -ve values, there is no element/2 pair to match 18 | return false; 19 | } 20 | int pair = element > 0 ? element*2 : element/2; //positive or negative 21 | if (ump[pair] == 0) { //no match with element 22 | return false; 23 | } 24 | ump[element]--; 25 | ump[pair]--; 26 | } 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /atoi.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(string str) { 4 | int r = 0; 5 | stringstream ss; 6 | ss << str; 7 | ss >> r; 8 | return r; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /average_of_levels.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def averageOfLevels(self, root: TreeNode) -> List[float]: 10 | levels, queue = [],[root] 11 | while queue: 12 | levels.append(sum([e.val for e in queue]) / float(len(queue))) 13 | queue = [ee for e in queue for ee in [e.left,e.right] if ee] 14 | return levels -------------------------------------------------------------------------------- /best_time_to_buy_sell_stock_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | 5 | 6 | int maxProfit = 0; 7 | int i = 0, N = prices.size() - 1; 8 | int buy = 0, sell = 0; 9 | 10 | while(i < N){ 11 | //current_price > next_price 12 | while(i < N && prices[i+1] <= prices[i]) i++; //break when current_price !< next_price 13 | buy = prices[i]; 14 | while(i < N && prices[i+1] > prices[i]) i++; 15 | sell = prices[i]; 16 | maxProfit += sell - buy; 17 | } 18 | return maxProfit; 19 | } 20 | }; -------------------------------------------------------------------------------- /binary_tree_tilt.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def findTilt(self, root: TreeNode) -> int: 10 | if not root: 11 | return 0 12 | self._sum = 0 13 | def util(root): 14 | if not root: 15 | return 0 16 | left, right = util(root.left), util(root.right) 17 | self._sum += abs(left - right) 18 | return root.val + left + right 19 | util(root) 20 | return self._sum -------------------------------------------------------------------------------- /boats_to_rescue.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | people.sort(reverse = True) 4 | i, j = 0, len(people) - 1 5 | boats = 0 6 | while i <= j: 7 | if people[i] + people[j] <= limit: 8 | j -= 1 9 | i += 1 10 | return i -------------------------------------------------------------------------------- /boats_to_save_people.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | sort(people.begin(), people.end()); 5 | int i = 0, j = people.size() - 1; 6 | int boats = 0; 7 | 8 | while(i <= j){ 9 | if(people[i] + people[j] <= limit) 10 | i++; 11 | j--; 12 | boats++; 13 | } 14 | return boats; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /bottom-most_left_val_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int findBottomLeftValue(TreeNode* root) { 13 | 14 | queue q; 15 | q.push(root); 16 | 17 | while(!q.empty()){ 18 | root = q.front(); 19 | q.pop(); 20 | if(root->right) 21 | q.push(root->right); 22 | if(root->left) 23 | q.push(root->left); 24 | } 25 | return root->val; 26 | } 27 | }; -------------------------------------------------------------------------------- /bst_to_greater_tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | 13 | int sum = 0; 14 | TreeNode* convertBST(TreeNode* root) { 15 | if(root){ 16 | convertBST(root->right); 17 | root->val += sum; 18 | sum = root->val; 19 | convertBST(root->left); 20 | } 21 | return root; 22 | } 23 | }; -------------------------------------------------------------------------------- /buddy_strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool buddyStrings(string A, string B) { 4 | 5 | if(A.length() != B.length()) return false; //no possible swap 6 | 7 | if(A == B && set(A.begin(), A.end()).size() < A.size()) return true; 8 | 9 | vector diff; 10 | 11 | for(int i=0; i str: 3 | d = {} 4 | bull, cow = 0,0 5 | 6 | for index,s in enumerate(secret): 7 | if guess[index] == s: 8 | bull += 1 9 | else: 10 | d[s] = d.get(s,0) + 1 11 | 12 | for index,s in enumerate(secret): 13 | if (guess[index] != s) & (d.get(guess[index],0) != 0): 14 | cow += 1 15 | d[guess[index]] -= 1 16 | 17 | return str(bull) + "A" + str(cow) + "B" 18 | -------------------------------------------------------------------------------- /burst_balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxCoins(vector& nums) { 4 | int n = nums.size(); 5 | int len = n+2; 6 | vector arr = {1}; 7 | for(auto& num : nums) 8 | arr.push_back(num); 9 | 10 | arr.push_back(1); 11 | vector> dp(len, vector(len, 0)); 12 | 13 | for(int gap = 2; gap < len; gap++) { 14 | for(int left = 0; left < len-gap; left++) { 15 | int right = left+gap; 16 | int cur = 0; 17 | for(int mid = left+1; mid < right; mid++) { 18 | cur = max(cur, dp[left][mid]+dp[mid][right]+arr[left]*arr[mid]*arr[right]); 19 | } 20 | dp[left][right] = cur; 21 | } 22 | } 23 | return dp[0][len-1]; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /candy_swap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: 3 | su = (sum(A) + sum(B)) // 2 4 | diffSum = su - sum(A) 5 | sb = set(B) 6 | for a in A: 7 | if diffSum + a in sb: 8 | return [a, diffSum + a] 9 | 10 | ''' 11 | A [1, 1] 12 | B [2, 2] 13 | 14 | S = 6 // 2 = 3 15 | diffSum = 3 - 2 = 1 16 | if 1 + 1 in sb: 17 | Yes -- 18 | return [1 , 2] 19 | ''' -------------------------------------------------------------------------------- /car_pooling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool carPooling(vector>& trips, int capacity) { 4 | vector race(1001, 0); 5 | 6 | for(auto &trip : trips){ 7 | for(int i = trip[1]; i < trip[2]; ++i){ 8 | race[i] += trip[0]; 9 | if(race[i] > capacity) return false; 10 | } 11 | } 12 | return true; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /check_ugly.py: -------------------------------------------------------------------------------- 1 | #naive solution 2 | class Solution: 3 | def reduceUgly(self, a, b): 4 | while a%b == 0: 5 | a /= b 6 | return a 7 | 8 | def isUgly(self, num: int) -> bool: 9 | 10 | num = self.reduceUgly(num, 2) 11 | num = self.reduceUgly(num, 3) 12 | num = self.reduceUgly(num, 5) 13 | 14 | if num == 1: return True 15 | else: return False 16 | -------------------------------------------------------------------------------- /climbing_stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | if(n == 0 || n == 1 || n == 2) 5 | return n; 6 | 7 | vector mem(n); 8 | mem[0] = 1; 9 | mem[1] = 2; 10 | for(int i = 2; i < n; i++) 11 | mem[i] = mem[i-1] + mem[i-2]; 12 | 13 | return mem[n-1]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /combination_sum3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum3(int k, int n) { 4 | vector> result; 5 | vector answer; 6 | helper(result, answer, k, n, 1); // Start from digit 1 7 | return result; 8 | } 9 | 10 | void helper(vector>& r, vector& a, int k, int n, int digit) { 11 | if(k == 0) { 12 | if(n == 0) r.push_back(a); 13 | return; 14 | } 15 | 16 | for(int i = digit; i < 10; ++i) { 17 | a.push_back(i); 18 | helper(r, a, k-1, n-i, i+1); 19 | a.pop_back(); 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /combinations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combine(int n, int k) { 4 | vector> output; 5 | vector combination; 6 | combine(output, combination, n, k, 1); 7 | return output; 8 | } 9 | 10 | private: 11 | void combine(vector>& output, vector combination, int n, int k, int i) { 12 | if (combination.size() == k) { 13 | output.push_back(combination); 14 | return; 15 | } 16 | for (int j = i; j <= n; j++) { 17 | combination.push_back(j); 18 | combine(output, combination, n, k, j + 1); 19 | combination.pop_back(); 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /complement_of_base_10.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bitwiseComplement(int n) { 4 | if(n == 0) return 1; 5 | 6 | vector bits; 7 | while(n) { 8 | bits.push_back(n % 2); 9 | n /= 2; 10 | } 11 | reverse(bits.begin(), bits.end()); 12 | 13 | vector inverse; 14 | for(auto &bit : bits) { 15 | int bitInv = (bit == 1) ? 0 : 1; 16 | inverse.push_back(bitInv); 17 | } 18 | 19 | unsigned int complement = 0; 20 | int sz = inverse.size() - 1; 21 | for(int acc = sz; acc >= 0; --acc) { // x * 2^(n - i) where x == arr[i] 22 | complement += (inverse[acc] * pow(2, sz - acc)); 23 | } 24 | 25 | return complement; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /constructStringFromBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | string tree2str(TreeNode* t) { 13 | if (!t) return ""; 14 | string str = to_string(t->val); 15 | if (t->left || t->right) { 16 | str += "(" + tree2str(t->left) + ")"; 17 | 18 | if (t->right) str += "(" + tree2str(t->right) + ")"; 19 | } 20 | return str; 21 | } 22 | }; -------------------------------------------------------------------------------- /contains_duplicate_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyDuplicate(vector& nums, int k) { 4 | 5 | unordered_map ump; 6 | for(int i=0; i& nums, int k) { 5 | int i, sum = 0, len = 0; 6 | unordered_map map; 7 | map[0] = -1; 8 | 9 | if(k==0){ 10 | for(i=1; i= 2){ 23 | return true; 24 | } 25 | } else { 26 | map[sum % k] = i; 27 | } 28 | } 29 | return false; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /convert_ll_to_binary_number.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | int getDecimalValue(ListNode* head) { 12 | 13 | int res=0; 14 | while(head!=NULL) { 15 | res*=2; 16 | if(head->val==1) res++; 17 | head=head->next; 18 | } 19 | return res; 20 | 21 | } 22 | }; -------------------------------------------------------------------------------- /countConsistentStrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countConsistentStrings(string allowed, vector& words) { 4 | 5 | /* 6 | convert string to set -- 7 | linear search on words 8 | */ 9 | set unique; 10 | for(auto &c : allowed) { 11 | if(unique.find(c) == unique.end()) 12 | unique.insert(c); 13 | } 14 | 15 | int countConsistent = 0; 16 | for(auto &word : words) { 17 | bool checkFlag = true; 18 | for(auto &chr : word) { 19 | //if not present flag & break.. 20 | if(unique.find(chr) == unique.end()) { 21 | checkFlag = false; break; 22 | } 23 | } 24 | if(checkFlag) 25 | countConsistent++; 26 | } 27 | 28 | return countConsistent; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /count_and_say.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string countAndSay(int n) { 4 | if (n == 1) 5 | return "1"; 6 | 7 | string prev = countAndSay(n-1); 8 | string cur = ""; 9 | int count = 1; 10 | 11 | for (int i = 0; i < prev.length()-1; i++) { 12 | if (prev[i] == prev[i+1]) { 13 | count++; 14 | } 15 | else { 16 | cur += to_string(count); 17 | cur += prev[i]; 18 | count = 1; 19 | } 20 | } 21 | 22 | cur += to_string(count); 23 | cur += prev.back(); 24 | 25 | return cur; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /count_negative_in_2d.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNegatives(vector>& grid) { 4 | 5 | if(grid.size() == 0) return 0; 6 | int cn = 0; 7 | 8 | for(int i=grid.size()-1; i>=0; i--){ 9 | for(int j=grid[i].size()-1; j>=0; j--){ 10 | if(grid[i][j] < 0) 11 | cn++; 12 | if(grid[i][j] >= 0) 13 | break; 14 | } 15 | } 16 | return cn; 17 | } 18 | }; -------------------------------------------------------------------------------- /count_number_of_teams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTeams(vector& rating) { 4 | if(rating.size() == 0) return 0; 5 | int c=0; 6 | for(int i=0; i< rating.size()-2; i++){ 7 | for(int j=i+1; j< rating.size()-1; j++){ 8 | for(int k=j+1; k rating[j] && rating[j] > rating[k])) c++; 10 | } 11 | } 12 | } 13 | return c; 14 | } 15 | }; -------------------------------------------------------------------------------- /count_palindromic_substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s): 3 | 4 | leftrights = [(x,x) for x in list(range(len(s)))] + [(x,x+1) for x in list(range(len(s)-1))] 5 | count = 0 6 | for left, right in leftrights: 7 | while left >= 0 and right < len(s) and s[left]==s[right]: 8 | count += 1 9 | left -= 1 10 | right += 1 11 | return count 12 | -------------------------------------------------------------------------------- /count_substrings_k_distinct_characters.py: -------------------------------------------------------------------------------- 1 | def substr(mystr, k): 2 | if mystr == None or k == 0: 3 | return 0 4 | ls = list() 5 | for i in range(len(mystr) - (k-1)): 6 | ls.append(mystr[i:i+k]) # set to remove duplicate k length strings 7 | 8 | res = set() 9 | for ele in ls: 10 | if len(set(ele)) == k: 11 | res.add(ele) 12 | return len(res) 13 | 14 | n = int(input()) 15 | for i in range(n): 16 | mystr = str(input()) 17 | k = int(input()) 18 | print(substr(mystr, k)) 19 | -------------------------------------------------------------------------------- /counting_bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int num) { 4 | vector ans; 5 | for(int i=0; i<=num; i++){ 6 | ans.push_back(__builtin_popcount(i)); 7 | } 8 | return ans; 9 | } 10 | 11 | }; -------------------------------------------------------------------------------- /course_schedule_iv.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { 4 | vector> adj(numCourses,vector(numCourses, false)); 5 | for(auto it : prerequisites) { 6 | adj[it[0]][it[1]] = true; 7 | } 8 | 9 | for(int k = 0; k < numCourses; k++) { 10 | for(int i = 0; i < numCourses; i++) { 11 | for(int j = 0; j < numCourses; j++) { 12 | if(!adj[i][j] && adj[i][k] && adj[k][j]) { 13 | adj[i][j]=true; 14 | } 15 | } 16 | } 17 | } 18 | 19 | vector result; 20 | for(auto it: queries) { 21 | result.push_back(adj[it[0]][it[1]]); 22 | } 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /defragmenting_ip_address.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string split(string s){ 4 | string new_str = ""; 5 | for(auto it=s.begin(); it!=s.end();it++){ 6 | if(*it != '.') 7 | new_str+= *it; 8 | else if(*it == '.') 9 | new_str += "[.]"; 10 | } 11 | return new_str; 12 | } 13 | string defangIPaddr(string address){ 14 | return split(address); 15 | } 16 | }; -------------------------------------------------------------------------------- /design_stack_with_increment_operation.cpp: -------------------------------------------------------------------------------- 1 | class CustomStack { 2 | public: 3 | int max; 4 | vector v; 5 | 6 | CustomStack(int maxSize) { 7 | max = maxSize; 8 | } 9 | 10 | void push(int x) { 11 | if(v.size() < max) v.push_back(x); 12 | } 13 | 14 | int pop() { 15 | if(v.size() == 0) return -1; 16 | int result = v.back(); 17 | v.pop_back(); 18 | return result; 19 | } 20 | 21 | void increment(int k, int val) { 22 | if(v.size() < k) k = v.size(); 23 | 24 | for(int i = 0; i < k; i++) { 25 | v[i] += val; 26 | } 27 | } 28 | }; 29 | 30 | /** 31 | * Your CustomStack object will be instantiated and called as such: 32 | * CustomStack* obj = new CustomStack(maxSize); 33 | * obj->push(x); 34 | * int param_2 = obj->pop(); 35 | * obj->increment(k,val); 36 | */ 37 | -------------------------------------------------------------------------------- /detect_capital.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | if(word.size() == 0) return false; 5 | auto capital = 0; 6 | auto flag = false; 7 | if(word[0] >= 'A' and word[0] <= 'Z') flag = true; 8 | 9 | for(auto i=1; i= 'A' and word[i] <= 'Z') capital++; 11 | } 12 | //if(capital < word.size()-1 and flag == true) return false; 13 | if((capital == 0) or (capital == word.size()-1 and flag == true)) return true; 14 | return false; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /distribute_coins_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int helper(TreeNode* root, int &sum) { 15 | if(!root) return 0; 16 | 17 | int l = helper(root->left, sum); 18 | int r = helper(root->right, sum); 19 | sum += abs(l) + abs(r); 20 | return root->val + l + r - 1; 21 | } 22 | 23 | int distributeCoins(TreeNode* root) { 24 | int sum = 0; 25 | helper(root, sum); 26 | return sum; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /duplicate_zeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def duplicateZeros(self, arr: List[int]) -> None: 3 | """ 4 | Do not return anything, modify arr in-place instead. 5 | """ 6 | zero_shifts = arr.count(0) 7 | l = len(arr) 8 | for i in range(l-1, -1, -1): 9 | if i + zero_shifts < l: 10 | arr[i + zero_shifts] = arr[i] 11 | #print(i, zero_shifts, arr[i + zero_shifts]) 12 | if arr[i] == 0: 13 | zero_shifts -= 1 14 | if i + zero_shifts < l: 15 | arr[i + zero_shifts] = 0 16 | #print(i, zero_shifts, arr[i + zero_shifts]) 17 | 18 | 19 | -------------------------------------------------------------------------------- /evaluate_reverse_polish_notation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector& tokens) { 4 | stack s; 5 | for(auto& t : tokens) { 6 | if(t == "+" || t == "-" || t == "*" || t == "/") { 7 | int op1 = s.top(); s.pop(); 8 | int op2 = s.top(); s.pop(); 9 | if(t == "+") op1 = op2 + op1; 10 | if(t == "-") op1 = op2 - op1; 11 | if(t == "/") op1 = op2 / op1; 12 | if(t == "*") op1 = op2 * op1; 13 | s.push(op1); 14 | } 15 | else { 16 | s.push(stoi(t)); // str to int 17 | } 18 | } 19 | return s.top(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /excel_sheet_column_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string s) { 4 | int result = 0; 5 | 6 | for(auto c : s) { 7 | int decimal = c - 'A' + 1; //convert 0 based indexing to 1 based indexing hence added once 8 | result = result * 26 + decimal; 9 | } 10 | 11 | return result; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /find_disappeared_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | 4 | for i in range(len(nums)): 5 | m = abs(nums[i]) - 1 6 | if nums[m] > 0: 7 | nums[m] = -nums[m] 8 | res = [] 9 | for i in range(len(nums)): 10 | if nums[i] > 0: 11 | res.append(i + 1) 12 | return res 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /find_duplicates_file_system.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, paths: List[str]) -> List[List[str]]: 3 | M = collections.defaultdict(list) 4 | for line in paths: 5 | data = line.split() 6 | root = data[0] 7 | for file in data[1:]: 8 | name, _, content = file.partition('(') 9 | M[content[:-1]].append(root + '/' + name) 10 | return [x for x in M.values() if len(x) > 1] -------------------------------------------------------------------------------- /find_elements_in_contaminated_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class FindElements: 8 | #dfs 9 | def __init__(self, root: TreeNode): 10 | self.res = set() 11 | x = [(root, 0)] 12 | 13 | while x: 14 | node, value = x.pop(0) 15 | node.val = value 16 | self.res.add(value) 17 | if node.left: 18 | x.append((node.left,(2*value+1))) 19 | if node.right: 20 | x.append((node.right,(2*value+2))) 21 | 22 | def find(self, target: int) -> bool: 23 | return target in self.res 24 | 25 | 26 | # Your FindElements object will be instantiated and called as such: 27 | # obj = FindElements(root) 28 | # param_1 = obj.find(target) 29 | -------------------------------------------------------------------------------- /find_first_missing_positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | 5 | int tofind = 1; 6 | while(1){ 7 | if(find(nums.begin(), nums.end(), tofind) == nums.end()) 8 | return tofind; 9 | tofind++; 10 | } 11 | return -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /find_median_from_stream.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | public: 3 | priority_queue maxHeap; 4 | priority_queue, greater<> > minHeap; 5 | /* 6 | 1) store first half in maxheap, second half in minheap 7 | 2) maxheap can have 1 element more than minheap 8 | */ 9 | void addNum(int num) { 10 | maxHeap.push(num); 11 | minHeap.push(maxHeap.top()); 12 | maxHeap.pop(); 13 | 14 | if(minHeap.size() > maxHeap.size()){ 15 | maxHeap.push(minHeap.top()); 16 | minHeap.pop(); 17 | } 18 | } 19 | double findMedian() { 20 | if(maxHeap.size() == minHeap.size()) { 21 | return (maxHeap.top() + minHeap.top()) / 2.0; 22 | } 23 | return maxHeap.top(); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /find_next_right_node_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /*----find next right node -----*/ 2 | Node *findNextRightNode(Node* root, int k){ 3 | if(!root) return NULL; 4 | queue q; 5 | q.push(root); 6 | 7 | while(!q.empty()){ 8 | int sz = q.size(); 9 | while(sz-- > 0){ 10 | Node *curr = q.front(); 11 | q.pop(); 12 | if(curr->data == k){ 13 | if(sz) 14 | printf("%d ", q.front()->data); 15 | else 16 | printf(-1); 17 | return; 18 | } 19 | if(curr->left) 20 | q.push(curr->left); 21 | if(curr->right) 22 | q.push(curr->right); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /find_original_array_from_doubled_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOriginalArray(vector& changed) { 4 | unordered_map freq; 5 | for (auto num : changed) freq[num]++; 6 | 7 | sort(changed.begin(), changed.end()); 8 | 9 | vector res; 10 | for (auto num : changed) { 11 | if (freq[num] && freq[num*2]) { 12 | freq[num]--; 13 | freq[num*2]--; 14 | res.push_back(num); 15 | } 16 | } 17 | 18 | for (auto [a, b] : freq) 19 | if (b) return {}; 20 | 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /find_peak_element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(const vector &num) { 4 | 5 | if (num.size() <= 1) return 0; //if only one element return 0th index 6 | 7 | int mid = 0, l = 0, h = num.size() - 1; 8 | while (l < h) { 9 | mid = l + (h-l) / 2; 10 | if (num[mid] > num[mid + 1]) 11 | h = mid; 12 | else if (num[mid] < num[mid + 1]) 13 | l = mid + 1; 14 | } 15 | 16 | return l; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /find_right_interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRightInterval(vector>& intervals) { 4 | 5 | if(intervals.size() <= 1) return {-1}; 6 | 7 | map mp; 8 | //map is naturally ordered data structure 9 | 10 | vector result(intervals.size()); 11 | 12 | for(int i=0; i returns first value >/= intervals[i][1] 23 | auto it = mp.lower_bound(intervals[i][1]); 24 | if(it != mp.end()) 25 | result[i] = it->second; 26 | else 27 | result[i] = -1; 28 | } 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /find_smallest_set_of_vertices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSmallestSetOfVertices(int n, vector>& edges) { 4 | //find all nodes in DAG with inDegree as 0 5 | 6 | vector res, indegree(n); 7 | 8 | for(auto &edge: edges) { 9 | indegree[edge[1]]++; 10 | } 11 | 12 | for(int i=0; i!=n; ++i) { 13 | if(indegree[i]==0) { 14 | res.push_back(i); 15 | } 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /find_the_difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | from collections import Counter 4 | hashed_s, hashed_t = dict(Counter(s)), dict(Counter(t)) 5 | found = "" 6 | for char in t: 7 | if char not in hashed_s: 8 | found = char 9 | return found 10 | elif hashed_s[char] != hashed_t[char]: 11 | found = char 12 | return found 13 | return None -------------------------------------------------------------------------------- /find_words_formed_by_characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countCharacters(vector& words, string chars) { 4 | 5 | vector mp(26), tmp(26); 6 | 7 | for(auto s:chars) 8 | mp[s - 'a']++; 9 | 10 | tmp = mp; 11 | auto result = 0; 12 | 13 | for(auto w:words){ 14 | 15 | mp = tmp; 16 | bool flag = true; 17 | 18 | for(auto i:w){ 19 | if(mp[i-'a'] == 0){ 20 | flag = false; 21 | break; 22 | } 23 | else 24 | mp[i - 'a']--; 25 | } 26 | if(flag) 27 | result += w.size(); 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /first_and_last_element_of_target.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int binarySearch(vector& n, int t, bool flag){ 4 | if(n.size() == 0) return -1; 5 | 6 | int l = 0, h = n.size(); 7 | 8 | while(l < h){ 9 | 10 | int mid = (l+h)/2; 11 | if(n[mid] > t || (n[mid] == t && flag)) 12 | h = mid; 13 | else 14 | l = mid + 1; 15 | } 16 | return l; 17 | } 18 | vector searchRange(vector& nums, int target) { 19 | if(nums.size() == 0) return {-1,-1}; 20 | int l = binarySearch(nums , target, true); 21 | if(l == nums.size() || nums[l] != target) 22 | return {-1, -1}; 23 | 24 | return {l, binarySearch(nums, target, false)-1}; 25 | } 26 | }; -------------------------------------------------------------------------------- /first_bad_version.cpp: -------------------------------------------------------------------------------- 1 | // The API isBadVersion is defined for you. 2 | // bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | 8 | int mid, left = 0, right = n; 9 | while(left < right) { 10 | 11 | //find mid 12 | mid = left + (right - left) / 2; 13 | 14 | //condition 15 | if(isBadVersion(mid)) { 16 | right = mid; 17 | } 18 | 19 | //else 20 | else { 21 | left = mid + 1; 22 | } 23 | } 24 | return left; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /flatten_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def __init__(self): 10 | self.prev = None 11 | 12 | def flatten(self, root: TreeNode) -> None: 13 | """ 14 | Do not return anything, modify root in-place instead. 15 | #reverse postorder traversal 16 | 17 | """ 18 | if not root: return None 19 | 20 | self.flatten(root.right) 21 | self.flatten(root.left) 22 | 23 | root.right = self.prev 24 | root.left = None 25 | self.prev = root 26 | 27 | -------------------------------------------------------------------------------- /flip_equivalent.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 15 | if (!root1 && !root2) return true; 16 | if (!root1 && root2 || root1 && !root2 || root1->val != root2->val) 17 | return false; 18 | 19 | return flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right)|| flipEquiv(root1->right, root2->left) && flipEquiv(root1->left, root2->right); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /flippin_an_image.py: -------------------------------------------------------------------------------- 1 | #mysolution 2 | class Solution: 3 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 4 | A_rev = [x[::-1] for x in A] 5 | # print(A_rev) 6 | A_inv = [] 7 | for ls in A_rev: 8 | curr, t = ls, [] 9 | for i in range(len(curr)): 10 | if curr[i] == 1: 11 | t.append(0) 12 | else: 13 | t.append(1) 14 | A_inv.append(t) 15 | return A_inv 16 | 17 | #optimised 18 | class Solution: 19 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 20 | return [[1 ^ i for i in x[::-1]] for x in A] -------------------------------------------------------------------------------- /gas_station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | 5 | int n = gas.size(); 6 | int total_delta = 0, delta = 0; 7 | int start = 0, i = 0; 8 | 9 | while(i < n) { 10 | total_delta += gas[i] - cost[i]; 11 | delta += gas[i] - cost[i]; 12 | 13 | if(delta < 0) { 14 | delta = 0; 15 | start = i + 1; 16 | } 17 | i++; 18 | } 19 | 20 | if(total_delta < 0) return -1; 21 | else return start; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /generate_parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateParenthesis(int n) { 4 | if(n == 0) return vector(); 5 | int open = n, close = n; 6 | vector result; 7 | solve("", open, close, result); 8 | return result; 9 | } 10 | 11 | void solve(string operations, int open, int close, vector &result) { 12 | 13 | if(open == 0 and close == 0){ 14 | result.push_back(operations); 15 | return; 16 | } 17 | 18 | if(open > 0) { 19 | solve(operations + "(", open-1, close, result); 20 | } 21 | if(close > open ) { 22 | solve(operations + ")", open, close-1, result); 23 | } 24 | return; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /hamming_distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingDistance(int x, int y) { 4 | int op1, op2; 5 | long long int distance = 0; 6 | while(x > 0 || y > 0){ 7 | op1 = x % 2; 8 | op2 = y % 2; 9 | distance += (op1 ^ op2); 10 | x /= 2; 11 | y /= 2; 12 | } 13 | cout< tmp; 6 | 7 | while(n != 1) 8 | { 9 | if(tmp[n] == 0) 10 | tmp[n]++; 11 | else 12 | return false; 13 | 14 | int sum = 0; 15 | while(n != 0) 16 | { 17 | sum += pow(n % 10,2); 18 | n = n / 10; 19 | } 20 | 21 | n = sum; 22 | } 23 | 24 | return true; 25 | } 26 | }; -------------------------------------------------------------------------------- /hashcode_more_pizza.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int mod=1e9+7; 5 | #define F(a,b,var) for(int var=a;var>M>>N; 16 | int W = M; 17 | vector types(N), result; 18 | ll total = 0; 19 | 20 | for(auto i=0; i>types[i]; 22 | 23 | for(auto i=N-1; i>=0; i--){ 24 | if(M >= types[i]){ 25 | total+=types[i]; 26 | M -= types[i]; 27 | //cout< int: 3 | return sum(h1 != h2 for h1,h2 in zip(heights, sorted(heights))) 4 | -------------------------------------------------------------------------------- /hello_world.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avidLearnerInProgress/leetcode-solutions/5015f38252a1c7f39f690df294a973eebbc22c90/hello_world.py -------------------------------------------------------------------------------- /house_robbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | if(nums.empty())return 0; 5 | int a = 0 ,b = 0; 6 | for(int i=0; i=b ? a: b; 5 | } 6 | int rob(vector& nums) { 7 | int a = 0, b = 0; 8 | 9 | for(int i=0; i& nums) { 4 | 5 | int min_ = INT_MAX, nmin_ = INT_MAX; 6 | 7 | for(auto num : nums){ 8 | min_ = min(min_, num); 9 | if(num > min_) 10 | nmin_ = min(nmin_, num); 11 | if(num > nmin_) 12 | return true; 13 | } 14 | return false; 15 | } 16 | }; -------------------------------------------------------------------------------- /inorder_predecessor_in_bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of TreeNode: 3 | * class TreeNode { 4 | * public: 5 | * int val; 6 | * TreeNode *left, *right; 7 | * TreeNode(int val) { 8 | * this->val = val; 9 | * this->left = this->right = NULL; 10 | * } 11 | * } 12 | */ 13 | 14 | class Solution { 15 | public: 16 | /** 17 | * @param root: the given BST 18 | * @param p: the given node 19 | * @return: the in-order predecessor of the given node in the BST 20 | */ 21 | TreeNode * inorderPredecessor(TreeNode * root, TreeNode * p) { 22 | // write your code here 23 | 24 | 25 | if(root == nullptr) { 26 | return nullptr; 27 | } 28 | 29 | if(root->val >= p->val) { 30 | return inorderPredecessor(root->left, p); 31 | } 32 | 33 | TreeNode *pre = inorderPredecessor(root->right, p); 34 | return pre == nullptr ? root : pre; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /inorder_successor_in_bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | /* 15 | * @param root: The root of the BST. 16 | * @param p: You need find the successor node of p. 17 | * @return: Successor of p. 18 | */ 19 | 20 | TreeNode *successor = nullptr; 21 | TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) { 22 | // write your code here 23 | 24 | if(root == nullptr) { 25 | return nullptr; 26 | } 27 | 28 | if(root->val <= p->val) { 29 | return inorderSuccessor(root->right, p); 30 | } 31 | 32 | TreeNode *successor = inorderSuccessor(root->left, p); 33 | return successor == nullptr ? root : successor; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /integer_to_roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string intToRoman(int num) { 4 | if(num == 0) return ""; 5 | 6 | string table[4][10] = { 7 | {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, 8 | {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, 9 | {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, 10 | {"", "M", "MM", "MMM"} 11 | }; 12 | 13 | //2538 => run through this example when revisiting code. 14 | 15 | int count = 0; //gives the index of row in table.. 10's place, 100's place, 1000's place 16 | string result = ""; 17 | while(num > 0) { 18 | int value = num % 10; //gives the index in the row of table basicall 19 | result = table[count][value] + result; 20 | count++; 21 | num /= 10; 22 | } 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /interleaving_string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 3 | if len(s1) + len(s2) != len(s3): return False 4 | m, n = len(s1), len(s2) 5 | 6 | @lru_cache(None) 7 | def dp(i, j): 8 | if i == m and j == n: return True # Found a valid match 9 | ans = False 10 | if i < m and s1[i] == s3[i+j]: # Case match s1[i] with s3[i+j] 11 | ans |= dp(i + 1, j) 12 | if j < n and s2[j] == s3[i+j]: # Case match s2[j] with s3[i+j] 13 | ans |= dp(i, j + 1) 14 | return ans 15 | 16 | return dp(0, 0) 17 | -------------------------------------------------------------------------------- /intersection_of_2_arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | 4 | ''' 5 | if len(nums1) == 0 or len(nums2) == 0: 6 | return [] 7 | st = set() 8 | for ele in nums1: 9 | if ele in nums2: 10 | st.add(ele) 11 | return list(st) 12 | ''' 13 | return list(set(nums1) & set(nums2)) -------------------------------------------------------------------------------- /is_subtree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSame(TreeNode *s, TreeNode *t){ 13 | if(s==NULL || t==NULL) return s == t; 14 | 15 | if(s->val != t->val) return false; 16 | 17 | return isSame(s->left, t->left) && isSame(s->right, t->right); 18 | } 19 | 20 | bool isSubtree(TreeNode* s, TreeNode* t) { 21 | if(s==NULL) return false; 22 | if(isSame(s, t)) return true; 23 | return isSubtree(s->left, t) || isSubtree(s->right, t); 24 | } 25 | }; -------------------------------------------------------------------------------- /island_perimeter.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int islandPerimeter(vector>& grid) { 4 | 5 | int m = grid.size(), n = grid[0].size(); 6 | int perimeter, area=0, repeated=0; 7 | 8 | for(int i=0; i 0 and grid[i-1][j] == 1) repeated++; 14 | if(j > 0 and grid[i][j-1] == 1) 15 | repeated++; 16 | } 17 | } 18 | } 19 | return (4 * area) - (2 * repeated); 20 | } 21 | }; -------------------------------------------------------------------------------- /isomorphic_strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | if len(s) != len(t): 4 | return False 5 | d = {} 6 | for a, b in zip(s, t): 7 | if a in d: 8 | if d[a] != b: 9 | return False 10 | else: 11 | d[a] = b 12 | sett = set(d.values()) 13 | 14 | if len(d.values()) == len(sett): 15 | return True 16 | else: 17 | return False -------------------------------------------------------------------------------- /iterator_for_combination.cpp: -------------------------------------------------------------------------------- 1 | class CombinationIterator { 2 | string s; 3 | queue q; 4 | 5 | void getCombination(int start, int length, string txt){ 6 | if(length == 0){ 7 | q.push(txt); 8 | return; 9 | } 10 | 11 | for(int i = start; i <= s.length() - length; ++i) 12 | getCombination(i+1, length-1, txt + s[i]); 13 | } 14 | public: 15 | CombinationIterator(string characters, int combinationLength) { 16 | s = characters; 17 | string txt = ""; 18 | getCombination(0, combinationLength, txt); 19 | } 20 | 21 | string next() { 22 | string str = q.front(); 23 | q.pop(); 24 | return str; 25 | } 26 | 27 | bool hasNext() { 28 | return !q.empty(); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /jewels_and_stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numJewelsInStones(string J, string S) { 4 | if(J == "") return 0; 5 | if(S == "") return 0; 6 | 7 | int ct = 0; 8 | for(auto const &n : J){ 9 | ct += count(S.begin(), S.end(), n); 10 | } 11 | return ct; 12 | } 13 | }; -------------------------------------------------------------------------------- /jumpy_game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | 5 | int i = 0; 6 | for(int reach = 0; i < nums.size() && i <= reach; ++i) 7 | reach = max(i + nums[i], reach); 8 | return i == nums.size(); 9 | } 10 | }; -------------------------------------------------------------------------------- /keys_and_rooms.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void dfs(vector> &graph, int s, vector &vis){ 3 | vis[s] = true; 4 | for(int i = 0; i < graph[s].size(); i++){ 5 | if(!vis[graph[s][i]]){ 6 | dfs(graph, graph[s][i], vis); 7 | } 8 | } 9 | } 10 | 11 | public: 12 | bool canVisitAllRooms(vector>& rooms) { 13 | int i, n=rooms.size(); 14 | vector vis(n, false); 15 | dfs(rooms, 0, vis); 16 | for(i = 0; i < n; i++){ 17 | if(!vis[i]){ 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /kth_grammar.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthGrammar(self, n: int, k: int) -> int: 3 | # pattern - 4 | # for nth row 5 | # + mutate the (n-1)th row 6 | # + negate the (n-1)th row 7 | 8 | if n == 1 or k == 1: 9 | return 0 10 | 11 | mid = pow(2, n - 1) // 2 12 | 13 | if k <= mid: 14 | return self.kthGrammar(n - 1, k) 15 | else: 16 | return (int) (not self.kthGrammar(n - 1, k - mid)) 17 | -------------------------------------------------------------------------------- /kth_largest_element_in_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | 5 | make_heap(nums.begin(), nums.end()); 6 | for(auto i=0; i, greater > Q; 5 | KthLargest(int k, vector& nums) { 6 | size = k; 7 | for(auto num : nums) { 8 | Q.push(num); 9 | if(Q.size() > k) Q.pop(); //only keep k elements in the Queue 10 | } 11 | } 12 | 13 | int add(int val) { 14 | Q.push(val); 15 | if(Q.size() > size) Q.pop(); 16 | return Q.top(); 17 | } 18 | }; 19 | 20 | /** 21 | * Your KthLargest object will be instantiated and called as such: 22 | * KthLargest* obj = new KthLargest(k, nums); 23 | * int param_1 = obj->add(val); 24 | */ 25 | -------------------------------------------------------------------------------- /largest_merge_of_two_strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestMerge(string word1, string word2) { 4 | string ans=""; 5 | while(!word1.empty() || !word2.empty()) { 6 | if(word1[0]>word2[0]) { 7 | ans+=word1[0]; 8 | word1.erase(word1.begin()); 9 | }else if(word1[0] str: 3 | 4 | for i in range(len(num) - 1, -1, -1): 5 | if int(num[i]) % 2 == 1: 6 | return num[:i+1] 7 | return "" 8 | -------------------------------------------------------------------------------- /last_stone_weight.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lastStoneWeight(vector& stones) { 4 | priority_queue Q; 5 | for(auto stone : stones) { 6 | Q.emplace(stone); 7 | } 8 | 9 | while(!Q.empty()) { 10 | if(Q.size() == 1) return Q.top(); 11 | int x = Q.top(); Q.pop(); 12 | int y = Q.top(); Q.pop(); 13 | if(x != y) 14 | Q.push(x - y); 15 | } 16 | return 0; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /lca_in_bst.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 10 | if not root or not p or not q: 11 | return None 12 | 13 | #max of two < root; then the other has to be less than root which means that both p and q lie in left subtree 14 | if (max(p.val, q.val) < root.val): 15 | return self.lowestCommonAncestor(root.left, p, q) 16 | 17 | #min of two > root; then the other has to be greater than root which means that both p and q lie in right subtree 18 | elif min(p.val, q.val) > root.val: 19 | return self.lowestCommonAncestor(root.right, p, q) 20 | 21 | else: 22 | return root 23 | 24 | -------------------------------------------------------------------------------- /leaf_similar_trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def findleaf(self, root): 10 | if not root: return [] 11 | if not (root.left or root.right): return [root.val] 12 | return self.findleaf(root.left) + self.findleaf(root.right) 13 | 14 | 15 | def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: 16 | return self.findleaf(root1) == self.findleaf(root2) 17 | 18 | -------------------------------------------------------------------------------- /length_of_last_word.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | private: 4 | static inline void rtrim(std::string &s) { 5 | s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { 6 | return !std::isspace(ch); 7 | }).base(), s.end()); 8 | } 9 | 10 | public: 11 | int lengthOfLastWord(string s) { 12 | if(isspace(s[0]) and s.length() == 1) return 0; 13 | int cnt = 0; 14 | rtrim(s); 15 | for(int i=s.length()-1; i>=0; i--) { 16 | if(!isspace(s[i])) cnt++; 17 | else break; 18 | } 19 | return cnt; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /letter_case_permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void dfs(string& S, vector &permutations, int index, string path) { 5 | 6 | if(index == S.size()){ 7 | permutations.push_back(path); 8 | return; 9 | } 10 | 11 | if(isalpha(S[index])){ 12 | char t1 = tolower(S[index]); 13 | char t2 = toupper(S[index]); 14 | dfs(S, permutations, index + 1, path + t1); 15 | dfs(S, permutations, index + 1, path + t2); 16 | } 17 | else{ 18 | dfs(S, permutations, index + 1, path + S[index]); 19 | } 20 | 21 | } 22 | 23 | vector letterCasePermutation(string S) { 24 | 25 | if(S.size() == 0) return {}; 26 | vector permutations; 27 | dfs(S, permutations, 0, ""); 28 | return permutations; 29 | } 30 | }; -------------------------------------------------------------------------------- /letter_combinations_of_phone_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | def dfsSearch(number,stringToPassDown): 4 | for each in number: 5 | tempString = stringToPassDown 6 | tempString = tempString + each 7 | 8 | if len(tempString) < len(digits): 9 | dfsSearch(dict[digits[len(tempString)]],tempString) 10 | elif len(tempString) == len(digits): 11 | answer.append(tempString) 12 | else: 13 | None 14 | answer = [] 15 | dict = {'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6':['m','n','o'],'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']} 16 | if len(digits) == 0: 17 | return answer 18 | 19 | stringToPassDown = "" 20 | dfsSearch(dict[digits[0]],stringToPassDown) 21 | return answer -------------------------------------------------------------------------------- /long_pressed_name.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isLongPressedName(string name, string typed) { 4 | int i = 0, m = name.length(), n = typed.length(); 5 | for (int j = 0; j < n; ++j) 6 | if (i < m && name[i] == typed[j]) 7 | ++i; 8 | else if (!j || typed[j] != typed[j - 1]) 9 | return false; 10 | return i == m; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /longest_common_prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | if(strs.size() == 0) return ""; 5 | string lcp = ""; 6 | 7 | int ind = 0; 8 | for(char c : strs[0]){//for each character in string0 9 | for(int i=1; i int: 3 | nums = set(nums) 4 | best = 0 5 | for x in nums: 6 | if x - 1 not in nums: 7 | y = x + 1 8 | while y in nums: 9 | y += 1 10 | best = max(best, y - x) 11 | return best -------------------------------------------------------------------------------- /longest_common_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestCommonSubsequence(string text1, string text2) { 4 | 5 | int m = text1.size(), n = text2.size(); 6 | 7 | if(m == 0 or n == 0) return 0; 8 | 9 | vector> dp(m+1, vector(n+1)); 10 | for(int i=0; i<=m; i++){ 11 | for(int j=0; j<=n; j++){ 12 | if(i==0) dp[i][j] = 0; 13 | else if(j==0) dp[i][j] = 0; 14 | 15 | else{ 16 | if(text1[i-1] == text2[j-1]) 17 | dp[i][j] = dp[i-1][j-1] + 1; 18 | else 19 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 20 | } 21 | } 22 | } 23 | return dp[m][n]; 24 | } 25 | }; -------------------------------------------------------------------------------- /longest_harmonic_sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLHS(vector& nums) { 4 | unordered_mapm; 5 | for(auto i: nums) 6 | m[i]++; 7 | int res = 0; 8 | for(auto it:m) 9 | if(m.count(it.first-1)>0) 10 | res = max(res, it.second+m[it.first-1]); 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /longest_increasing_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | if(nums.size() == 0) return 0; 5 | 6 | vector dp(nums.size()); 7 | dp[0] = 1; 8 | 9 | for(int i = 1; in: 17 | while len(set(q))>n: 18 | q.popleft() 19 | if len(set(q))==n: 20 | l=max(l,len(q)) 21 | if l==0: 22 | print(-1) 23 | else: 24 | print(l) -------------------------------------------------------------------------------- /longest_palindrome.py: -------------------------------------------------------------------------------- 1 | # from collections import Counter 2 | # class Solution: 3 | # def longestPalindrome(self, s: str) -> int: 4 | # hashed = dict(Counter(s)) 5 | # sz, szz = 1, len(s) 6 | # for ele in hashed.values(): 7 | # if ele % 2 == 0: 8 | # sz += (ele -1) 9 | # else: 10 | # sz += ele 11 | # if sz > szz: 12 | # return szz 13 | # else: 14 | # return sz 15 | class Solution(object): 16 | from collections import Counter 17 | def longestPalindrome(self, s): 18 | m = set() 19 | count = 0 20 | for c in s: 21 | if c in m: 22 | m.remove(c) 23 | count += 1 24 | else: 25 | m.add(c) 26 | return count * 2 + 1 if len(m) != 0 else count * 2 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /longest_palindromic_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindromeSubseq(string s) { 4 | 5 | if(s == "") return 0; 6 | vector> dp(s.size(), vector(s.size(), 0)); 7 | 8 | for(int i=0; i=0; i--){ 13 | for(int j=i+1; j "< int: 3 | maxcnt, res = 0, 0 4 | counts = collections.Counter() #[0] * 26 5 | for i in range(len(s)): 6 | counts[s[i]] += 1 7 | maxcnt = max(maxcnt, counts[s[i]]) 8 | if res - maxcnt < k: 9 | res += 1 10 | #print('Curr res:'+ str(res)) 11 | else: 12 | counts[s[i - res]] -= 1 13 | #print(str(s[i - res]) + "--" + str(counts[s[i - res]])) 14 | return res 15 | 16 | -------------------------------------------------------------------------------- /longest_valid_parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestValidParentheses(self, s: str) -> int: 3 | if not s: return 0 4 | result, ind = 0, -1 5 | count, len_ = 0, 0 6 | for i in range(len(s)): 7 | len_ += 1 8 | if s[i] == '(': 9 | count += 1 10 | if s[i] == ')': 11 | count -= 1 12 | if count == 0 and len_ > result: 13 | result = len_ 14 | if count < 0: 15 | len_, count = 0, 0 16 | 17 | len_, count = 0, 0 18 | for i in range(len(s)-1, -1, -1): 19 | len_ += 1 20 | if s[i] == ')': 21 | count += 1 22 | if s[i] == '(': 23 | count -= 1 24 | if count == 0 and len_ > result: 25 | result = len_ 26 | if count < 0: 27 | len_, count = 0, 0 28 | 29 | return result -------------------------------------------------------------------------------- /majority_element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | if(nums.size() == 0) return -1; 5 | int candidate = 0; 6 | int count = 1; 7 | 8 | for(int i=0; i int: 3 | #Boyer - Moore Major Vote Algorithm 4 | 5 | major, count = nums[0], 1 6 | for i in range(1, len(nums)): 7 | if count == 0: 8 | count += 1 9 | major = nums[i] 10 | elif major == nums[i]: 11 | count += 1 12 | else: 13 | count -= 1 14 | return major 15 | 16 | #normal sorting 17 | #return sorted(nums)[len(nums)//2] -------------------------------------------------------------------------------- /max_chunks_to_make_sorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxChunksToSorted(vector& arr) { 4 | 5 | int max_ = 0, result = 0; 6 | //we find the max_seen_so_far 7 | //and if max_seen_so_far == current_index, we can divide the array in one chunk. 8 | 9 | for(int i=0; i& arr) { 4 | 5 | /* 6 | //if we have all elements towards left less than all elements towards right, then we have discovered a chunk 7 | //keep track of right min using rightMinArray 8 | //iterate over the actual array and calculate left max 9 | */ 10 | 11 | int N = arr.size(); 12 | vector trackRightMin(N); 13 | int result = 0, max_ = INT_MIN; 14 | 15 | 16 | trackRightMin[N-1] = arr[N-1]; 17 | for(int i=N-2; i>=0; --i) 18 | trackRightMin[i] = min(trackRightMin[i+1], arr[i]); 19 | 20 | for(int i=0; i& nums) { 4 | int cnt = 0, mxc = INT_MIN; 5 | 6 | for(int i=0; i int: 10 | if not root: 11 | return 0 12 | 13 | return 1 + max(self.maxDepth(root.left), self.maxDepth( root.right)) -------------------------------------------------------------------------------- /max_distance_to_closest_person.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDistToClosest(vector& seats) { 4 | int n = seats.size(); 5 | int empty = 0; 6 | int result = 0; 7 | int idx1 = -1, idx2 = -1; 8 | 9 | for(int i = 0; i < n; ++i){ 10 | if(seats[i] == 1){ //internal seats 11 | empty = 0; 12 | if(idx1 == -1) idx1 = i; //pick the first 1(1 from start) in the array 13 | idx2 = i; //pick the second 1 in the array 14 | } else { //external seats 15 | empty++; 16 | result = max(result, (empty+1)/2); 17 | } 18 | } 19 | result = max({result, idx1, n-1-idx2}); //max among all of them 20 | return result; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /max_network_rank.cpp: -------------------------------------------------------------------------------- 1 | int solution(vector&A, vector&B,int N){ 2 | vector mymap(N+1,0); 3 | for(int i = 0 ; i < A.size() ; i++){ 4 | mymap[A[i]]++; 5 | mymap[B[i]]++; 6 | } 7 | int res = INT_MIN; 8 | for(int i = 0 ; i < A.size() ; i++) 9 | res = max(res,mymap[A[i]]+mymap[B[i]]-1); 10 | return res; 11 | } -------------------------------------------------------------------------------- /max_path_sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | int ans; 12 | public: 13 | int maxPathRec(TreeNode* root){ 14 | if(!root) return 0; 15 | 16 | int l = max(0, maxPathRec(root->left)); 17 | int r = max(0, maxPathRec(root->right)); 18 | 19 | ans = max(ans, l+r+root->val); 20 | return max(l, r) + root->val; 21 | } 22 | 23 | int maxPathSum(TreeNode* root) { 24 | ans = INT_MIN; 25 | maxPathRec(root); 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /max_product_of_length_of_two_palindromic_sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, s: str) -> int: 3 | subs = [] 4 | n = len(s) 5 | def dfs(curr, ind, inds): 6 | if ind == n: 7 | if curr == curr[::-1]: 8 | subs.append((curr, inds)) 9 | return 10 | dfs(curr+s[ind], ind+1, inds|{ind}) 11 | dfs(curr, ind+1, inds) 12 | 13 | dfs('', 0, set()) 14 | 15 | res = 0 16 | n = len(subs) 17 | for i in range(n): 18 | s1, i1 = subs[i] 19 | for j in range(i+1, n): 20 | s2, i2 = subs[j] 21 | if len(i1 & i2) == 0: 22 | res = max(res, len(s1)*len(s2)) 23 | return res 24 | -------------------------------------------------------------------------------- /max_product_subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int n = nums.size(); 5 | int result = nums[0]; 6 | int curr_max = nums[0]; 7 | int curr_min = nums[0]; 8 | for (int i = 1; i < n; i++) { 9 | int curr_max_prev = curr_max; 10 | curr_max = max(nums[i], max(curr_max * nums[i], curr_min * nums[i])); 11 | curr_min = min(nums[i], min(curr_max_prev * nums[i], curr_min * nums[i])); 12 | result = max(result, curr_max); 13 | } 14 | return result; 15 | } 16 | }; 17 | 18 | -------------------------------------------------------------------------------- /max_product_two_elements_in_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | if(nums.size() == 0) return -1; 5 | int k = 2; 6 | 7 | priority_queue> Q; 8 | 9 | for(auto num : nums) 10 | Q.emplace(num); 11 | 12 | vector res; 13 | while(k-- and !Q.empty()) { 14 | res.emplace_back(Q.top()); 15 | Q.pop(); 16 | } 17 | return ((res[0]-1) * (res[1]-1)); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /max_products_word_length.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, words: List[str]) -> int: 3 | n, maxres = len(words), 0 4 | wordsset = [set(i) for i in words] 5 | for i in range(n): 6 | for j in range(i+1,n): 7 | for char in wordsset[j]: 8 | if char in wordsset[i]: 9 | break 10 | else: 11 | maxres = max(maxres, len(words[i])*len(words[j])) 12 | return maxres -------------------------------------------------------------------------------- /max_score_from_removing_stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumScore(int a, int b, int c) { 4 | priority_queue maxHeap; 5 | 6 | maxHeap.push(a); 7 | maxHeap.push(b); 8 | maxHeap.push(c); 9 | int score = 0; 10 | 11 | while(maxHeap.size() > 1) { 12 | auto first = maxHeap.top(); 13 | maxHeap.pop(); 14 | 15 | auto second = maxHeap.top(); 16 | maxHeap.pop(); 17 | 18 | if(first > 0 and second > 0) { 19 | score++; 20 | maxHeap.push(first - 1); 21 | maxHeap.push(second - 1); 22 | } 23 | } 24 | 25 | return score; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /max_value_after_insertion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string maxValue(string n, int x) { 4 | char c = ('0' + x); 5 | string ans = ""; 6 | int i = 0; 7 | 8 | if(n[0] != '-') { 9 | while(i < n.size() && c <= n[i]) 10 | ans += n[i++]; 11 | ans += c; 12 | 13 | while(i < n.size()) 14 | ans += n[i++]; 15 | } 16 | 17 | else { 18 | ans += '-'; 19 | i = 1; 20 | while(i < n.size() && n[i] <= c) 21 | ans += n[i++]; 22 | ans += c; 23 | while(i < n.size()) 24 | ans += n[i++]; 25 | } 26 | 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /maximum_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* constructMaximumBinaryTree(vector& nums) { 13 | stack stk; 14 | for (int num : nums) { 15 | TreeNode* node = new TreeNode(num); 16 | while (!stk.empty() && stk.top() -> val < node -> val) { 17 | node -> left = stk.top(); 18 | stk.pop(); 19 | } 20 | if (!stk.empty()) { 21 | stk.top() -> right = node; 22 | } 23 | stk.push(node); 24 | } 25 | while (stk.size() > 1) { 26 | stk.pop(); 27 | } 28 | return stk.top(); 29 | } 30 | }; -------------------------------------------------------------------------------- /maximum_binary_tree_2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* insertIntoMaxTree(TreeNode* root, int val) { 13 | 14 | TreeNode *curr = root; 15 | TreeNode *node = new TreeNode(val); 16 | 17 | if(curr->val < val){ 18 | node->left = curr; 19 | return node; 20 | } 21 | 22 | while(curr->right != NULL && curr->right->val > val){ 23 | curr = curr->right; 24 | } 25 | node->left = curr->right; 26 | curr->right = node; 27 | return root; 28 | } 29 | }; -------------------------------------------------------------------------------- /meeting_rooms.cpp: -------------------------------------------------------------------------------- 1 | struct meeting { 2 | int start, end, position; 3 | }; 4 | 5 | 6 | bool comparator(struct meeting m1, struct meeting m2) { 7 | if(m1.end < m2.end) return true; 8 | else if(m1.end > m2.end) return false; 9 | else if(m1.position < m2.position) return true; 10 | else return false; 11 | } 12 | 13 | 14 | int maxMeetings(int start[], int end[], int n) { 15 | // Your code here 16 | struct meeting meetings[n]; 17 | for(int i=0; i current_end) { 29 | current_end = meetings[i].end; 30 | result++; 31 | } 32 | } 33 | 34 | return result; 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /merge_2_binary_trees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 13 | if ( t1 && t2 ) { 14 | TreeNode * root = new TreeNode(t1->val + t2->val); 15 | root->left = mergeTrees(t1->left, t2->left); 16 | root->right = mergeTrees(t1->right, t2->right); 17 | return root; 18 | } 19 | else { 20 | return t1 ? t1 : t2; 21 | } 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /merge_k_sorted_lists_vectorised.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* mergeKLists(vector& lists) { 12 | 13 | map m; //value-count 14 | ListNode* it; 15 | 16 | for(ListNode *lst: lists){ 17 | it = lst; 18 | while(it != NULL){ 19 | m[it->val]++; 20 | it = it->next; 21 | } 22 | } 23 | 24 | auto ltr = new ListNode(0); 25 | auto head = ltr; 26 | 27 | for(pair p : m){ 28 | for(auto i=0; inext = new ListNode(p.first); 30 | ltr = ltr->next; 31 | } 32 | } 33 | return head->next; 34 | } 35 | }; -------------------------------------------------------------------------------- /minCostClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | 5 | 6 | if(cost.size() == 0) 7 | return 0; 8 | 9 | int minCost = 0; 10 | vector dp(cost.size() + 1, 0); 11 | 12 | dp[0] = cost[0]; 13 | dp[1] = cost[1]; 14 | 15 | for(int i=2; i> minimumAbsDifference(vector& arr) { 4 | sort(arr.begin(), arr.end()); 5 | 6 | int min_absolute_difference = INT_MAX; 7 | for(int i=0; i> varr; 12 | int curr_min = 0; 13 | for(int i=0; i& nums, int x) { 4 | 5 | int sum = 0; 6 | for(auto num : nums) sum += num; 7 | 8 | sum -= x; 9 | if(sum == 0) return nums.size(); 10 | 11 | 12 | int low = 0, cur = 0, mid = 0; 13 | for(int high = 0 ; high < nums.size(); high++) { 14 | cur += nums[high]; 15 | while(sum < cur and low < nums.size()) 16 | cur -= nums[low++]; 17 | 18 | if(sum == cur) 19 | mid = max(mid, high - low + 1); 20 | 21 | } 22 | 23 | return (mid == 0) ? -1 : nums.size() - mid; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /min_time_visiting_all_points.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minTimeToVisitAllPoints(vector>& points) { 4 | 5 | if(points.size() == 0) return 0; 6 | int min_time = 0; 7 | for(int i=1; i st; 5 | 6 | for(auto ch : s) { 7 | 8 | if(ch == '(') st.push(ch); 9 | else { 10 | if(!st.empty() and st.top() == '(') st.pop(); 11 | else st.push(ch); 12 | } 13 | 14 | } 15 | return st.size(); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /minimum_domino_rotations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int check(int x, vector& A, vector& B) 4 | { 5 | int a=0,b=0,k=0; 6 | for(int i=0;i& A, vector& B) { 21 | int x=check(A[0],A,B); 22 | if(x==-1) 23 | return check(B[0],A,B); 24 | return x; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /minimum_edit_distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | 5 | int M = word1.size(), N = word2.size(); 6 | 7 | vector> dp(M + 1, vector (N + 1, 0)); 8 | 9 | for(int i=1; i<=M; i++) 10 | dp[i][0] = i; 11 | 12 | for(int j=1; j<=N; j++) 13 | dp[0][j] = j; 14 | 15 | 16 | for(int i=1; i<=M; i++){ 17 | for(int j=1; j<=N; j++){ 18 | 19 | if(word1[i-1] == word2[j-1]) 20 | dp[i][j] = dp[i-1][j-1]; 21 | else{ 22 | dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])) + 1; 23 | } 24 | 25 | } 26 | } 27 | return dp[M][N]; 28 | } 29 | }; -------------------------------------------------------------------------------- /monotone_increasing_digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int monotoneIncreasingDigits(int N) { 4 | string str=to_string(N); 5 | int i; 6 | for(i=0; istr[i+1]) 8 | break; 9 | if(i==str.size()-1) 10 | return N; 11 | while(i>0 && str[i-1]>str[i]-1) 12 | i--; 13 | int num=0, j=0; 14 | while(ji) 18 | num=(num*10)+9; 19 | else 20 | num=(num*10)+(str[j]-'0'); 21 | j++; 22 | } 23 | return num; 24 | } 25 | }; -------------------------------------------------------------------------------- /monotonic_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIncreasing(vector &A) { 4 | for(int i=1; i A[i]){ 6 | cout< &A) { 14 | for(int i=1; i& A) { 23 | if(isIncreasing(A) || isDecreasing(A)) 24 | return true; 25 | return false; 26 | } 27 | }; -------------------------------------------------------------------------------- /most_stones_removed_with_same_row_or_column.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int n; 4 | vector vis; 5 | 6 | void dfs(int idx, vector> &stones){ 7 | vis[idx] = true; 8 | 9 | for(int i = 0; i < n; i++){ 10 | if(vis[i]) continue; 11 | if(stones[idx][0] == stones[i][0] || stones[idx][1] == stones[i][1]) 12 | dfs(i, stones); 13 | } 14 | return; 15 | } 16 | 17 | int removeStones(vector>& stones) { 18 | 19 | n = stones.size(); 20 | 21 | vis.resize(n, 0); 22 | 23 | int val = 0; 24 | 25 | for(int i = 0; i < n; i++){ 26 | if(vis[i]) continue; 27 | val++; 28 | dfs(i, stones); 29 | } 30 | 31 | return n - val; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /move_zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | 5 | int j = 0; 6 | 7 | for(int num : nums){ 8 | if(num != 0){ 9 | nums[j++] = num; 10 | } 11 | } 12 | 13 | for(; j children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution { 22 | public: 23 | vector result; 24 | 25 | void helper(Node* root) { 26 | if(!root) return; 27 | 28 | result.push_back(root->val); 29 | for(auto &n : root->children) { 30 | helper(n); 31 | } 32 | return; 33 | } 34 | vector preorder(Node* root) { 35 | if(!root) return vector(); 36 | helper(root); 37 | return result; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /network_delay_time.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int networkDelayTime(vector>& times, int N, int K) { 4 | vector d(N+1, 1000000); 5 | d[K]=0; 6 | for(int i=0;id[it[0]] + it[2]) 9 | d[it[1]]=d[it[0]]+it[2]; 10 | int res=*max_element(d.begin()+1, d.end()); 11 | if(res==1000000) return -1; 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /next_greater_element_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | int length = nums.size(); 5 | stack st; 6 | vector result(length, 0); 7 | 8 | 9 | // since, its a circular array, 10 | // we have create another copy of array elements towards its front 11 | // this behavior is captured by iterating over 2 * length indices and using (i % n)th index while accessing elements of nums 12 | for(int i = length * 2 - 1; i >= 0; i--) { 13 | 14 | while(!st.empty() and nums[i % length] >= st.top()) { 15 | st.pop(); 16 | } 17 | 18 | 19 | if(st.empty()) result[i % length] = -1; 20 | else result[i % length] = st.top(); 21 | 22 | st.push(nums[i % length]); 23 | } 24 | 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /next_greater_element_iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nextGreaterElement(int n) { 4 | string s = to_string(n); 5 | int i = s.size() - 2; 6 | // start from right 7 | // find the number x which is smaller than the next one 8 | for(; i >= 0; i--){ 9 | if(s[i] < s[i + 1]) break; 10 | } 11 | 12 | // if it doesn't exist, return -1 13 | if(i < 0) return -1; 14 | 15 | // find the number x' in the right side which is just greater than x 16 | for(int j = s.size() - 1; j > i; j--){ 17 | if(s[j] > s[i]){ 18 | swap(s[i], s[j]); 19 | break; 20 | } 21 | } 22 | 23 | // reverse right side to make it in increasing order 24 | reverse(s.begin() + i + 1, s.end()); 25 | long res = stol(s); 26 | return res > INT_MAX? -1 : res; // check if the result is longer than 32-bits 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /no_of_subarr_with_bounded_max.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSubarrayBoundedMax(vector& A, int L, int R) { 4 | if(A.size() == 0) return 0; 5 | int count = 0, prev = 0; 6 | int i = 0, j = 0; 7 | 8 | 9 | while(j < A.size()){ 10 | if(A[j] < L){ 11 | count += prev; 12 | //i++; 13 | } 14 | else if(L<=A[j] && A[j]<=R){ 15 | prev = j - i + 1; 16 | count += prev; 17 | //i++; 18 | } 19 | else{ 20 | prev = 0; 21 | i = j + 1; 22 | } 23 | j++; 24 | } 25 | return count; 26 | } 27 | }; -------------------------------------------------------------------------------- /non_overlapping_intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int eraseOverlapIntervals(vector>& intervals) { 4 | 5 | if(intervals.size() == 0) return 0; 6 | int count = 1; 7 | sort(intervals.begin(), intervals.end(), [](const vector &a, const vector &b){ 8 | return a[1] < b[1]; 9 | }); 10 | 11 | int end = intervals[0][1]; 12 | for(int i=1; i= end) { //next's start is greater than previous end time 14 | end = intervals[i][1]; 15 | count++; 16 | } 17 | } 18 | return intervals.size() - count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /nth_ugly.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthUglyNumber(self, n: int) -> int: 3 | 4 | inc2, inc3, inc5 = 0, 0, 0 5 | nxt2, nxt3, nxt5 = 2, 3, 5 6 | ugly = [0] * n 7 | ugly[0] = 1 8 | for i in range(1,n): 9 | nxt = min(nxt2, nxt3, nxt5) 10 | ugly[i] = nxt 11 | if ugly[i] == nxt2: 12 | inc2 += 1 13 | nxt2 = ugly[inc2] * 2 14 | if ugly[i] == nxt3: 15 | inc3 += 1 16 | nxt3 = ugly[inc3] * 3 17 | if ugly[i] == nxt5: 18 | inc5 += 1 19 | nxt5 = ugly[inc5] * 5 20 | return ugly[-1] 21 | 22 | -------------------------------------------------------------------------------- /number-of-dice-rolls-with-target-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRollsToTarget(self, n: int, k: int, target: int) -> int: 3 | dp = {} 4 | 5 | def dfs(idx, currSum): 6 | if idx == 0 and currSum == target: 7 | return 1 8 | if idx == 0 or currSum > target: 9 | return 0 10 | 11 | if (idx, currSum) in dp: 12 | return dp[(idx, currSum)] 13 | 14 | count = 0 15 | for i in range(1, k + 1): 16 | count += dfs(idx - 1, currSum + i) 17 | dp[(idx, currSum)] = count 18 | 19 | return count 20 | return dfs(n, 0) % (10**9 + 7) -------------------------------------------------------------------------------- /numberOfLIS.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNumberOfLIS(vector& nums) { 4 | int n = nums.size(); 5 | vector len(n, 1), cnt(n, 1); 6 | int lis = 1; 7 | for(int i = 1; i < n; i++){ 8 | for(int j = 0; j < i; j++){ 9 | if(nums[i] > nums[j]){ 10 | if(len[j] + 1 > len[i]){ 11 | len[i] = len[j] + 1; 12 | cnt[i] = cnt[j]; 13 | } 14 | else if(len[j] + 1 == len[i]){ 15 | cnt[i] += cnt[j]; 16 | } 17 | } 18 | lis = max(lis, len[i]); 19 | } 20 | } 21 | int ans = 0; 22 | for(int i = 0; i < n; i++){ 23 | if(len[i] == lis)ans += cnt[i]; 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /number_of_provices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void dfs(vector>& isConnected, int i, int n) { 3 | for(int j = 0; j < n; ++j) { 4 | if(isConnected[i][j]) { 5 | isConnected[i][j] = 0; 6 | isConnected[j][i] = 0; 7 | dfs(isConnected, j, n); 8 | } 9 | } 10 | } 11 | 12 | public: 13 | int findCircleNum(vector>& isConnected) { 14 | int n = isConnected.size(); 15 | int numProvince = 0; 16 | 17 | for(int i = 0; i < n; ++i) { 18 | if(isConnected[i][i]) { 19 | dfs(isConnected, i, n); 20 | numProvince++; 21 | } 22 | } 23 | return numProvince; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /occurrences_in_bigrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOcurrences(string text, string first, string second) { 4 | 5 | string F = "", S = ""; 6 | string word; 7 | vector ans; 8 | 9 | for(char c : text){ 10 | if(c == ' '){ 11 | if(F == first && S == second) ans.push_back(word); 12 | F = S; 13 | S = word; 14 | word.clear(); 15 | } 16 | else 17 | word.push_back(c); 18 | } 19 | if(F == first && S == second) ans.push_back(word); 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /oddValueCellsInMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int oddCells(int n, int m, vector>& indices) { 4 | 5 | vector rows(n, false); 6 | vector cols(m, false); 7 | 8 | //toggling the state of each cell in the vectors 9 | for(auto &index : indices){ 10 | rows[index[0]] = !rows[index[0]]; 11 | cols[index[1]] = !cols[index[1]]; 12 | } 13 | 14 | //if the ^ of rows[i] and cols[j] results in 1, just add it to odd count 15 | int odds = 0; 16 | for(auto i = 0; i < n; i++) 17 | for(auto j = 0; j < m; j++) 18 | if(rows[i] ^ cols[j]) odds++; 19 | return odds; 20 | } 21 | }; -------------------------------------------------------------------------------- /online_stock_span.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack> st; //{price, count/index} 4 | 5 | StockSpanner() { 6 | } 7 | 8 | int next(int price) { 9 | 10 | 11 | int count = 1; 12 | while(not st.empty() and st.top().first <= price) { 13 | count += st.top().second; 14 | st.pop(); 15 | } 16 | 17 | st.push({price, count}); 18 | return count; 19 | } 20 | }; 21 | 22 | /** 23 | * Your StockSpanner object will be instantiated and called as such: 24 | * StockSpanner* obj = new StockSpanner(); 25 | * int param_1 = obj->next(price); 26 | */ 27 | -------------------------------------------------------------------------------- /pair-of-songs-divisible-by-60.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numPairsDivisibleBy60(vector& time) { 4 | 5 | // (a + b)mod c = (a mod c + b mod c)mod c 6 | // (ti + tj) % 60 == 0 7 | // (ti % 60) + (tj % 60) % 60 = 0 or 60 8 | // (tj % 60) = (60 - ti % 60) % 60 9 | 10 | int hashmap[60] = {0}; 11 | int count = 0; 12 | 13 | for(auto &ti : time) { 14 | 15 | int tj = (60 - ti % 60) % 60; 16 | count += hashmap[tj]; 17 | ++hashmap[ti % 60]; 18 | } 19 | 20 | return count; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /palindrome_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | if x is None: 4 | return True 5 | reversin = list(str(x)) 6 | reversin.reverse() 7 | reversing = ''.join(reversin) 8 | if reversing == str(x): 9 | return True 10 | else: 11 | return False -------------------------------------------------------------------------------- /palindrome_partition_ii.cpp: -------------------------------------------------------------------------------- 1 | // BFS approach - n^2 2 | class Solution { 3 | public: 4 | int minCut(string s) { 5 | queue node; 6 | node.push(0); 7 | int cuts = 0; 8 | //bfs 9 | vector visited(s.size(), false); 10 | while (true){ 11 | queue tmp; 12 | while (!node.empty()){ 13 | int cur = node.front(); 14 | node.pop(); 15 | for (int i = s.size() - 1; i >= cur; i--){ 16 | if (visited[i]==false&&ispal(s, cur, i)){ 17 | if (i == s.size() - 1) 18 | return cuts; 19 | tmp.push(i+1); 20 | } 21 | } 22 | visited[cur] = true; 23 | } 24 | cuts++; 25 | node = tmp; 26 | } 27 | } 28 | 29 | bool ispal(string& s, int pre, int post){ 30 | while (pre < post){ 31 | if (s[pre++] != s[post--]) 32 | return false; 33 | } 34 | return true; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /partition_list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* partition(ListNode* head, int x) { 14 | ListNode *dummy1 = new ListNode(0), *dummy2 = new ListNode(0), *node1, *node2; 15 | node1 = dummy1; 16 | node2 = dummy2; 17 | while (head) { 18 | if (head->val < x) { 19 | node1->next = head; 20 | node1 = node1->next; 21 | } else { 22 | node2->next = head; 23 | node2 = node2->next; 24 | } 25 | head = head->next; 26 | } 27 | node2->next = NULL; 28 | node1->next = dummy2->next; 29 | return dummy1->next; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /pascal_triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | 5 | vector> pT(numRows); 6 | for(int i = 0; i < numRows; i++){ 7 | pT[i].resize(i + 1); 8 | pT[i][0] = 1; 9 | 10 | for(int j=1; j getRow(int rowIndex) { 4 | vector result(rowIndex+1, 1); 5 | for(int i = 1; i < rowIndex; i++){ 6 | for(int j = i; j > 0; j--) 7 | result[j] += result[j-1]; 8 | } 9 | return result; 10 | 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /patch_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPatches(vector& nums, int n) { 4 | if (n == 0) return 0; 5 | int num = nums.size(); 6 | long reach = 0; 7 | int patch = 0; 8 | for (int i = 0; i < num; ){ 9 | while (nums[i] > reach + 1){ 10 | reach += (reach + 1); 11 | ++patch; 12 | if (reach >= n) return patch; 13 | } 14 | reach += nums[i]; 15 | if (reach >= n) return patch; 16 | ++i; 17 | } 18 | while (reach < n){ 19 | reach += (reach + 1); 20 | ++patch; 21 | } 22 | return patch; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /plus_one.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | sum_, carry = 0, 0 4 | i = len(digits) - 1 5 | while i>=0: 6 | if i == len(digits) - 1: 7 | sum_ = carry + digits[-1] + 1 8 | else: 9 | sum_ = carry + digits[i] 10 | if sum_ > 9: 11 | carry = 1 12 | digits[i] = 0 13 | i -= 1 14 | continue 15 | else: 16 | digits[i] = sum_ 17 | break 18 | if digits[0] == 0 and carry == 1: 19 | new_digits = digits.insert(0, 1) 20 | #print(digits) 21 | return digits -------------------------------------------------------------------------------- /power_of_four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int num) { 4 | return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /prime_order_prioritization_amazonq2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | 10 | # 11 | # Complete the 'sortOrders' function below. 12 | # 13 | # The function is expected to return a STRING_ARRAY. 14 | # The function accepts STRING_ARRAY orderList as parameter. 15 | # 16 | import re, collections 17 | def sortOrders(orderList): 18 | # Write your code here 19 | 20 | primes, nonprimes = [], [] 21 | 22 | for order in orderList: 23 | metadata = order.split() 24 | if re.search('(^\d+$)', metadata[1]): 25 | nonprimes.append(order) 26 | else: 27 | primes.append(order) 28 | primes.sort(key = lambda k : k.split(' ', 1)[1]) 29 | return primes + nonprimes 30 | -------------------------------------------------------------------------------- /product_of_all_except_self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | 5 | vector L(nums.size()), R(nums.size()); 6 | 7 | L[0]=1; 8 | R[nums.size()-1]=1; 9 | 10 | for(int i=1; i=0;i--){ 15 | R[i] = R[i+1] * nums[i+1]; 16 | } 17 | 18 | vector pb; 19 | for(int i=0; i group; 7 | vector profit; 8 | int P; 9 | int G; 10 | int profitableSchemes(int G, int P, vector& group, vector& profit) { 11 | this->group = group; 12 | this->profit = profit; 13 | this->P = P; 14 | this->G = G; 15 | memset(dp,-1,sizeof(dp)); 16 | return rec(group.size()-1,0,0); 17 | } 18 | int rec(int pos,int point,int people) 19 | { 20 | if(pos == -1) return (point >= P) && (people <= G); 21 | if(people > G) return 0; 22 | point = min(point,P); 23 | int &ret = dp[pos][point][people]; 24 | if(ret != -1) return ret; 25 | 26 | ret = 0; 27 | 28 | ret += rec(pos-1,point + profit[pos],people + group[pos]); 29 | ret %= mod; 30 | 31 | ret += rec(pos-1,point,people); 32 | ret %= mod; 33 | 34 | -------------------------------------------------------------------------------- /range_sum_query.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | vector memo = {0}; 4 | NumArray(vector& nums) { 5 | int summ = 0; 6 | for (int n : nums) { 7 | summ += n; 8 | memo.push_back(summ); 9 | } 10 | } 11 | 12 | int sumRange(int left, int right) { 13 | return memo[right + 1] - memo[left]; 14 | } 15 | }; 16 | 17 | /** 18 | * Your NumArray object will be instantiated and called as such: 19 | * NumArray* obj = new NumArray(nums); 20 | * int param_1 = obj->sumRange(left,right); 21 | */ 22 | -------------------------------------------------------------------------------- /reduce_operations_to_make_equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reductionOperations(vector& nums) { 4 | int n = nums.size(); 5 | 6 | map mp; 7 | for(int i = 0; i < n; i ++) { 8 | mp[nums[i]] ++; // storing the frequency 9 | } 10 | 11 | int ans = 0; 12 | int pre = 0; 13 | for (auto i = mp.end(); i != mp.begin(); i--) { 14 | ans += i -> second + pre; // total operations 15 | pre += i -> second; // maintaing the previous frequency count 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | if(nums.size() < 2) return nums.size(); 5 | int remove = 1; 6 | for(int i=1; i 0) { //k-- 8 | 9 | //triggered when i > 0 10 | i = (i > 0) ? i - 1 : 0; //bring the i back to peak before the previously removed peak 11 | 12 | while(i ListNode: 9 | if not head: 10 | return None 11 | fast = slow = head 12 | for i in range(n): 13 | fast = fast.next 14 | if not fast: 15 | return head.next 16 | while fast.next: 17 | slow = slow.next 18 | fast = fast.next 19 | slow.next = slow.next.next 20 | return head -------------------------------------------------------------------------------- /reorder_data_in_log.py: -------------------------------------------------------------------------------- 1 | # best when solved with Python instead of C++. custom sorter in c++ is too complicated unnecessarily 2 | class Solution: 3 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 4 | def stable_sort(log): 5 | left, right = log.split(' ', 1) 6 | if right[0].isalpha(): 7 | return (0, right, left) 8 | else: 9 | return (1, None, None) 10 | return sorted(logs, key = stable_sort) 11 | 12 | -------------------------------------------------------------------------------- /reorder_data_in_log_files.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | class Solution: 3 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 4 | letterLogs, digitLogs, result = [], [], [] 5 | 6 | for log in logs: 7 | identifier, content = log.split(' ', 1) 8 | if content[0].isdigit(): 9 | digitLogs.append(log) 10 | else: 11 | heappush(letterLogs, (content, identifier)) # heapify by lexicographical order of content and then identifier 12 | 13 | while letterLogs: 14 | content, identifier = heapq.heappop(letterLogs) # lexicographically smallest element 15 | result.append(identifier + ' ' + content) 16 | 17 | return result + digitLogs 18 | -------------------------------------------------------------------------------- /repeated_dna_sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRepeatedDnaSequences(self, s: str) -> List[str]: 3 | count=dict() 4 | return_=[] 5 | for i in range(0,len(s)-9): 6 | sub=s[i:i+10] 7 | if sub in count: 8 | if count[sub]: 9 | return_.append(sub) 10 | count[sub]=False 11 | else: 12 | count[sub]=True 13 | return return_ -------------------------------------------------------------------------------- /reverse-only-letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void swap(char &x, char &y){ 5 | auto t = x; 6 | x = y; 7 | y = t; 8 | } 9 | 10 | string reverseOnlyLetters(string S) { 11 | 12 | if(S.size() == 0) return ""; 13 | 14 | int i = 0, j = S.size() - 1; 15 | 16 | 17 | while(i <= j){ 18 | 19 | if(isalpha(S[i]) and isalpha(S[j])) 20 | swap(S[i], S[j]); 21 | 22 | else if(!isalpha(S[i])){ 23 | i++; continue; 24 | } 25 | else if(!isalpha(S[j])){ 26 | j--; continue; 27 | } 28 | 29 | i++; j--; 30 | } 31 | return S; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /reverse_integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x == 0: 4 | return 0 5 | elif x < 0: 6 | s = -1 7 | else: 8 | s = 1 9 | x = list(str(x * s)) 10 | x.reverse() 11 | res = int("".join(x)) 12 | return res * s if res < 0x7fffffff else 0 -------------------------------------------------------------------------------- /reverse_level_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector> result; 13 | 14 | void BFS(TreeNode *root, int level){ 15 | if(root == NULL) return; 16 | 17 | if(level == result.size()) result.push_back(vector()); 18 | 19 | result[level].push_back(root->val); 20 | 21 | BFS(root->left, level + 1); 22 | BFS(root->right, level + 1); 23 | 24 | } 25 | vector> levelOrderBottom(TreeNode* root) { 26 | 27 | if(root == NULL) return vector>(); 28 | BFS(root, 0); 29 | return vector> (result.rbegin(), result.rend()); 30 | } 31 | }; -------------------------------------------------------------------------------- /reverse_words_in_string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | 5 | string result = ""; 6 | int i = 0, N = s.length(); 7 | 8 | while(i < N) { 9 | while(i < N && s[i] == ' ') i++; 10 | if(i >= N) break; 11 | 12 | int j = i + 1; 13 | 14 | while(j < N && s[j] != ' ') 15 | j++; 16 | 17 | string substr = s.substr(i, j-i); 18 | if(result.length() == 0) { 19 | result = substr; 20 | } 21 | else result = substr + " " + result; 22 | i = j + 1; 23 | } 24 | 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /reverse_words_in_string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | parts = s.strip().split(' ') 4 | print(parts) 5 | revst = [] 6 | pparts = [] 7 | for p in parts: 8 | if p != "": 9 | pparts.append(p) 10 | for i in range(len(pparts)): 11 | revst.append(pparts[i]) 12 | rev = revst[::-1] 13 | return ' '.join(rev) 14 | -------------------------------------------------------------------------------- /robot_return_to_origin.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeCircle(string moves) { 4 | int r = 0, c = 0; 5 | 6 | for(auto &move : moves) { 7 | if(move == 'U') r--; 8 | else if(move == 'D') r++; 9 | else if(move == 'L') c--; 10 | else c++; 11 | } 12 | return r == 0 and c == 0; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /roman_to_int.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | 5 | unordered_map mp = {{'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}}; 6 | 7 | int res = mp[s.back()]; 8 | for(int i = 0; i < s.size()-1; i++){ 9 | if(mp[s[i]] < mp[s[i + 1]]) 10 | res -= mp[s[i]]; 11 | else 12 | res += mp[s[i]]; 13 | } 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /root_to_leaf_sum_binary_numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def sumRootToLeaf(self, root: TreeNode) -> int: 10 | stack, res = [(root, str(root.val))], 0 11 | while stack: 12 | node, parent_val = stack.pop() 13 | if not node.left and not node.right: 14 | res += int(parent_val, 2) 15 | continue 16 | if node.left: stack.append((node.left, parent_val + str(node.left.val))) 17 | if node.right: stack.append((node.right, parent_val + str(node.right.val))) 18 | 19 | return res 20 | 21 | -------------------------------------------------------------------------------- /rotate_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n = nums.size(); 5 | k %= n; 6 | reverse(nums.begin(), nums.begin()+n-k); 7 | reverse(nums.begin()+n-k, nums.end()); 8 | reverse(begin(nums), end(nums)); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /rotate_function.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxRotateFunction(self, A: List[int]) -> int: 3 | if len(A) == 0: 4 | return 0 5 | totalSum = sum(A) 6 | lMax = 0 7 | for i in range(len(A)): 8 | lMax += i * A[i] 9 | gMax = lMax 10 | for i in range(len(A)-1, 0, -1): 11 | lMax += (totalSum - A[i] * len(A)) 12 | gMax = max(gMax, lMax) 13 | return gMax 14 | -------------------------------------------------------------------------------- /rotate_image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int N = matrix.size(); 5 | 6 | //1. transpose matrix 7 | for(int i=0; i>& envelopes) { 4 | 5 | int n = envelopes.size(); 6 | if(n == 0) return 0; 7 | 8 | 9 | sort(envelopes.begin(), envelopes.end()); 10 | vector dp(n+1, 1); 11 | 12 | int max = 1; 13 | 14 | for(int i=1; i envelopes[j][0] and envelopes[i][1] > envelopes[j][1] and 1 + dp[j] > dp[i]) { 18 | dp[i] = 1 + dp[j]; 19 | } 20 | 21 | if(dp[i] > max) max = dp[i]; 22 | } 23 | } 24 | return max; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /score_of_parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfParentheses(string S) { 4 | if(S.size() == 0) return 0; 5 | int score = 0; 6 | 7 | stack st; 8 | for(const auto c : S) { 9 | if(c == '(') { 10 | st.push(score); 11 | score = 0; 12 | } 13 | else { 14 | score = st.top() + max(2 * score, 1); 15 | st.pop(); 16 | } 17 | } 18 | return score; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /score_of_parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def scoreOfParentheses(self, S: str) -> int: 3 | ''' 4 | Maintain depth of each ( as 0. 5 | 6 | As soon as a ) is encountered check for the current_top in stack. 7 | If its 0 then simply pop and add 1 to the prev val in stack.. signifies... () 8 | If its not 0, then pop add the prev value + 2 * popped_element to the prev val in stack... signifies A + B and 2 * A operation 9 | ''' 10 | if len(S) == 0 or len(S) == 1: 11 | return 0 12 | st = [0] 13 | 14 | for c in S: 15 | if c == '(': 16 | st.append(0) 17 | else: 18 | item = st.pop() 19 | result = st.pop() 20 | if item == 0: 21 | result += 1 22 | else: 23 | result += 2 * item 24 | st.append(result) 25 | return st.pop(0) -------------------------------------------------------------------------------- /search_in_bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | 13 | TreeNode* helper(TreeNode* root, int val){ 14 | if(root == NULL) return root; 15 | 16 | if(root->val == val) return root; 17 | else if(root->val < val) return helper(root->right, val); 18 | else return helper(root->left,val); 19 | 20 | return NULL; 21 | } 22 | 23 | TreeNode* searchBST(TreeNode* root, int val) { 24 | 25 | if(root == NULL) return root; 26 | return helper(root, val); 27 | } 28 | }; -------------------------------------------------------------------------------- /search_in_rotated_sorted_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums, target): 3 | if not nums: 4 | return -1 5 | return self.binarySearch(nums, target, 0, len(nums)-1) 6 | 7 | def binarySearch(self, nums, target, start, end): 8 | if end < start: 9 | return -1 10 | mid = (start+end)//2 11 | if nums[mid] == target: 12 | return mid 13 | if nums[start] <= target < nums[mid]: # left side is sorted and has target 14 | return self.binarySearch(nums, target, start, mid-1) 15 | elif nums[mid] < target <= nums[end]: # right side is sorted and has target 16 | return self.binarySearch(nums, target, mid+1, end) 17 | elif nums[mid] > nums[end]: # right side is pivoted 18 | return self.binarySearch(nums, target, mid+1, end) 19 | else: # left side is pivoted 20 | return self.binarySearch(nums, target, start, mid-1) -------------------------------------------------------------------------------- /shifting_letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shiftingLetters(string S, vector& shifts,long long s=0) { 4 | // walk from the end of the string add the shifts and change the char at that pos 5 | for(int i=shifts.size()-1; i>=0; i--) { 6 | s += shifts[i]; // sum of shifts 7 | long long perShift = (S[i]-'a'+s) % 26; // at a particular pos , (sum of shifts + pos of char between 0..25) % 26 8 | S[i] = (char)(perShift+'a'); // change the char at every pos of the given string to the new shifted char 9 | } 10 | return S; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /shortest_distance_between_points.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distanceBetweenBusStops(vector& distance, int start, int destination) { 4 | 5 | if(distance.size() == 0) return 0; 6 | int res1 = 0, res2 = 0; 7 | 8 | for(int i=start; i!=destination;){ 9 | res1 += distance[i]; 10 | i = (i + 1) % distance.size(); 11 | } 12 | for(int i=destination; i!=start;){ 13 | res2 += distance[i]; 14 | i = (i + 1) % distance.size(); 15 | } 16 | return min(res1, res2); 17 | } 18 | }; -------------------------------------------------------------------------------- /sieve_of_eranthoses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | //Sieve of Erantothoses 5 | vector check(n+1,true); 6 | 7 | //Because 0 and 1 are not primes 8 | check[0]=false; 9 | check[1]=false; 10 | 11 | //OPtimization 2: Do only till rootn since all numbers after that are handled 12 | //The remaining values are already true 13 | for(int i=2;i*i<=n;i++) 14 | { 15 | //If already visited 16 | if(check[i]==false) continue; 17 | 18 | //Optimation 1 : 3*2 is already handled by 2*3. Then directly start from 9 19 | int j=i*i; 20 | while(j<=n) 21 | { 22 | check[j]=false; 23 | j = j+i; 24 | } 25 | 26 | } 27 | 28 | int count=0; 29 | //Checking all the numbers which are prime (less than n) 30 | for(int i=1;i 2 | using namespace std; 3 | 4 | 5 | int main() { 6 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 7 | int N; 8 | cin>>N; 9 | stackstk; 10 | string st; 11 | while(N--){ 12 | int n; cin>>n; 13 | if(n==1){ 14 | string str; 15 | cin>>str; 16 | stk.push(st); 17 | st+=str; 18 | } 19 | else if(n==2){ 20 | int k;cin>>k; 21 | stk.push(st); 22 | st.erase(st.size()-k); 23 | } 24 | else if(n==3){ 25 | int k;cin>>k; 26 | cout< str: 4 | s = deque() 5 | for node in path.split('/'): 6 | if node == '..': 7 | if s: 8 | s.pop() 9 | elif node and node != '.': 10 | s.append(node) 11 | return "/" + "/".join(s) 12 | -------------------------------------------------------------------------------- /single_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution: 2 | int singleNumber(vector &nums){ 3 | int x = 0; 4 | for(auto num : nums) x ^= num; 5 | return x; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /sliding_window_maximum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: 3 | d = collections.deque() 4 | out = [] 5 | for i, n in enumerate(nums): 6 | #print("i = {}, curr element = {}, d = {} and out = {}".format(i, n, d, out)) 7 | while d and nums[d[-1]] < n: 8 | d.pop() 9 | #print("\t Popped from d because d has elements and nums[d.top] < curr element") 10 | d.append(i) 11 | #print("\t Added i to d") 12 | if d[0] == i - k: 13 | d.popleft() 14 | #print("\t Popped left from d because it's outside the window's leftmost (i-k)") 15 | if i>=k-1: 16 | out.append(nums[d[0]]) 17 | #print("\t Append nums[d[0]] = {} to out".format(nums[d[0]])) 18 | return out -------------------------------------------------------------------------------- /smallest_positive_missing_integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | //Position this line where user code will be pasted. 4 | int missingNumber(int arr[], int n); 5 | int main() { 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | int n; 10 | cin>>n; 11 | int arr[n]; 12 | for(int i=0; i>arr[i]; 13 | cout<mp; 21 | for(int i=0;i0) 23 | mp[arr[i]]++; 24 | 25 | map:: iterator it; 26 | int max_ele = *max_element(arr,arr+n); 27 | int i=1; 28 | while(i<=max_ele) 29 | { 30 | if(mp.find(i)==mp.end()) 31 | return i; 32 | i++; 33 | } 34 | return i; 35 | } -------------------------------------------------------------------------------- /snapshot_array.cpp: -------------------------------------------------------------------------------- 1 | class SnapshotArray { 2 | public: 3 | unordered_map> database; 4 | unordered_map cur_data; 5 | int snap_id; 6 | SnapshotArray(int length) { 7 | snap_id = -1; 8 | } 9 | 10 | void set(int index, int val) { 11 | cur_data[index] = val; 12 | } 13 | 14 | int snap() { 15 | snap_id++; 16 | database[snap_id] = cur_data; 17 | return snap_id; 18 | } 19 | 20 | int get(int index, int snap_id) { 21 | return database[snap_id][index]; 22 | } 23 | }; 24 | /** 25 | * Your SnapshotArray object will be instantiated and called as such: 26 | * SnapshotArray* obj = new SnapshotArray(length); 27 | * obj->set(index,val); 28 | * int param_2 = obj->snap(); 29 | * int param_3 = obj->get(index,snap_id); 30 | */ 31 | -------------------------------------------------------------------------------- /snapshot_array.py: -------------------------------------------------------------------------------- 1 | class SnapshotArray: 2 | 3 | def __init__(self, length: int): 4 | self.snapshot = {i: {0: 0} for i in range(length)} 5 | self.snap_id = 0 6 | 7 | def set(self, index: int, val: int) -> None: 8 | self.snapshot[index][self.snap_id] = val 9 | 10 | def snap(self) -> int: 11 | self.snap_id += 1 12 | return self.snap_id - 1 13 | 14 | def get(self, index: int, snap_id: int) -> int: 15 | while snap_id > 0 and snap_id not in self.snapshot[index]: 16 | snap_id -= 1 17 | return self.snapshot[index][snap_id] 18 | -------------------------------------------------------------------------------- /sort_by_bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortByBits(vector& arr) { 4 | 5 | 6 | sort(arr.begin(), arr.end(), [](const int& A, const int &B){ 7 | 8 | int countA = __builtin_popcount(A), countB = __builtin_popcount(B); 9 | return countA == countB ? A < B : countA < countB; 10 | }); 11 | 12 | return arr; 13 | } 14 | }; -------------------------------------------------------------------------------- /split_arary_into_3_arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def waysToSplit(self, nums: List[int]) -> int: 3 | # Calculate prefix & define variables 4 | N = len(nums) 5 | prefix = [0] * (N + 1) 6 | mod = 10 ** 9 + 7 7 | for i in range(1, N + 1): 8 | prefix[i] = prefix[i-1] + nums[i-1] 9 | 10 | l, r, cnt = 0, 0, 0 11 | for i in range(1, N + 1): 12 | l = max(l, i + 1) 13 | 14 | # find the first l such that mid >= left 15 | while(l < N and prefix[i] > prefix[l] - prefix[i]): 16 | l += 1 17 | 18 | r = max(r, l) 19 | 20 | # find the last r such that right >= mid 21 | # so that for any r in this range [l, r] 22 | # left <= mid <= right is True 23 | while(r < N and prefix[r] - prefix[i] <= prefix[-1] - prefix[r]): 24 | r += 1 25 | 26 | cnt = (cnt + r - l) % mod 27 | return cnt 28 | -------------------------------------------------------------------------------- /sqrt.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | if(x == 0) return 0; 5 | if(x == 1) return 1; 6 | 7 | int left = 1, right = x; 8 | long mid; 9 | 10 | while(left < right) { 11 | 12 | //find mid 13 | mid = left + (right - left) / 2; 14 | 15 | //condition 16 | if(mid * mid > x) right = mid; 17 | 18 | //else 19 | else left = mid + 1; 20 | } 21 | return left - 1; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /squares_of_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& A) { 4 | int dimension = A.size(); 5 | if(dimension == 0) return {}; 6 | 7 | 8 | int ind = dimension - 1; 9 | int left = 0, right = dimension - 1; 10 | vector tmp(dimension); 11 | 12 | while(left <= right){ 13 | int c1 = A[left] * A[left]; 14 | int c2 = A[right] *A[right]; 15 | 16 | if(c1 < c2){ 17 | tmp[ind] = c2; 18 | right--; 19 | ind--; 20 | } 21 | else{ 22 | tmp[ind] = c1; 23 | left++; 24 | ind--; 25 | } 26 | } 27 | 28 | return tmp; 29 | } 30 | }; -------------------------------------------------------------------------------- /string_compression.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compress(vector& chars) { 4 | 5 | int index = 0; 6 | int i = 0; 7 | 8 | while(i < chars.size()) { 9 | int j = i; 10 | 11 | while(j < chars.size() and chars[i] == chars[j]) { 12 | j++; 13 | } 14 | 15 | chars[index++] = chars[i]; //first char of repeated sequence ... 16 | if(j - i > 1) { 17 | string count = to_string(j - i); 18 | for(char c : count) 19 | chars[index++] = c; 20 | } 21 | i = j; 22 | } 23 | 24 | return index; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /subarray_sum_equals_k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | if(nums.size() == 0) return 0; 5 | 6 | int running_sum = 0, result = 0; 7 | unordered_map ump; 8 | 9 | for(int i=0; i if difference between k and current_sum is in map or not. 13 | 14 | if(ump[s]) { //if s in map 15 | result += ump[s]; 16 | } 17 | 18 | if(running_sum == k) result++; 19 | 20 | ump[running_sum]++; //if s not in map 21 | } 22 | 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private: 4 | 5 | 6 | void backtrack(vector> &global_result, vector &local_result, vector& nums, int start) { 7 | global_result.push_back(local_result); 8 | for(int i=start; i> subsets(vector& nums) { 17 | if(nums.size() == 0) return vector>(); 18 | vector> global_result; 19 | vector local_result; 20 | 21 | backtrack(global_result, local_result, nums, 0); 22 | return global_result; 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /subsets_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private: 4 | void backtrack(vector> &global_result, vector &local_result, vector& nums, int start) { 5 | global_result.push_back(local_result); 6 | for(int i=start; i start and nums[i] == nums[i-1]) continue; 8 | local_result.push_back(nums[i]); 9 | backtrack(global_result, local_result, nums, i+1); 10 | local_result.pop_back(); 11 | } 12 | } 13 | 14 | public: 15 | vector> subsetsWithDup(vector& nums) { 16 | vector> gr; 17 | vector lr; 18 | sort(nums.begin(), nums.end()); 19 | backtrack(gr, lr, nums, 0); 20 | return gr; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /sum_of_left_leaves.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def sumOfLeftLeaves(self, root: TreeNode, isLeft = False) -> int: 10 | if not root : return 0 11 | if not root.left and not root.right: 12 | return root.val * isLeft 13 | return self.sumOfLeftLeaves(root.left, True) + self.sumOfLeftLeaves(root.right)s -------------------------------------------------------------------------------- /sum_of_mutated_array_closest_to_target.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findBestValue(vector& arr, int target) { 4 | 5 | /* 6 | The only catch in the problem is we cannot change elements that are previously visited. Only current and all elements from current to end can be mutated. 7 | */ 8 | 9 | int n = arr.size(); 10 | sort(arr.begin(), arr.end()); 11 | 12 | int trailingSum = 0, sumNeeded; 13 | for(int i=0; i int: 4 | if not root: 5 | return 0 6 | 7 | sum_ = 0 8 | queue = [(root, None, None)] 9 | 10 | while(queue): 11 | root, parent, grandparent = queue.pop() 12 | if grandparent and root and grandparent.val % 2 == 0: 13 | sum_ += root.val; 14 | 15 | if root.left: 16 | queue.append((root.left, root, parent)) 17 | 18 | 19 | if root.right: 20 | queue.append((root.right, root, parent)) 21 | 22 | return sum_ -------------------------------------------------------------------------------- /sum_root_to_leaf_numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def __init__(self): 10 | self._sum = 0 11 | 12 | def util(self, root, c): 13 | if root == None: 14 | return 15 | 16 | c = c*10 + root.val #sum 17 | 18 | if root.left == None and root.right == None: #cummulative sum 19 | self._sum += c 20 | 21 | self.util(root.left, c) 22 | self.util(root.right, c) 23 | c /= 10 #used for backtracking from left to right node 24 | 25 | 26 | def sumNumbers(self, root: TreeNode) -> int: 27 | self.util(root, 0) 28 | return self._sum -------------------------------------------------------------------------------- /super_washing_machines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int max(int a, int b) { 4 | return a >= b ? a : b; 5 | } 6 | 7 | int findMinMoves(vector& machines) { 8 | if(machines.size() == 0) return 0; 9 | auto total_dresses = accumulate(machines.begin(), machines.end(), 0); 10 | cout< bool: 3 | if len(start) != len(end): return False 4 | i, j, l = 0, 0, len(start) 5 | while True: 6 | while i < l and start[i] == 'X': i += 1 7 | while j < l and end[j] == 'X': j += 1 8 | if i == l or j == l: 9 | if i == j: return True 10 | return False 11 | if start[i] != end[j]: return False 12 | if start[i] == 'L': 13 | if i < j: return False 14 | #start[i] == 'R' 15 | else: 16 | if i > j: return False 17 | i, j = i+1, j+1 18 | 19 | -------------------------------------------------------------------------------- /swap_nodes_in_pairs.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | 9 | def swapPairs(self, head: ListNode) -> ListNode: 10 | temp = head 11 | while temp != None and temp.next != None: 12 | temp.val, temp.next.val = temp.next.val, temp.val 13 | temp = temp.next.next 14 | return head -------------------------------------------------------------------------------- /swapping_nodes_in_linked_list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapNodes(ListNode* head, int k) { 14 | if(k == 0) return head; 15 | 16 | ListNode *slow, *kthBegin, *fast = head; 17 | 18 | for(int i = 0; i < k; i++) { 19 | kthBegin = fast; 20 | fast = fast->next; 21 | } 22 | 23 | slow = head; 24 | while(fast) { 25 | slow = slow->next; 26 | fast = fast->next; 27 | } 28 | cout<val<<" "<val<<" "; 29 | swap(slow->val, kthBegin->val); 30 | 31 | return head; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /tallest_billboard.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tallestBillboard(vector& rods) { 4 | int sum = accumulate(rods.begin(),rods.end(),0); 5 | vector dp(sum*2+1,-1); 6 | dp[sum] = 0; 7 | for(int& r:rods) { 8 | vector prev = dp; 9 | for(int i=0;i<=2*sum;i++) { 10 | if(prev[i]==-1)continue; 11 | dp[i+r]=max(dp[i+r],prev[i]+r); 12 | dp[i-r]=max(dp[i-r],prev[i]); 13 | } 14 | } 15 | return dp[sum]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /toeplitz_matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isToeplitzMatrix(vector>& matrix) { 4 | int m = matrix.size(), n = matrix[0].size(); 5 | for (int i = 1; i < m; i++) 6 | for (int j = 1; j < n; j++) 7 | if (matrix[i][j] != matrix[i - 1][j - 1]) 8 | return false; 9 | return true; 10 | } 11 | 12 | }; -------------------------------------------------------------------------------- /top_k_frequent_elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | c = {} 4 | for num in nums: # O(n) 5 | if num in c: 6 | c[num] += 1 7 | else: 8 | c[num] = 1 9 | print(c) 10 | 11 | f = {} 12 | for num, freq in c.items(): # O(n) 13 | if freq not in f: 14 | f[freq] = [num] 15 | else: 16 | f[freq].append(num) 17 | res = [] 18 | 19 | for i in range(len(nums), -1, -1): # O(n) 20 | if i in f: 21 | res += f[i] 22 | if len(res) >= k: 23 | break 24 | return res[:k] -------------------------------------------------------------------------------- /transition_point.cpp: -------------------------------------------------------------------------------- 1 | /*This is a function problem.You only need to complete the function given below*/ 2 | 3 | int helper(int arr[], int strt, int end){ 4 | while(strt <= end){ 5 | int mid = strt + (end - strt)/2; 6 | if(arr[mid] == 1 && arr[mid - 1] == 0) 7 | return mid; 8 | else if(arr[mid] == 1) 9 | end = mid - 1; 10 | else 11 | strt = mid + 1; 12 | } 13 | return -1; 14 | } 15 | 16 | int transitionPoint(int arr[],int n) 17 | { 18 | // Your code goes here 19 | int strt = 0, end = n -1; 20 | return helper(arr, strt, end); 21 | } -------------------------------------------------------------------------------- /two_sum_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& numbers, int target) { 4 | unordered_map mp; 5 | vector solution(2, 0); 6 | 7 | //store difference as first element of map and index as second element of map 8 | for(int i=0; i(2, 0); 25 | } 26 | }; -------------------------------------------------------------------------------- /ugly_numbers_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | vector ugly(n); 5 | ugly[0] = 1; //ugly of first number is 1 6 | 7 | int i2 = 0, i3 = 0, i5 = 0; 8 | int nm2 = 2, nm3 = 3, nm5 = 5; 9 | int next_ugly_number = 1; 10 | 11 | for(int i=1; i>& obstacleGrid) { 4 | 5 | int m = obstacleGrid.size(), n = obstacleGrid[0].size(), i , j; 6 | 7 | vector> dp (m, vector (n, 0)); 8 | 9 | for (i = 0; i < n;) { 10 | if(obstacleGrid[0][i] == 0) 11 | dp[0][i++] = 1; 12 | else 13 | break; 14 | } 15 | 16 | for (j = 0; j < m;){ 17 | if(obstacleGrid[j][0] == 0) 18 | dp[j++][0] = 1; 19 | else 20 | break; 21 | } 22 | 23 | for (i = 1; i < m; ++i) { 24 | for (j = 1; j < n; ++j) { 25 | if (obstacleGrid[i][j] == 0) 26 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 27 | } 28 | } 29 | 30 | return dp[m-1][n-1]; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /uniqueTwitterUserIdSet.cpp: -------------------------------------------------------------------------------- 1 | int minSum(vector arr) { 2 | sort(arr.begin(), arr.end()); 3 | int sum = 0, low = 0; 4 | for (int a : arr) { 5 | sum += (low = max(low + 1, a)); 6 | } 7 | return sum; 8 | } 9 | -------------------------------------------------------------------------------- /unique_paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | 5 | 6 | int dp[m+1][n+1]; 7 | 8 | 9 | for(int i=0; i bool: 3 | p1, p2, p3 = points[0],points[1],points[2] 4 | 5 | area = p1[0]*(p2[1]-p3[1]) + p2[0]*(p3[1]-p1[1]) + p3[0]*(p1[1]-p2[1]) 6 | if abs(area) > 0: 7 | return True 8 | if abs(area) == 0: 9 | return False -------------------------------------------------------------------------------- /valid_mountain_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validMountainArray(vector& A) { 4 | if(A.size() < 3) return false; 5 | if(A.size() == 0) return false; 6 | if(A[0] > A[1]) return false; 7 | 8 | int peak = A[0], index = -1; 9 | 10 | for(int i=0; i= A[i]) 21 | return false; 22 | 23 | return true; 24 | } 25 | }; -------------------------------------------------------------------------------- /verify_alien_dict.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAlienSorted(vector& words, string order) { 4 | for(int i=0 ;i i2) return false; 15 | } 16 | return true; 17 | } 18 | }; -------------------------------------------------------------------------------- /water_and_jug.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMeasureWater(int x, int y, int z) { 4 | if (x+y == z) 5 | return true; 6 | if (x+y < z) 7 | return false; 8 | if (x > y) { 9 | int temp = x; 10 | x = y; 11 | y = temp; 12 | } 13 | int volume = 0; 14 | while (1) { 15 | if (volume < x) 16 | volume += y; 17 | else 18 | volume -= x; 19 | if (volume == z) 20 | return true; 21 | if (volume == 0) 22 | return false; 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /wiggle_subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleMaxLength(self, nums: List[int]) -> int: 3 | if (len(nums) < 2): 4 | return len(nums) 5 | # create array of diffs 6 | diffs = [] 7 | for i in range(1, len(nums)): 8 | x = nums[i] - nums[i - 1] 9 | # ignore diffs of 0 as they don't count as turning points 10 | if (x != 0): 11 | diffs.append(x) 12 | # if there were diffs of only 0, then seq length is 1 13 | if (not diffs): 14 | return 1 15 | 16 | cnt = 1 # min seq length at this stage 17 | # now count the number of times the sign of diff between consecutive numbers changes 18 | # that will be equal to the max wiggle subseq length 19 | for i in range(1, len(diffs)): 20 | prod = diffs[i] * diffs[i - 1] 21 | if (prod < 0): 22 | cnt += 1 23 | 24 | return cnt + 1 -------------------------------------------------------------------------------- /word_break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, vector& wordDict) { 4 | int n = s.size(); 5 | set dict; 6 | for(auto &word : wordDict) dict.insert(word); 7 | vector dp(n+1, false); 8 | dp[0] = true; 9 | 10 | for(int i=0; i=0; j--) { 12 | string current = s.substr(j, i-j+1); //from j pick (i-j+1) characters backwards.. 13 | /* 14 | 00 - l 15 | 16 | 11 - e 17 | 10 - le 18 | 19 | 22 - e 20 | 21 - ee 21 | 20 - lee 22 | ... and so on. 23 | */ 24 | 25 | if(dict.find(current) != dict.end()) 26 | dp[i+1] = dp[j]; 27 | 28 | if(dp[i+1]) break; 29 | } 30 | } 31 | return dp[n]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /word_break_ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map> dp; 4 | vector wordBreak(string s, vector& wordDict) { 5 | if(dp.find(s) != dp.end()) return dp[s]; 6 | vector result; 7 | 8 | for(auto w : wordDict) { //for each word in wordDict 9 | 10 | if(s.substr(0, w.length()) == w) { // find the first word in s that is in the word dict 11 | if(s.length() == w.length()) { 12 | result.push_back(w); 13 | } 14 | 15 | else { 16 | vector suffix = wordBreak(s.substr(w.length()), wordDict); 17 | for(string s : suffix) { 18 | result.push_back(w + " " + s); 19 | } 20 | } 21 | } 22 | 23 | } 24 | dp[s] = result; 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /word_pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordPattern(self, pattern: str, str: str) -> bool: 3 | words = str.split() 4 | p = list(pattern) 5 | x1 = [] 6 | x2 = [] 7 | y1 = [] 8 | y2 = [] 9 | 10 | for i in p: 11 | if i not in x1: 12 | x1.append(i) 13 | x2.append(x1.index(i)) 14 | 15 | for j in words: 16 | if j not in y1: 17 | y1.append(j) 18 | y2.append(y1.index(j)) 19 | 20 | print(x2) 21 | print(y2) 22 | return x2 == y2 -------------------------------------------------------------------------------- /zigzag_conversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convert(self, s: str, numRows: int) -> str: 3 | if numRows == 1: 4 | return s 5 | strings = [""] * numRows 6 | nR = numRows 7 | steps, row = 0, 0 8 | for c in s: 9 | strings[row] += c 10 | if row == 0: steps = 1 11 | if row == nR - 1: steps = -1 12 | row += steps 13 | s = str() 14 | 15 | for li in strings: 16 | s += str(li) 17 | return s --------------------------------------------------------------------------------