├── .gitignore ├── .vscode ├── c_cpp_properties.json ├── launch.json └── settings.json ├── 001-1st_jan-Assign_Cookies ├── approach-explanation.txt └── code.cpp ├── 002-2nd_jan-Convert_array_to_2D ├── approach-explanation.txt └── code.cpp ├── 003-3rd_jan-Laser_beams_in_bank ├── approach-explanation.txt └── code.cpp ├── 004-4th_jan-Make_array_empty ├── approach-explanation.txt └── code.cpp ├── 005-5th_jan-Longest_increasing_sequence ├── approach-explanation.txt └── code.cpp ├── 006-6th_jan-Maximum_profit ├── approach-explanation.txt └── code.cpp ├── 007-7th_jan-Arithmetic_slices_II ├── approach-explanation.txt └── code.cpp ├── 008-8th_jan-Range_sum_BST ├── approach-explanation.txt └── code.cpp ├── 009-9th_jan-Leaf_similar_trees ├── approach-explanation.txt └── code.cpp ├── 010-10th_jan-Binary_tree_infected_time ├── approach-explanation.txt └── code.cpp ├── 011-11th_jan-Difference_node_ancestor ├── approach-explanation.txt └── code.cpp ├── 012-12th_jan-Half_strings_alike ├── approach-explanation.txt └── code.cpp ├── 013-13th_jan-Make_strings_anagram ├── approach-explanation.txt └── code.cpp ├── 014-14th_jan-Two_strings_are_close ├── approach-explanation.txt └── code.cpp ├── 015-15th_jan-Zero_or_one_loss ├── approach-explanation.txt └── code.cpp ├── 016-16th_jan-Insert_delete_random ├── approach-explanation.txt └── code.cpp ├── 017-17th_jan-unique_num_occurence ├── approach-explanation.txt └── code.cpp ├── 018-18th_jan-Climbing_stairs ├── approach-explanation.txt └── code.cpp ├── 019-19th_jan-Minimum_falling_path_sum ├── approach-explanation.txt └── code.cpp ├── 020-20th_jan-Sum_of_subarray_min ├── approach-explanation.txt └── code.cpp ├── 021-21st_jan-House_robber ├── approach-explanation.txt └── code.cpp ├── 022-22nd_jan-Set_mismatch ├── approach-explanation.txt └── code.cpp ├── 023-23rd_jan-Max_length_concatenated_string ├── approach-explanation.txt └── code.cpp ├── 024-24th_jan-Pseudo_palindromic_paths ├── approach-explanation.txt └── code.cpp ├── 025-25th_jan-Longest_common_subsequence ├── approach-explanation.txt └── code.cpp ├── 026-26th_jan-Out_of_boundary ├── approach-explanation.txt └── code.cpp ├── 027-27th_jan-K_inverse_pairs_array ├── approach-explanation.txt └── code.cpp ├── 028-28th_jan-Submatrices_sum_target ├── approach-explanation.txt └── code.cpp ├── 029-29th_jan-Implement_queue_using_stack ├── approach-explanation.txt └── code.cpp ├── 030-30th_jan-Reverse_polish_notation ├── approach-explanation.txt └── code.cpp ├── 031-31st_jan-Daily_temperatures ├── approach-explanation.txt └── code.cpp ├── 032-1st_feb-Divide_arrays_into_groups ├── approach-explanation.txt └── code.cpp ├── 033-2nd_feb-Sequential_digits ├── approach-explanation.txt └── code.cpp ├── 034-3rd_feb-Partition_array_max_sum ├── approach-explanation.txt └── code.cpp ├── 035-4th_feb-Minimum_window_substring ├── approach-explanation.txt └── code.cpp ├── 036-5th_feb-Unique_char_in_string ├── approach-explanation.txt └── code.cpp ├── 037-6th_feb-Group_anagrams ├── approach-explanation.txt └── code.cpp ├── 038-7th_feb-Sort_char_by_frequency ├── approach-explanation.txt └── code.cpp ├── 039-8th_feb-Perfect_squares ├── approach-explanation.txt └── code.cpp ├── 040-9th_feb-Largest_divisible_subset ├── approach-explanation.txt └── code.cpp ├── 041-10th_feb-Palindromic_substrings ├── approach-explanation.txt └── code.cpp ├── 042-11th_feb-Cherry_pickup_II ├── approach-explanation.txt └── code.cpp ├── 043-12th_feb-Majority_element ├── approach-explanation.txt └── code.cpp ├── 044-13th_feb-Palindrome_string_in_array ├── approach-explanation.txt └── code.cpp ├── 045-14th_feb-Rearrange_array_by_sign ├── approach-explanation.txt └── code.cpp ├── 046-15th_feb-Polygon_with_largest_perimeter ├── approach-explanation.txt └── code.cpp ├── 047-16th_feb-Least_num_of_unique_int ├── approach-explanation.txt └── code.cpp ├── 048-17th_feb-Furthest_building_you_can_reach ├── approach-explanation.txt └── code.cpp ├── 049-18th_feb-Meeting_rooms_III ├── approach-explanation.txt └── code.cpp ├── 050-19th_feb-Power_of_two ├── approach-explanation.txt └── code.cpp ├── 051-20th_feb-Missing_number ├── approach-explanation.txt └── code.cpp ├── 052-21st_feb-Bitwise_AND_number_range ├── approach-explanation.txt └── code.cpp ├── 053-22nd_feb-Town_judge ├── approach-explanation.txt └── code.cpp ├── 054-23rd_feb-K_stop_cheapest_flight ├── approach-explanation.txt └── code.cpp ├── 055-24th_feb-Find_people_with_secret ├── approach-explanation.txt └── code.cpp ├── 056-25th_feb-GCD_traversal ├── approach-explanation.txt └── code.cpp ├── 057-26th_feb-Same_tree ├── approach-explanation.txt └── code.cpp ├── 058-27th_feb-Diameter_binary_tree ├── approach-explanation.txt └── code.cpp ├── 059-28th_feb-Find_bottom_left_tree_val ├── approach-explanation.txt └── code.cpp ├── 060-29th_feb-Even_odd_tree ├── approach-explanation.txt └── code.cpp ├── 061-1st_march-Max_binary_odd_number ├── approach-explanation.txt └── code.cpp ├── 062-2nd_march-Squares_of_sorted_array ├── approach-explanation.txt └── code.cpp ├── 063-3rd_march-Remove_Nth_node_from_last ├── approach-explanation.txt └── code.cpp ├── 064-4th_march-Bag_of_tokens ├── approach-explanation.txt └── code.cpp ├── 065-5th_march-Min_length_of_string_after_erase ├── approach-explanation.txt └── code.cpp ├── 066-6th_march-Loop_in_linkedlist ├── approach-explanation.txt └── code.cpp ├── 067-7th_march-Middle_of_linkedlist ├── approach-explanation.txt └── code.cpp ├── 068-8th_march-Count_max_freq_elements ├── approach-explanation.txt └── code.cpp ├── 069-9th_march-Minimum_common_value ├── approach-explanation.txt └── code.cpp ├── 070-10th_march-Intersection_of_two_arrays ├── approach-explanation.txt └── code.cpp ├── 071-11th_march-Custom_sort_string ├── approach-explanation.txt └── code.cpp ├── 072-12th_march-Remove_zero_sum_nodes ├── approach-explanation.txt └── code.cpp ├── 073-13th_march-Find_pivot ├── approach-explanation.txt └── code.cpp ├── 074-14th_march-Binary_subarrays_with_sum ├── approach-explanation.txt └── code.cpp ├── 075-15th_march-Prioduct_of_array ├── approach-explanation.txt └── code.cpp ├── 076-16th_march-Contiguous_subarray ├── approach-explanation.txt └── code.cpp ├── 077-17th_march-Insert_interval ├── approach-explanation.txt └── code.cpp ├── 078-18th_march-Min_no_of_arrows ├── approach-explanation.txt └── code.cpp ├── 079-19th_march-Task_scheduler ├── approach-explanation.txt └── code.cpp ├── 080-20th_march-Merge_in-between_LL ├── approach-explanation.txt └── code.cpp ├── 081-21st_march-Reverse_linked-list ├── approach-explanation.txt └── code.cpp ├── 082-22nd_march-Palindrome_linked-list ├── approach-explanation.txt └── code.cpp ├── 083-23rd_march-Reorder_list ├── approach-explanation.txt └── code.cpp ├── 084-24th_march-Find_duplicate ├── approach-explanation.txt └── code.cpp ├── 085-25th_march-Find_all_duplicates ├── approach-explanation.txt └── code.cpp ├── 086-26th_march-First_missing_positive ├── approach-explanation.txt └── code.cpp ├── 087-27th_march-Subarray_product_less_than_K ├── approach-explanation.txt └── code.cpp ├── 088-28th_march-Longest_subarray_with_freq_K ├── approach-explanation.txt └── code.cpp ├── 089-29th_march-Count_subarrays_largest_appear_K_times ├── approach-explanation.txt └── code.cpp ├── 090-30th_march-Subarrays_with_K_different_ints ├── approach-explanation.txt └── code.cpp ├── 091-31st_march-Count_subarrays_fixed_bounds ├── approach-explanation.txt └── code.cpp ├── 092-1st_april-Length_of_last_word ├── approach-explanation.txt └── code.cpp ├── 093-2nd_april-Isomorphic_strings ├── approach-explanation.txt └── code.cpp ├── 094-3rd_april-Word_search ├── approach-explanation.txt └── code.cpp ├── 095-4th_april-Depth_of_parentheses ├── approach-explanation.txt └── code.cpp ├── 096-5th_april-Make_string_great ├── approach-explanation.txt └── code.cpp ├── 097-6th_april-Min_remove_to_make_valid_parenthesis ├── approach-explanation.txt └── code.cpp ├── 098-7th_april-Valid_parenthesis_string ├── approach-explanation.txt └── code.cpp ├── 099-8th_april-Students_eating_lunch ├── approach-explanation.txt └── code.cpp ├── 100-9th_april-Time_needed_to_buy_tickets ├── approach-explanation.txt └── code.cpp ├── 101-10th_april-Reveal_cards_in_increasing_order ├── approach-explanation.txt └── code.cpp ├── 102-11th_april-Renove_K_digits ├── approach-explanation.txt └── code.cpp ├── 103-12th_april-Trapping_rain_water ├── approach-explanation.txt └── code.cpp ├── 104-13th_april-Maximal_rectangle ├── approach-explanation.txt └── code.cpp ├── 105-14th_april-Sum_of_left_leaves ├── approach-explanation.txt └── code.cpp ├── 106-15th_april-Sum_root_to_leaf_numbers ├── approach-explanation.txt └── code.cpp ├── 107-16th_april-Add_one_row_to_tree ├── approach-explanation.txt └── code.cpp ├── 108-17th_april-Smallest_string_starting_from_leaf ├── approach-explanation.txt └── code.cpp ├── 109-18th_april-Island_perimeter ├── approach-explanation.txt └── code.cpp ├── 110-19th_april-Number_of_islands ├── approach-explanation.txt └── code.cpp ├── 111-20th_april-Find_all_groups_of_farmland ├── approach-explanation.txt └── code.cpp ├── 112-21st_april-Find_if_path_exists_in_graph ├── approach-explanation.txt └── code.cpp ├── 113-22nd_april-Open_the_lock ├── approach-explanation.txt └── code.cpp ├── 114-23rd_april-Min_height_trees ├── approach-explanation.txt └── code.cpp ├── 115-24th_april-Nth_fibonacci_number ├── approach-explanation.txt └── code.cpp ├── 116-25th_april-Longest_ideal_subsequence ├── approach-explanation.txt └── code.cpp ├── 117-26th_april-Min_falling_path_sum-II ├── approach-explanation.txt └── code.cpp ├── 118-27th_april-Freedom_trail ├── approach-explanation.txt └── code.cpp ├── 119-28th_april-Sum_of_distances_in_tree ├── approach-explanation.txt └── code.cpp ├── 120-29th_april-Min_number_of_operations ├── approach-explanation.txt └── code.cpp ├── 121-30th_april-Num_of_wonderful_substrings ├── approach-explanation.txt └── code.cpp ├── 122-1st_may-Reverse_prefix_of_word ├── approach-explanation.txt └── code.cpp ├── 123-2nd_may-Largest_positive_int_that_exists_with_-ve ├── approach-explanation.txt └── code.cpp ├── 124-3rd_may-Compare_version_numbers ├── approach-explanation.txt └── code.cpp ├── 125-4th_may-Boats_to_save_people ├── approach-explanation.txt └── code.cpp ├── 126-5th_may-Delete_linkedlist_node ├── approach-explanation.txt └── code.cpp ├── 127-6th_may-Remove_nodes_from_list ├── approach-explanation.txt └── code.cpp ├── 128-7th_may-Double_a_num_as_linkedlist ├── approach-explanation.txt └── code.cpp ├── 129-8th_may-Relative_ranks ├── approach-explanation.txt └── code.cpp ├── 130-9th_may-Max_happiness_of_selected_children ├── approach-explanation.txt └── code.cpp ├── 131-10th_may-Kth_smallest_prime_fraction ├── approach-explanation.txt └── code.cpp ├── 132-11th_may-Cost_to_hire_K_workers ├── approach-explanation.txt └── code.cpp ├── 133-12th_may-Largest_local_value_in_matrix ├── approach-explanation.txt └── code.cpp ├── 134-13th_may-Score_after_flipping_matrix ├── approach-explanation.txt └── code.cpp ├── 135-14th_may-Path_with_max_gold ├── approach-explanation.txt └── code.cpp ├── 136-15th_may-Safest_path_in_grid ├── approach-explanation.txt └── code.cpp ├── 137-16th_may-Evaluate_boolean_binary_tree ├── approach-explanation.txt └── code.cpp ├── 138-17th_may-Delete_leaves_with_given_value ├── approach-explanation.txt └── code.cpp ├── 139-18th_may-Distribute_coins_in_BT ├── approach-explanation.txt └── code.cpp ├── 140-19th_may-Find_max_sum_of_node_values ├── approach-explanation.txt └── code.cpp ├── 141-20th_may-Sum_of_all_subset_XOR_trials ├── approach-explanation.txt └── code.cpp ├── 142-21st_may-Subsets ├── approach-explanation.txt └── code.cpp ├── 143-22nd_may-Palindrome_partitioning ├── approach-explanation.txt └── code.cpp ├── 144-23rd_may-Number_of_beautiful_subsets ├── approach-explanation.txt └── code.cpp ├── 145-24th_may-Max_score_words_formed_by_letter ├── approach-explanation.txt └── code.cpp ├── 146-25th_may-Word_break-II ├── approach-explanation.txt └── code.cpp ├── 147-26th_may-Student_attendance_record-II ├── approach-explanation.txt └── code.cpp ├── 148-27th_may-Special_array_with_X_elements ├── approach-explanation.txt └── code.cpp ├── 149-28th_may-Equal_substrings_within_budget ├── approach-explanation.txt └── code.cpp ├── 150-29th_may-Num_of_steps_to_reduce_num_in_binary_rep ├── approach-explanation.txt └── code.cpp ├── 151-30th_may-Count_triplets_that_can_form_two_arrays ├── approach-explanation.txt └── code.cpp ├── 152-31st_may-Single_number-III ├── approach-explanation.txt └── code.cpp ├── 153-1st_June-Score_of_a_string ├── approach-explanation.txt └── code.cpp ├── 154-2nd_June-Reverse_string ├── approach-explanation.txt └── code.cpp ├── 155-3rd_June-Append_characters_to_string ├── approach-explanation.txt └── code.cpp ├── 156-4th_June-Longest_palindrome ├── approach-explanation.txt └── code.cpp ├── 157-5th_June-Find_common_characters ├── approach-explanation.txt └── code.cpp ├── 158-6th_June-Hand_of_straights ├── approach-explanation.txt └── code.cpp ├── 159-7th_June-Replace_words ├── approach-explanation.txt └── code.cpp ├── 160-8th_June-Continuous_subarray_sum ├── approach-explanation.txt └── code.cpp ├── 161-9th_June-Subaaray_sums_divisible_by_K ├── approach-explanation.txt └── code.cpp ├── 162-10th_June-Height_checker ├── approach-explanation.txt └── code.cpp ├── 163-11th_June-Relative_sort_array ├── approach-explanation.txt └── code.cpp ├── 164-12th_June-Sort_colours ├── approach-explanation.txt └── code.cpp ├── 165-13th_June-Move_to_seat_everyone ├── approach-explanation.txt └── code.cpp ├── 166-14th_June-Min_increment_to_make_array_unique ├── approach-explanation.txt └── code.cpp ├── 167-15th_June-IPO ├── approach-explanation.txt └── code.cpp ├── 168-16th_June-Patching_array ├── approach-explanation.txt └── code.cpp ├── 169-17th_June-Sum_of_square_nums ├── approach-explanation.txt └── code.cpp ├── 170-18th_June-Assigning_work ├── approach-explanation.txt └── code.cpp ├── 171-19th_June-Min_num_of_days_to_make_m_bouqets ├── approach-explanation.txt └── code.cpp ├── 172-20th_June-Magnetic_force_between_balls ├── approach-explanation.txt └── code.cpp ├── 173-21st_June-Grumpy_bookstore_owner ├── approach-explanation.txt └── code.cpp ├── 174-22nd_June-Count_num_of_nice_subarrays ├── approach-explanation.txt └── code.cpp ├── 175-23rd_June-Long_cont_subarray_with_absolute_diff ├── approach-explanation.txt └── code.cpp ├── 176-24th_June-Min_num_of_K_consecutive_bit_slips ├── approach-explanation.txt └── code.cpp ├── 177-25th_June-BST_to_greater_sum_tree ├── approach-explanation.txt └── code.cpp ├── 178-26th_June-Balance_BST ├── approach-explanation.txt └── code.cpp ├── 179-27th_June-Center_of_star_graph ├── approach-explanation.txt └── code.cpp ├── 180-28th_June-Max_imp_of_roads ├── approach-explanation.txt └── code.cpp ├── 181-29th_June-Ancestors_of_node_in_acyclic_graph ├── approach-explanation.txt └── code.cpp ├── 182-30th_June-Remove_max_edges ├── approach-explanation.txt └── code.cpp ├── 183-1st_July-Three_consecutive_odds ├── approach-explanation.txt └── code.cpp ├── 184-2nd_July-Intersection_of_arrays-II ├── approach-explanation.txt └── code.cpp ├── 185-3rd_July-Min_diff_bw_values ├── approach-explanation.txt └── code.cpp ├── 186-4th_July-Merge_nodes_in_bw_zeroes ├── approach-explanation.txt └── code.cpp ├── 187-5th_July-Find_min_max_num_of_nodes ├── approach-explanation.txt └── code.cpp ├── 188-6th_July-Pass_the_pillow ├── approach-explanation.txt └── code.cpp ├── 189-7th_July-Water_bottles ├── approach-explanation.txt └── code.cpp ├── 190-8th_July-Find_winner ├── approach-explanation.txt └── code.cpp ├── 191-9th_July-Average_waiting_time ├── approach-explanation.txt └── code.cpp ├── 192-10th_July-Crawler_log_folder ├── approach-explanation.txt └── code.cpp ├── 193-11th_July-Reverse_substrings ├── approach-explanation.txt └── code.cpp ├── 194-12th_July-Max_score_from_substrings ├── approach-explanation.txt └── code.cpp ├── 195-13th_July-Robot_collisions ├── approach-explanation.txt └── code.cpp ├── 196-14th_July-Number_of_atoms ├── approach-explanation.txt └── code.cpp ├── 197-15th_July-Create_binary_tree ├── approach-explanation.txt └── code.cpp ├── 198-16th_July-Step-by-step_directions ├── approach-explanation.txt └── code.cpp ├── 199-17th_July-Delete_nodes ├── approach-explanation.txt └── code.cpp ├── 200-18th_July-Number_of_good_leaf_node_pairs ├── approach-explanation.txt └── code.cpp ├── 201-19th_July-Lucky_number ├── approach-explanation.txt └── code.cpp ├── 202-20th_July-Find_valid_matrix ├── approach-explanation.txt └── code.cpp ├── 203-21st_July-Build_matrix_with_conditions ├── approach-explanation.txt └── code.cpp ├── 204-22nd_July-Sort_the_people ├── approach-explanation.txt └── code.cpp ├── 205-23rd_July-Sort_array_by_freq ├── approach-explanation.txt └── code.cpp ├── 206-24th_July-Sort_jumbled_numbers ├── approach-explanation.txt └── code.cpp ├── 207-25th_July-Sort_array ├── approach-explanation.txt └── code.cpp ├── 208-26th_July-Find_city ├── approach-explanation.txt └── code.cpp ├── 209-27th_July-Min_cost_to_convert ├── approach-explanation.txt └── code.cpp ├── 210-28th_July-Second_min_time ├── approach-explanation.txt └── code.cpp ├── 211-29th_July-Count_number_of_teams ├── approach-explanation.txt └── code.cpp ├── 212-30th_July-Min_deletions ├── approach-explanation.txt └── code.cpp ├── 213-31st_July-Filling_bookcase_shelves ├── approach-explanation.txt └── code.cpp ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/next-step-for-interview-prep/Daily-leetcode-problem_with_detailed_solutions/fa312f3991123996752f26744293490c29e8761c/.gitignore -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x86", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "C:/MinGW64/bin/gcc.exe", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x86", 12 | "compilerArgs": [ 13 | "" 14 | ] 15 | } 16 | ], 17 | "version": 4 18 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "externalConsole": true, 11 | "cwd": "c:/Users/saksh/OneDrive/Desktop/github/Daily-leetcode-problem_with_detailed_solutions", 12 | "program": "c:/Users/saksh/OneDrive/Desktop/github/Daily-leetcode-problem_with_detailed_solutions/build/Debug/outDebug", 13 | "MIMode": "gdb", 14 | "miDebuggerPath": "gdb", 15 | "setupCommands": [ 16 | { 17 | "description": "Enable pretty-printing for gdb", 18 | "text": "-enable-pretty-printing", 19 | "ignoreFailures": true 20 | } 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /001-1st_jan-Assign_Cookies/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Here we are using two variables i and j that will iterate through the arrays greed factor and size of cookies and will help us compare them in O[N] time. And as soon as we reach the end of size of cookie array, the array will terminate and we will return the number of children who got correct cookie size. -------------------------------------------------------------------------------- /001-1st_jan-Assign_Cookies/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int findContentChildren(vector& g, vector& s) { 9 | sort(g.begin(), g.end()); 10 | sort(s.begin(), s.end()); 11 | int count = 0; 12 | int i = 0; 13 | int j = 0; 14 | while (i < g.size() && j < s.size()) { 15 | if (s[j] >= g[i]) { 16 | count++; 17 | i++; 18 | } 19 | j++; 20 | } 21 | return count; 22 | } 23 | }; -------------------------------------------------------------------------------- /002-2nd_jan-Convert_array_to_2D/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | In this question, we need to convert an array into 2-d array, with the condition being that if there exists duplicates of an element, then they have to be pushed to next row in the array and only distinct integers can be present in the array. 2 | 3 | So with the same logic were are going to proceed solving this question in O(N) time complexity by understanding that as we traverse through the array and encounter a duplicate, we will push it in the next row of our 2-D array and when the traversal will be done, our final 2-D array will be ready. -------------------------------------------------------------------------------- /003-3rd_jan-Laser_beams_in_bank/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Here we solved our problem using greedy approach. 2 | In this question we first simply converted the string into integers and took their sum. Then we will check if sum is zero or not. If it comes out to be not zero we will preserve its value in another variable named prevSum till we find another non zero sum row after which we will add sum*prevRow to our solution and so on. -------------------------------------------------------------------------------- /003-3rd_jan-Laser_beams_in_bank/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfBeams(vector& bank) { 4 | ios_base::sync_with_stdio(false); 5 | cin.tie(NULL); 6 | 7 | int prevRow = 0; 8 | int solution = 0; 9 | for (auto row : bank) { 10 | int sum = 0; 11 | for (auto c : row) { 12 | int temp = c - '0'; 13 | sum += temp; 14 | } 15 | solution += sum * prevRow; 16 | prevRow = (sum == 0) * prevRow + sum; 17 | } 18 | return solution; 19 | } 20 | }; -------------------------------------------------------------------------------- /004-4th_jan-Make_array_empty/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | It uses a map mp to calculate the frequency of each number in nums. 2 | 3 | If any number occurs only once in nums, it's impossible to achieve the desired pattern, so the function returns -1. 4 | 5 | It calculates the number of moves needed to make all occurrences of each number a multiple of 3. If there are remaining occurrences (not divisible by 3), it adds one more move for each such occurrence. 6 | 7 | Finally, it returns the total number of moves needed to achieve the desired pattern. -------------------------------------------------------------------------------- /004-4th_jan-Make_array_empty/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minOperations(vector& nums) { 9 | unordered_mapmp; 10 | for(auto a: nums){ 11 | mp[a]++; 12 | } 13 | 14 | int count=0; 15 | for(auto a: mp){ 16 | int t = a.second; 17 | if(t==1)return -1; 18 | count += t/3; 19 | if(t%3)count++; 20 | } 21 | return count; 22 | } 23 | }; -------------------------------------------------------------------------------- /005-5th_jan-Longest_increasing_sequence/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | We can initialize an array dp of the same length as the input array nums, where dp[i] represents the length of the longest increasing subsequence ending at index i. We can iterate through the array and update dp based on the elements before the current index. The final result will be the maximum value in the dp array. -------------------------------------------------------------------------------- /005-5th_jan-Longest_increasing_sequence/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int lengthOfLIS(vector &nums) 10 | { 11 | if(nums.empty()) 12 | { 13 | return 0; 14 | } 15 | int n = nums.size(); 16 | vector dp(n,0); 17 | for (int i = 1; i < n; i++) 18 | { 19 | for (int j = 0; j < i; j++) 20 | { 21 | if(nums[i] > nums[j]) 22 | { 23 | dp[i] = max( dp[i], dp[j] + 1); 24 | } 25 | } 26 | } 27 | return *max_element(dp.begin(), dp.end()); 28 | } 29 | }; -------------------------------------------------------------------------------- /007-7th_jan-Arithmetic_slices_II/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution { 6 | public: 7 | int numberOfArithmeticSlices(std::vector& nums) { 8 | int n = nums.size(); 9 | int total_count = 0; 10 | 11 | std::vector> dp(n); 12 | 13 | for (int i = 1; i < n; ++i) { 14 | for (int j = 0; j < i; ++j) { 15 | long long diff = static_cast(nums[i]) - nums[j]; 16 | 17 | if (diff > INT_MAX || diff < INT_MIN) 18 | continue; 19 | 20 | int diff_int = static_cast(diff); 21 | 22 | dp[i][diff_int] += 1; 23 | 24 | if (dp[j].count(diff_int)) { 25 | dp[i][diff_int] += dp[j][diff_int]; 26 | total_count += dp[j][diff_int]; 27 | } 28 | } 29 | } 30 | 31 | return total_count; 32 | } 33 | }; -------------------------------------------------------------------------------- /008-8th_jan-Range_sum_BST/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode 5 | { 6 | int val; 7 | TreeNode* left; 8 | TreeNode* right; 9 | 10 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | int rangeSumBST(TreeNode* root, int low, int high) { 16 | if (!root) { 17 | return 0; 18 | } 19 | 20 | int currentVal = (root->val >= low && root->val <= high) ? root->val : 0; 21 | 22 | int leftSum = rangeSumBST(root->left, low, high); 23 | int rightSum = rangeSumBST(root->right, low, high); 24 | 25 | return currentVal + leftSum + rightSum; 26 | } 27 | }; -------------------------------------------------------------------------------- /009-9th_jan-Leaf_similar_trees/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct TreeNode 7 | { 8 | int val = 0; 9 | TreeNode *left = nullptr; 10 | TreeNode *right = nullptr; 11 | }; 12 | 13 | class Solution { 14 | public: 15 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 16 | function&)> collectLeafValues = 17 | [&](TreeNode* root, vector& leafValues) { 18 | if (!root) { 19 | return; 20 | } 21 | if (!root->left && !root->right) { 22 | leafValues.push_back(root->val); 23 | } 24 | collectLeafValues(root->left, leafValues); 25 | collectLeafValues(root->right, leafValues); 26 | }; 27 | 28 | vector leafValues1, leafValues2; 29 | collectLeafValues(root1, leafValues1); 30 | collectLeafValues(root2, leafValues2); 31 | 32 | return leafValues1 == leafValues2; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /011-11th_jan-Difference_node_ancestor/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The goal is to find the maximum difference between the values of any ancestor and descendant nodes in a binary tree. To achieve this, we need to track the minimum and maximum values encountered during the traversal. 3 | 4 | Approach 5 | Initialize the minimum and maximum values to the root node's value. 6 | Traverse the tree using a recursive approach. 7 | Update the minimum and maximum values encountered during the traversal. 8 | At each node, calculate the difference between the current node's value and the updated minimum and maximum values. 9 | Update the global maximum difference if a larger difference is found. 10 | Recursively explore the left and right subtrees. 11 | Return the maximum difference after the traversal. 12 | Complexity 13 | Time complexity: The time complexity is O(N), where N is the number of nodes in the tree, as we visit each node once. 14 | Space complexity: The space complexity is O(H), where H is the height of the tree. In the worst case (unbalanced tree), the recursion stack could go as deep as the height of the tree. -------------------------------------------------------------------------------- /011-11th_jan-Difference_node_ancestor/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode 5 | { 6 | int val; 7 | TreeNode *left; 8 | TreeNode *right; 9 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | }; 13 | 14 | class Solution 15 | { 16 | public: 17 | int maxAncestorDiff(TreeNode *root) 18 | { 19 | if (!root) 20 | return 0; 21 | int minVal = root->val, maxVal = root->val; 22 | differ(root, minVal, maxVal); 23 | return diff; 24 | } 25 | 26 | private: 27 | int diff = 0; 28 | 29 | void differ(TreeNode *root, int minVal, int maxVal) 30 | { 31 | if (!root) 32 | return; 33 | diff = max(diff, max(abs(minVal - root->val), abs(maxVal - root->val))); 34 | minVal = min(minVal, root->val); 35 | maxVal = max(maxVal, root->val); 36 | differ(root->left, minVal, maxVal); 37 | differ(root->right, minVal, maxVal); 38 | } 39 | }; -------------------------------------------------------------------------------- /012-12th_jan-Half_strings_alike/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The problem involves counting the number of vowels in two halves of a string. A straightforward approach is to iterate through each character in both halves and count the vowels. Afterward, compare the counts to determine if the halves are alike. 3 | Approach 4 | 1. Define a helper function count_vowels to count the number of vowels in a given string. 5 | 2. Compute the length of the input string and find the midpoint. 6 | 3. Split the string into two halves: the first half (first_half) and the second half (second_half). 7 | 4. Use the count_vowels function to count the vowels in both halves. 8 | 5. Compare the counts of vowels in both halves. If they are equal, return True; otherwise, return False. 9 | Complexity 10 | Time complexity: 11 | O(n)O(n)O(n), where nnn is the length of the input string. The function iterates through each character in the two halves to count the vowels. 12 | Space complexity: 13 | O(1)O(1)O(1), as the additional space used is constant, regardless of the input size. -------------------------------------------------------------------------------- /012-12th_jan-Half_strings_alike/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool halvesAreAlike(string s) { 8 | auto countVowels = [](const string& str) { 9 | unordered_set vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 10 | int count = 0; 11 | for (char c : str) { 12 | if (vowels.count(c) > 0) { 13 | count++; 14 | } 15 | } 16 | return count; 17 | }; 18 | 19 | int length = s.length(); 20 | int midPoint = length / 2; 21 | 22 | string firstHalf = s.substr(0, midPoint); 23 | string secondHalf = s.substr(midPoint); 24 | 25 | return countVowels(firstHalf) == countVowels(secondHalf); 26 | } 27 | }; -------------------------------------------------------------------------------- /013-13th_jan-Make_strings_anagram/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minSteps(string s, string t) { 8 | vector count_s(26, 0); 9 | vector count_t(26, 0); 10 | 11 | for (char ch : s) { 12 | count_s[ch - 'a']++; 13 | } 14 | 15 | for (char ch : t) { 16 | count_t[ch - 'a']++; 17 | } 18 | 19 | int steps = 0; 20 | for (int i = 0; i < 26; i++) { 21 | steps += abs(count_s[i] - count_t[i]); 22 | } 23 | 24 | return steps / 2; 25 | } 26 | }; -------------------------------------------------------------------------------- /014-14th_jan-Two_strings_are_close/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Frequency Counting: 2 | 3 | Two vectors (freq1 and freq2) are used to count the frequency of each letter in word1 and word2. 4 | freq1[i] stores the count of the i-th letter in the English alphabet in word1, and similarly for freq2. 5 | Checking Presence of Characters: 6 | 7 | Iterate over each character in the alphabet. 8 | If a character is present in one word and not in the other (or vice versa), return false. 9 | This ensures that both words contain the same set of characters. 10 | Sorting Frequencies: 11 | 12 | Sort the frequency vectors (freq1 and freq2). 13 | This step is necessary because the order of frequencies doesn't matter, only their values. 14 | Comparing Sorted Frequencies: 15 | 16 | Iterate through the sorted frequency vectors and compare corresponding elements. 17 | If any corresponding elements are not equal, return false. 18 | Final Result: 19 | 20 | If all the checks pass, return true, indicating that the two words are "close" as per the problem definition. 21 | Complexity 22 | Time complexity: 23 | O(n)O(n)O(n) 24 | 25 | Space complexity: 26 | O(1)O(1)O(1) -------------------------------------------------------------------------------- /014-14th_jan-Two_strings_are_close/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool closeStrings(std::string word1, std::string word2) { 9 | std::vector freq1(26, 0); 10 | std::vector freq2(26, 0); 11 | 12 | for (char ch : word1) { 13 | freq1[ch - 'a']++; 14 | } 15 | 16 | for (char ch : word2) { 17 | freq2[ch - 'a']++; 18 | } 19 | 20 | for (int i = 0; i < 26; i++) { 21 | if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) { 22 | return false; 23 | } 24 | } 25 | 26 | std::sort(freq1.begin(), freq1.end()); 27 | std::sort(freq2.begin(), freq2.end()); 28 | 29 | for (int i = 0; i < 26; i++) { 30 | if (freq1[i] != freq2[i]) { 31 | return false; 32 | } 33 | } 34 | 35 | return true; 36 | } 37 | }; 38 | 39 | 40 | -------------------------------------------------------------------------------- /016-16th_jan-Insert_delete_random/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | The class RandomizedSet uses a vector v to store the elements and an unordered map mp to store the mapping of elements to their indices in the vector. 2 | The search function checks if a given value is present in the set by looking it up in the unordered map. 3 | The insert function adds a value to the set if it's not already present. It appends the value to the vector and updates the unordered map with its index. 4 | The remove function removes a value from the set if it's present. It replaces the value with the last element in the vector, updates the index in the unordered map, and then removes the last element. 5 | The getRandom function returns a random element from the vector using the rand() function. 6 | 7 | Complexity 8 | Time complexity: 9 | O(1) 10 | 11 | Space complexity: 12 | O(n) -------------------------------------------------------------------------------- /016-16th_jan-Insert_delete_random/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class RandomizedSet { 7 | vector v; 8 | unordered_map mp; 9 | public: 10 | 11 | RandomizedSet() { 12 | } 13 | 14 | bool search(int val){ 15 | 16 | if(mp.find(val)!=mp.end()) 17 | return true; 18 | return false; 19 | 20 | } 21 | 22 | 23 | bool insert(int val) { 24 | 25 | if(search(val)) 26 | return false; 27 | 28 | v.push_back(val); 29 | mp[val] = v.size()-1; 30 | return true; 31 | } 32 | 33 | 34 | bool remove(int val) { 35 | 36 | if(!search(val)) 37 | return false; 38 | 39 | 40 | auto it = mp.find(val); 41 | v[it->second] = v.back(); 42 | v.pop_back(); 43 | mp[v[it->second]] = it->second; 44 | mp.erase(val); 45 | return true; 46 | } 47 | 48 | 49 | int getRandom() { 50 | 51 | return v[rand()%v.size()]; 52 | } 53 | }; -------------------------------------------------------------------------------- /017-17th_jan-unique_num_occurence/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Create an unordered map freq to store the frequency of each element in the array. 2 | Iterate through each element of the input array (arr). 3 | Update the frequency count in the freq map. 4 | Create an unordered set s to store unique frequencies. 5 | Iterate through the entries in the freq map and insert the frequencies into the set s. 6 | Check if the size of the freq map is equal to the size of the set s. If they are equal, it means that the occurrences of frequencies are unique. 7 | Complexity 8 | Time complexity: 9 | O(n) 10 | 11 | Space complexity: 12 | O(n) -------------------------------------------------------------------------------- /017-17th_jan-unique_num_occurence/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool uniqueOccurrences(vector& arr) { 10 | unordered_mapfreq; 11 | for(auto x: arr){ 12 | freq[x]++; 13 | } 14 | unordered_sets; 15 | for(auto x: freq){ 16 | s.insert(x.second); 17 | } 18 | return freq.size()==s.size(); 19 | } 20 | }; -------------------------------------------------------------------------------- /018-18th_jan-Climbing_stairs/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | In this problem, we can use 3 methods to reach the answer explained from best to worst- 2 | 3 | 1) Iterative approach- The best approach is to solve it iteratively in which we use 2 variables, one to update number of ways and the other to store number of ways calculated in previous iteration and these two variables being added together help us account for all number of ways to climb stairs by jumping either 2 steps or 1. 4 | 5 | 2) memoization approach- In memoization, we do the exact same thing as we did in recursion, only difference is it is further optimised by remembering what number of steps we calculated for a number and store it in a dp array to access instead of recalculating it thus saving us a lot of unnecesary and repeatitive function calls. 6 | 7 | 3) Recursion- In recursion, we simply do function calls and calculate the number of steps as asked in question. The only problem being is it is too repetitive and thus gives TLE. -------------------------------------------------------------------------------- /018-18th_jan-Climbing_stairs/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // class Solution { 6 | // public: 7 | // int climbStairs(int n) { 8 | // long long int prev1 = 1; 9 | // long long int prev2 = 1; 10 | 11 | // for(int i = 0; i < n; i++){ 12 | // long long int temp = prev1; // iterative approach 13 | // prev1 = prev1 + prev2; 14 | // prev2 = temp; 15 | 16 | // } 17 | 18 | // return prev2; 19 | // } 20 | // }; 21 | 22 | class Solution { 23 | public: 24 | int solveUsingMem(int n, vector& dp) { 25 | if (n == 0 || n == 1) 26 | return 1; 27 | if (dp[n] != -1) 28 | return dp[n]; 29 | int ans = solveUsingMem(n - 1, dp) + solveUsingMem(n - 2, dp); // memoization approach 30 | dp[n] = ans; 31 | return dp[n]; 32 | } 33 | 34 | int climbStairs(int n) { 35 | vector dp(n + 1, -1); 36 | int ans = solveUsingMem(n, dp); 37 | return ans; 38 | } 39 | }; -------------------------------------------------------------------------------- /019-19th_jan-Minimum_falling_path_sum/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | 8 | int minFallingPathSum(vector>& matrix) { 9 | int n=matrix.size(); 10 | int m=matrix[0].size(); 11 | vector>dp(n,vector(m,0)); 12 | 13 | for(int j=0;j=0) 26 | ld=matrix[i][j] + dp[i-1][j-1]; 27 | if(j+1 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int rob(vector& nums) { 9 | int rob = 0; 10 | int norob = 0; 11 | for (int i = 0; i < nums.size(); i++) { 12 | int newRob = norob + nums[i]; 13 | int newNoRob = max(norob, rob); 14 | rob = newRob; 15 | norob = newNoRob; 16 | } 17 | return max(rob, norob); 18 | } 19 | }; -------------------------------------------------------------------------------- /022-22nd_jan-Set_mismatch/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector findErrorNums(vector& nums) { 8 | vector ans; 9 | int s = nums.size(); 10 | int visited[s+1]; 11 | // int visited[s]={0}; 12 | 13 | for(int i = 0; i<=s; i++) 14 | { 15 | visited[i]=0; 16 | } 17 | 18 | for(int i = 0; i < s; i++) 19 | { 20 | visited[nums[i]] = visited[nums[i]] - 1; 21 | } 22 | 23 | for(int i = 1; i < s+1; i++) 24 | { 25 | if(visited[i]==-2) 26 | { 27 | ans.push_back(i); 28 | } 29 | } 30 | 31 | for(int i = 1; i < s+1; i++) 32 | { 33 | if(visited[i]==0) 34 | { 35 | ans.push_back(i); 36 | } 37 | } 38 | 39 | return ans; 40 | 41 | } 42 | }; -------------------------------------------------------------------------------- /023-23rd_jan-Max_length_concatenated_string/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxLength(vector& arr) { 8 | vector dp = {0}; 9 | int res = 0; 10 | 11 | for (const string& s : arr) { 12 | int a = 0, dup = 0; 13 | for (char c : s) { 14 | dup |= a & (1 << (c - 'a')); 15 | a |= 1 << (c - 'a'); 16 | } 17 | 18 | if (dup > 0) 19 | continue; 20 | 21 | for (int i = dp.size() - 1; i >= 0; i--) { 22 | if ((dp[i] & a) > 0) 23 | continue; 24 | dp.push_back(dp[i] | a); 25 | res = max(res, __builtin_popcount(dp[i] | a)); 26 | } 27 | } 28 | 29 | return res; 30 | } 31 | }; -------------------------------------------------------------------------------- /024-24th_jan-Pseudo_palindromic_paths/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct TreeNode { 6 | int val; 7 | TreeNode* left; 8 | TreeNode* right; 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | int pseudoPalindromicPaths(TreeNode* root) { 15 | return dfs(root, 0); 16 | } 17 | 18 | private: 19 | int dfs(TreeNode* node, int currentPath) { 20 | if (node == nullptr) { 21 | return 0; 22 | } 23 | 24 | currentPath = currentPath ^ (1 << node->val); 25 | 26 | if (node->left == nullptr && node->right == nullptr) { 27 | // Check if the path is pseudo-palindromic 28 | return (currentPath & (currentPath - 1)) == 0 ? 1 : 0; 29 | } 30 | 31 | int leftCount = dfs(node->left, currentPath); 32 | int rightCount = dfs(node->right, currentPath); 33 | 34 | return leftCount + rightCount; 35 | } 36 | }; 37 | 38 | int main() { 39 | // You can create a sample tree and test the function here if needed. 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /025-25th_jan-Longest_common_subsequence/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int longestCommonSubsequence(string text1, string text2) { 9 | if (text1.length() < text2.length()) { 10 | return LCS(text1, text2); 11 | } 12 | return LCS(text2, text1); 13 | } 14 | 15 | int LCS(string s1, string s2) { 16 | vector> M(2, vector(s1.length() + 1, 0)); 17 | 18 | for (int i = 1; i <= s2.length(); i++) { 19 | M[i % 2][0] = 0; 20 | for (int j = 1; j <= s1.length(); j++) { 21 | if (s1[j - 1] == s2[i - 1]) { 22 | M[i % 2][j] = M[(i - 1) % 2][j - 1] + 1; 23 | } else { 24 | M[i % 2][j] = max(M[(i - 1) % 2][j - 1], 25 | max(M[(i - 1) % 2][j], M[i % 2][j - 1])); 26 | } 27 | } 28 | } 29 | return M[s2.length() % 2][s1.length()]; 30 | } 31 | }; -------------------------------------------------------------------------------- /026-26th_jan-Out_of_boundary/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approaches: 2 | 3 | Initialization: 4 | 5 | Initialize a 2D vector dp of size m x n to represent the number of ways to reach each cell. 6 | Set the starting cell (x, y) to 1, as there is one way to reach it initially. 7 | Counting Paths: 8 | 9 | Use a nested loop to iterate over the number of moves from 1 to N. 10 | For each cell (i, j) in the grid: 11 | If (i, j) is on the boundary, increment the count by the value of dp[i][j]. This accounts for paths going out of the grid. 12 | Update temp[i][j] based on the sum of the ways to reach the adjacent cells in the previous state (dp). 13 | Use modulo M to avoid integer overflow. 14 | Updating State: 15 | 16 | Update the dp vector with the values from the temp vector for the next iteration. 17 | Return Result: 18 | 19 | Return the final count, representing the total number of paths that lead out of the grid after N moves. 20 | Complexity 21 | Time complexity: 22 | O(Nmn) 23 | (dp array with dimensions m×nm \times nm×n NNN times) 24 | 25 | Space complexity: 26 | O(mn) 27 | (dp and temptemptemp array of size m×nm \times nm×n are used.) -------------------------------------------------------------------------------- /027-27th_jan-K_inverse_pairs_array/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach:- 2 | Dynamic Programming: 3 | 4 | Use a 2D array dp to store the number of arrays with at most k inverse pairs for each size i and number of inverse pairs j. 5 | Initialize dp[0][0] to 1 as a base case. 6 | Recurrence Relation: 7 | 8 | For each i and j, iterate over x to compute the number of arrays with at most k inverse pairs. 9 | Update dp[i][j] based on the recurrence relation: dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007. 10 | Result: 11 | 12 | The final result is stored in dp[n][k], representing the number of arrays with at most k inverse pairs for an array of size n. 13 | Complexity 14 | Time complexity: 15 | O(n∗k^2) 16 | 17 | Space complexity: 18 | O(n∗k) -------------------------------------------------------------------------------- /027-27th_jan-K_inverse_pairs_array/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int kInversePairs(int n, int k) { 7 | int dp[1001][1001] = {1}; 8 | for (int i = 1; i <= n; i++) { 9 | for (int j = 0; j <= k; j++) { 10 | for (int x = 0; x <= min(j, i - 1); x++) { 11 | 12 | if (j - x >= 0) { 13 | dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007; 14 | } 15 | } 16 | } 17 | } 18 | 19 | return dp[n][k]; 20 | } 21 | }; 22 | 23 | 24 | -------------------------------------------------------------------------------- /029-29th_jan-Implement_queue_using_stack/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach:- 2 | 3 | Initialization: 4 | We have two stacks, s1 and s2, where s1 acts as the primary stack for enqueue operations, and s2 helps in reversing the order of elements for efficient dequeuing. 5 | Enqueue Operation (Push): 6 | 7 | When a new element is pushed into the queue (push operation): 8 | All elements from s1 are popped and pushed onto s2. This effectively reverses the order of elements. 9 | The new element is pushed onto the now-empty s1. 10 | Finally, elements are popped from s2 and pushed back onto s1 to maintain the original order. 11 | Dequeue Operation (Pop): 12 | 13 | When an element is dequeued (pop operation): 14 | The top element from s1 is directly popped. 15 | Peek Operation: 16 | 17 | The top element of s1 is returned for the peek operation. 18 | Empty Check: 19 | 20 | The empty operation checks whether s1 is empty. 21 | Complexity 22 | Time complexity: 23 | Enqueue (push): O(n) 24 | Dequeue (pop): O(1) 25 | Peek (peek): O(1) 26 | Empty Check (empty): O(1) 27 | (where n is the number of elements in the queue.) 28 | 29 | Space complexity: 30 | O(n) -------------------------------------------------------------------------------- /029-29th_jan-Implement_queue_using_stack/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MyQueue { 5 | private: 6 | stack s1; 7 | stack s2; 8 | 9 | public: 10 | MyQueue() {} 11 | 12 | void push(int x) { 13 | while (!s1.empty()) { 14 | s2.push(s1.top()); 15 | s1.pop(); 16 | } 17 | s1.push(x); 18 | while (!s2.empty()) { 19 | s1.push(s2.top()); 20 | s2.pop(); 21 | } 22 | } 23 | 24 | int pop() { 25 | int temp = s1.top(); 26 | s1.pop(); 27 | return temp; 28 | } 29 | 30 | int peek() { 31 | return s1.top(); 32 | } 33 | 34 | bool empty() { 35 | return s1.empty(); 36 | } 37 | }; -------------------------------------------------------------------------------- /030-30th_jan-Reverse_polish_notation/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approaches: 2 | 3 | Stack for Operand Storage: Use a stack to store operands while iterating through the given list of tokens. When encountering an operand, push it onto the stack. 4 | 5 | Operator Handling: When encountering an operator, pop the top two operands from the stack, apply the operator, and push the result back onto the stack. 6 | 7 | Numeric Token Detection: Check whether the token is a numeric value or an operator. If it is a numeric value, convert it to a long and push it onto the stack. 8 | 9 | Resolving Operations: Define a helper function (resolves) to handle the arithmetic operations based on the encountered operator. Perform the operation on the top two operands and push the result back onto the stack. 10 | 11 | Final Result: After processing all tokens, the final result will be the only remaining element on the stack. Return this value as the result of the evaluation. 12 | 13 | Complexity 14 | Time complexity: 15 | O(n) 16 | 17 | Space complexity: 18 | O(n) -------------------------------------------------------------------------------- /031-31st_jan-Daily_temperatures/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Initialize a deque to store indices of temperatures. 4 | Initialize a result vector to store the days until a warmer temperature is encountered. 5 | Iterate through the temperatures in reverse order. 6 | If the deque is empty, push the current index and set the result for that index to 0. 7 | If the deque is not empty, pop indices from the front of the deque while the current temperature is greater than or equal to the temperature at the front. 8 | If the deque is empty after the above step, set the result for the current index to 0. 9 | If the deque is not empty, set the result for the current index to the difference between the front of the deque and the current index. 10 | Push the current index to the front of the deque. 11 | Continue these steps for all temperatures. 12 | Return the result vector. 13 | Complexity 14 | Time complexity: 15 | O(n) 16 | 17 | Space complexity: 18 | O(n) -------------------------------------------------------------------------------- /031-31st_jan-Daily_temperatures/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | vector dailyTemperatures(vector &temperatures) 10 | { 11 | deque deque; 12 | vector res(temperatures.size(), 0); 13 | for (int i = temperatures.size() - 1; i >= 0; --i) 14 | { 15 | if (deque.empty()) 16 | { 17 | deque.push_front(i); 18 | res[i] = 0; 19 | } 20 | else 21 | { 22 | while (!deque.empty() && temperatures[i] >= temperatures[deque.front()]) 23 | { 24 | deque.pop_front(); 25 | } 26 | 27 | if (deque.empty()) 28 | { 29 | res[i] = 0; 30 | } 31 | else 32 | { 33 | res[i] = deque.front() - i; 34 | } 35 | 36 | deque.push_front(i); 37 | } 38 | } 39 | return res; 40 | } 41 | }; -------------------------------------------------------------------------------- /032-1st_feb-Divide_arrays_into_groups/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Dividing into Groups of Three: 4 | 5 | The goal is to divide the given array into groups of three consecutive elements. This decision likely comes from the requirement or nature of the problem being solved. 6 | Sorting for Comparison: 7 | 8 | Sorting the array is done to simplify the process of comparing the elements within each group. When the array is sorted, the minimum and maximum elements for each group can be easily identified. 9 | Setting a Condition (k): 10 | 11 | The condition involving k is introduced to filter out groups based on the difference between the maximum and minimum elements within each group. This condition ensures that the elements in a group are within a certain range. 12 | Iterative Approach: 13 | 14 | The code iterates through the sorted array in steps of 3, forming groups and checking the condition for each group. If a group meets the condition, it is added to the result. If any group fails the condition, the function returns an empty result. 15 | Complexity 16 | Time complexity: 17 | O(nlogn) 18 | 19 | Space complexity: 20 | O(n) -------------------------------------------------------------------------------- /032-1st_feb-Divide_arrays_into_groups/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | vector> divideArray(vector &nums, int k) 10 | { 11 | int size = nums.size(); 12 | sort(nums.begin(), nums.end()); 13 | vector> result(size / 3, vector(3)); 14 | int groupIndex = 0; 15 | for (int i = 0; i < size; i += 3) 16 | { 17 | if (i + 2 < size && nums[i + 2] - nums[i] <= k) 18 | { 19 | result[groupIndex] = {nums[i], nums[i + 1], nums[i + 2]}; 20 | groupIndex++; 21 | } 22 | else 23 | { 24 | return vector>(); 25 | } 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /033-2nd_feb-Sequential_digits/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Iterate through starting digits from 1 to 9. 3 | For each starting digit, build a sequential number by adding consecutive digits until reaching 9 or exceeding the high value. 4 | Add valid sequential numbers to a vector (a). 5 | Sort the vector. 6 | 7 | Complexity 8 | Time complexity: 9 | O(1) 10 | 11 | Space complexity: 12 | O(1) -------------------------------------------------------------------------------- /033-2nd_feb-Sequential_digits/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector sequentialDigits(int low, int high) { 9 | vector a; 10 | 11 | for (int i = 1; i <= 9; ++i) { 12 | int num = i; 13 | int nextDigit = i + 1; 14 | 15 | while (num <= high && nextDigit <= 9) { 16 | num = num * 10 + nextDigit; 17 | if (low <= num && num <= high) a.push_back(num); 18 | ++nextDigit; 19 | } 20 | } 21 | 22 | sort(a.begin(), a.end()); 23 | return a; 24 | } 25 | }; -------------------------------------------------------------------------------- /034-3rd_feb-Partition_array_max_sum/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Uses dynamic programming to find the maximum sum after partitioning an array. 4 | 5 | Initializing an array dp to store the maximum sum at each position. 6 | 7 | Iterating through the array from the end to the beginning. For each position, considering all possible partitions of the array. 8 | 9 | Within each partition, we calculates the maximum value and updates the dynamic programming array dp to store the maximum sum. 10 | 11 | The final result is stored in dp[0], representing the maximum sum after partitioning the entire array. 12 | 13 | Complexity 14 | Time complexity: 15 | O(n∗k) 16 | (where N is the size of the input array and K is the given parameter) 17 | 18 | Space complexity: 19 | O(k) -------------------------------------------------------------------------------- /034-3rd_feb-Partition_array_max_sum/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxSumAfterPartitioning(vector& arr, int k) { 8 | int N = arr.size(); 9 | int K = k + 1; 10 | 11 | vector dp(K); 12 | 13 | for (int start = N - 1; start >= 0; start--) { 14 | int currMax = 0; 15 | int end = min(N, start + k); 16 | 17 | for (int i = start; i < end; i++) { 18 | currMax = max(currMax, arr[i]); 19 | dp[start % K] = max(dp[start % K], dp[(i + 1) % K] + currMax * (i - start + 1)); 20 | } 21 | } 22 | return dp[0]; 23 | } 24 | }; -------------------------------------------------------------------------------- /036-5th_feb-Unique_char_in_string/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Initialize an unordered map (mp) to store character counts. 4 | Iterate through the string to update character counts in the map. 5 | Iterate through the string again, return the index of the first character with a count of 1. 6 | Complexity 7 | Time complexity: 8 | O(n) 9 | 10 | Space complexity: 11 | O(U) 12 | (U is the number of unique characters in the string) -------------------------------------------------------------------------------- /036-5th_feb-Unique_char_in_string/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int firstUniqChar(string s) 9 | { 10 | unordered_map mp; 11 | for (auto a : s) 12 | mp[a]++; 13 | 14 | for (int i = 0; i < s.size(); i++) 15 | { 16 | if (mp[s[i]] == 1) 17 | { 18 | 19 | return i; 20 | } 21 | } 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /037-6th_feb-Group_anagrams/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Using an Unordered Map: We utilize an unordered map to store the sorted version of each string (anagram) as the key and the index of the corresponding group in the answer vector as the value. This allows us to quickly check if an anagram group already exists. 3 | 4 | Iterating Through the Input Strings: We iterate through each string in the input vector 'strs'. 5 | 6 | Sorting Strings: For each string, we sort its characters alphabetically. This ensures that anagrams will have the same sorted representation. 7 | 8 | Grouping Anagrams: We check if the sorted string exists in the unordered map. If it does, we add the current string to the corresponding group in the answer vector. If not, we create a new group and store its index in the unordered map. 9 | 10 | Returning the Answer: Once all strings have been processed, we return the answer vector containing the grouped anagrams. 11 | 12 | Complexity 13 | Time complexity: 14 | O(n∗k∗logk) 15 | (K is the length of the longest string) 16 | 17 | Space complexity: 18 | O(n∗k) 19 | (K is the length of the longest string) -------------------------------------------------------------------------------- /037-6th_feb-Group_anagrams/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> groupAnagrams(vector& strs) { 10 | unordered_map mp; 11 | vector> ans; 12 | for (int i = 0; i < strs.size(); i++) { 13 | string temp = strs[i]; 14 | sort(temp.begin(), temp.end()); 15 | if (mp.find(temp) != mp.end()) { 16 | ans[mp[temp]].push_back(strs[i]); 17 | } else { 18 | mp[temp] = ans.size(); 19 | ans.push_back({strs[i]}); 20 | } 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /038-7th_feb-Sort_char_by_frequency/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Iterate through the input string 's' and count the frequency of each character using an unordered map 'hm'. 4 | Use a priority queue 'pq' to store pairs of characters and their frequencies, sorted in decreasing order of frequency. 5 | Define a lambda function 'cmp' to compare pairs based on the second element (frequency). 6 | Iterate through the hashmap entries and push each pair into the priority queue. 7 | Pop elements from the priority queue and append characters to the result string according to their frequency. 8 | Complexity 9 | Time complexity: 10 | O(nlogn) 11 | 12 | Space complexity: 13 | O(n) -------------------------------------------------------------------------------- /038-7th_feb-Sort_char_by_frequency/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | string frequencySort(string s) 11 | { 12 | auto cmp = [](const pair &a, const pair &b) 13 | { 14 | return a.second < b.second; 15 | }; 16 | 17 | priority_queue, vector>, decltype(cmp)> pq(cmp); 18 | 19 | unordered_map hm; 20 | 21 | for (char c : s) 22 | { 23 | hm[c]++; 24 | } 25 | 26 | for (const auto &entry : hm) 27 | { 28 | pq.push(make_pair(entry.first, entry.second)); 29 | } 30 | 31 | string result = ""; 32 | while (!pq.empty()) 33 | { 34 | pair p = pq.top(); 35 | pq.pop(); 36 | result.append(p.second, p.first); 37 | } 38 | 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /039-8th_feb-Perfect_squares/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Dynamic Programming: Utilizes dynamic programming to find the minimum number of perfect squares that sum up to the given number n. 3 | 4 | Initialization: Initializes a vector dp of size n + 1 where each element is initialized to INT_MAX, except dp[0] which is set to 0 since it doesn't require any perfect squares to represent. 5 | 6 | Iterative Calculation: Iterates from 1 to n to calculate the minimum number of perfect squares required for each number. 7 | 8 | Inner Loop: For each number i, iterates over all perfect squares less than or equal to i (from 1 to sqrt(i)) to find the minimum number of perfect squares required. 9 | 10 | Updating dp[i]: Updates dp[i] with the minimum value found by comparing it with the current value of dp[i - j * j] + 1, where j * j represents the perfect square being considered. 11 | 12 | Complexity 13 | Time complexity: 14 | O(n∗sqrt(n)) 15 | 16 | Space complexity: 17 | O(n) -------------------------------------------------------------------------------- /039-8th_feb-Perfect_squares/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int numSquares(int n) 10 | { 11 | vector dp(n + 1, INT_MAX); 12 | dp[0] = 0; 13 | for (int i = 1; i <= n; ++i) 14 | { 15 | for (int j = 1; j * j <= i; ++j) 16 | { 17 | dp[i] = min(dp[i], dp[i - j * j] + 1); 18 | } 19 | } 20 | return dp[n]; 21 | } 22 | }; -------------------------------------------------------------------------------- /041-10th_feb-Palindromic_substrings/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Initialization: The function initializes variables n (length of the input string s) and ans (to store the count of palindromic substrings). It checks if the length of the string is non-positive and returns 0 if true. 4 | 5 | Dynamic Programming: It creates a 2D boolean array dp of size n x n, where dp[i][j] indicates whether the substring from index i to j is a palindrome. 6 | 7 | Base Cases: It sets the diagonal elements of dp to true (single-letter substrings are always palindromes) and checks for double-letter substrings. 8 | 9 | Palindromic Substrings: It iterates over all substrings of length 3 to n, checking if each substring is a palindrome using dynamic programming. It updates the answer accordingly. 10 | 11 | Complexity 12 | Time complexity: 13 | O(n2) 14 | 15 | Space complexity: 16 | O(n2) -------------------------------------------------------------------------------- /041-10th_feb-Palindromic_substrings/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int countSubstrings(string s) 9 | { 10 | int n = s.size(); 11 | int ans = 0; 12 | 13 | if (n <= 0) 14 | return 0; 15 | 16 | vector> dp(n, vector(n, false)); 17 | 18 | for (int i = 0; i < n; ++i, ++ans) 19 | dp[i][i] = true; 20 | 21 | for (int i = 0; i < n - 1; ++i) 22 | { 23 | dp[i][i + 1] = (s[i] == s[i + 1]); 24 | ans += (dp[i][i + 1] ? 1 : 0); 25 | } 26 | 27 | for (int len = 3; len <= n; ++len) 28 | for (int i = 0, j = i + len - 1; j < n; ++i, ++j) 29 | { 30 | dp[i][j] = dp[i + 1][j - 1] && (s[i] == s[j]); 31 | ans += (dp[i][j] ? 1 : 0); 32 | } 33 | 34 | return ans; 35 | } 36 | }; -------------------------------------------------------------------------------- /042-11th_feb-Cherry_pickup_II/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition: 2 | 1st try uses recursive DP solution which has large time complexity. 3 | 4 | 2nd approach is a bottom-up design, an iterative DP version, converted from the 1st one with space optimization by using & tick 5 | 6 | Think how to reduce the TC. 7 | 8 | Approach: 9 | This is a 3D array named dp used for memoization to store intermediate results of the dynamic programming solution. 10 | 11 | int f(int r, int c0, int c1, vector>& grid): This is a recursive function f that calculates the maximum number of cherries that can be picked starting from cell (r, c0) and (r, c1). 12 | 13 | ans is initialized based on whether the two pickers are on the same or different cells. 14 | The nested loops iterate over the possible next positions for both pickers and calculate the maximum cherries that can be picked from the next row. 15 | 16 | ans += next; 17 | 18 | Complexity 19 | Time complexity: 20 | O(row×col2) 21 | 22 | Space complexity: 23 | O(70^3)→O(70^2) -------------------------------------------------------------------------------- /043-12th_feb-Majority_element/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int majorityElement(vector &nums) 9 | { 10 | ios_base::sync_with_stdio(false); 11 | cin.tie(nullptr); 12 | int count = 0; 13 | int candidate = 0; 14 | 15 | for (int num : nums) 16 | { 17 | if (count == 0) 18 | candidate = num; 19 | 20 | if (num == candidate) 21 | count++; 22 | 23 | else 24 | count--; 25 | } 26 | return candidate; 27 | } 28 | }; -------------------------------------------------------------------------------- /044-13th_feb-Palindrome_string_in_array/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool check(string s) 9 | { 10 | int i = 0, j = s.size() - 1; 11 | while (i <= j) 12 | { 13 | if (s[i] == s[j]) 14 | i++, j--; 15 | else 16 | return false; 17 | } 18 | return true; 19 | } 20 | string firstPalindrome(vector &words) 21 | { 22 | for (int i = 0; i < words.size(); i++) 23 | { 24 | if (check(words[i])) 25 | return words[i]; 26 | } 27 | return ""; 28 | } 29 | }; -------------------------------------------------------------------------------- /045-14th_feb-Rearrange_array_by_sign/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Here we are directly putting values in the ans vector with the help of 2 pointer approach where initially both the indexes pos and neg are 0 and 1. 3 | If we encounter positive element then will put values in the ans vector with the help of ans[pos] = nums[i] and if found negative element then ans[neg] = nums[i]. 4 | Here, we can't use ans.push_back() to add elements because we're not appending values sequentially. Instead, we're placing values at specific indexes based on the element we have. 5 | 6 | Complexity 7 | Time complexity: 8 | O(n) 9 | 10 | Space complexity: 11 | O(n) -------------------------------------------------------------------------------- /045-14th_feb-Rearrange_array_by_sign/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector rearrangeArray(vector& nums) { 8 | vectorans(nums.size(),0); 9 | int pos=0,neg=1; 10 | for(int i=0;i0){ 12 | ans[pos] = nums[i]; 13 | pos+=2; 14 | }else{ 15 | ans[neg] = nums[i]; 16 | neg+=2; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /046-15th_feb-Polygon_with_largest_perimeter/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach- 2 | Sort the array: Start by sorting the array of numbers in ascending order. 3 | 4 | Initialize variables: Set up variables to track the running sum (sum) and the largest perimeter found so far (ans). 5 | 6 | Iterate through the sorted array: Loop through each number in the sorted array. 7 | 8 | Check polygon condition: For each number, check if it's smaller than the sum of all previous numbers encountered. 9 | 10 | Update largest perimeter: If the condition is met, update ans with the sum of the current number and the running sum. Finally, return the largest perimeter found (ans). 11 | 12 | Complexity 13 | Time complexity: 14 | O(nlogn) 15 | 16 | Space complexity: 17 | O(1) -------------------------------------------------------------------------------- /046-15th_feb-Polygon_with_largest_perimeter/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | long long largestPerimeter(vector& nums) { 9 | sort(nums.begin(),nums.end()); 10 | long long sum = 0; 11 | long long ans = -1; 12 | 13 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution 7 | { 8 | public: 9 | int findLeastNumOfUniqueInts(vector &arr, int k) 10 | { 11 | unordered_map mp; 12 | for (auto a : arr) 13 | mp[a]++; 14 | 15 | vector v; 16 | int cnt = 0; 17 | for (auto a : mp) 18 | { 19 | v.push_back(a.second); 20 | } 21 | sort(v.begin(), v.end()); 22 | for (int i = 0; i < v.size(); i++) 23 | { 24 | if (k > v[i]) 25 | { 26 | k -= v[i]; 27 | v[i] = 0; 28 | } 29 | else 30 | { 31 | v[i] -= k; 32 | k = 0; 33 | } 34 | if (v[i] != 0) 35 | cnt++; 36 | } 37 | 38 | return cnt; 39 | } 40 | }; -------------------------------------------------------------------------------- /048-17th_feb-Furthest_building_you_can_reach/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int furthestBuilding(vector& h, int b, int l) { 9 | priority_queue, greater> pq; 10 | for (int i = 0; i < h.size() - 1; ++i) { 11 | int diff = h[i + 1] - h[i]; 12 | if (diff <= 0) continue; 13 | pq.push(diff); 14 | if (pq.size() > l) { 15 | b -= pq.top(); pq.pop(); 16 | } 17 | if (b < 0) return i; 18 | } 19 | return h.size() - 1; 20 | } 21 | }; -------------------------------------------------------------------------------- /050-19th_feb-Power_of_two/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | LMAO method 4 | We are literally gonna take the advantage of the constraints. I dont recommend you all to use this method during your interviews. It's a fun method . Do this on your own, you will enjoy it ;)) 5 | 6 | Hint:Constraints [-2^31 <= n <= 2^31 - 1] also 2^30 is 1073741824 -------------------------------------------------------------------------------- /050-19th_feb-Power_of_two/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool isPowerOfTwo(int n) 9 | { 10 | if (n == 0) 11 | return false; 12 | return (n > 0) && (1073741824 % n == 0); 13 | } 14 | }; -------------------------------------------------------------------------------- /051-20th_feb-Missing_number/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach- 2 | 3 | Approach 1(Using Vectors) 4 | Will iterate over the nums and will put elements in the v vector(size of n+1). 5 | 6 | At last will iterate in v and will return index of the element which is still -1. 7 | 8 | Complexity 9 | Time complexity: 10 | O(n) 11 | 12 | Space complexity: 13 | O(n) -------------------------------------------------------------------------------- /051-20th_feb-Missing_number/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | int missingNumber(vector& nums) { 7 | int n = nums.size(); 8 | vectorv(n+1,-1); 9 | for(int i =0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int rangeBitwiseAnd(int left, int right) { 7 | int cnt = 0; 8 | while (left != right) { 9 | left >>= 1; 10 | right >>= 1; 11 | cnt++; 12 | } 13 | return (left << cnt); 14 | } 15 | }; -------------------------------------------------------------------------------- /053-22nd_feb-Town_judge/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | 3 | Initialization: Initialize two vectors, in and out, to store the in-degree and out-degree of each person. 4 | 5 | Counting Trust Relationships: Iterate through each trust relationship, incrementing the out count for the truster and the in count for the trustee. 6 | 7 | Finding the Judge: Iterate through each person, checking if they have an in-degree of N - 1 and an out-degree of 0, indicating they are trusted by everyone and trust no one. 8 | 9 | Return Value: Return the index of the judge if found, otherwise return -1. 10 | 11 | Overall Functionality: The function identifies the judge within a community based on trust relationships, leveraging counts of in-degree and out-degree. 12 | 13 | Complexity 14 | Time complexity: 15 | O(n) 16 | 17 | Space complexity: 18 | O(n) -------------------------------------------------------------------------------- /053-22nd_feb-Town_judge/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findJudge(int n, vector>& trust) { 8 | vector trustScores(n + 1, 0); // To store trust scores for each person 9 | 10 | // Iterate through the trust relationships and update trust scores 11 | for (const auto& t : trust) { 12 | trustScores[t[0]]--; // Decrease trust score for the person who trusts 13 | trustScores[t[1]]++; // Increase trust score for the person who is trusted 14 | } 15 | 16 | // Check if there is a person who is trusted by everyone (except themselves) 17 | for (int i = 1; i <= n; ++i) { 18 | if (trustScores[i] == n - 1) { // If someone's trust score is n-1, they are the judge 19 | return i; 20 | } 21 | } 22 | 23 | return -1; // If no such person is found 24 | } 25 | }; -------------------------------------------------------------------------------- /057-26th_feb-Same_tree/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Base Case Handling: Checks if both trees are empty. If so, returns true. 3 | Null Check: If one tree is empty while the other is not, returns false. 4 | Value Comparison: Compares the values of the current nodes in both trees. 5 | Recursive Calls: Recursively calls the function for left subtrees and right subtrees. 6 | Return: Returns true if all conditions hold true, indicating identical trees; otherwise, returns false. 7 | 8 | Complexity 9 | Time complexity: 10 | O(n) 11 | (n is the number of nodes in the tree) 12 | 13 | Space complexity: 14 | O(h) 15 | (h is the height of the tree) -------------------------------------------------------------------------------- /057-26th_feb-Same_tree/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | bool isSameTree(TreeNode* p, TreeNode* q) { 16 | if(!p && !q) return true; 17 | if(!p || !q) return false; 18 | return p->val==q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 19 | } 20 | }; -------------------------------------------------------------------------------- /058-27th_feb-Diameter_binary_tree/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | int diameterOfBinaryTree(TreeNode* root) { 16 | // Define a helper function to calculate the diameter recursively 17 | int res = 0; 18 | diameter(root, res); 19 | return res; 20 | } 21 | 22 | private: 23 | int diameter(TreeNode* curr, int& res){ 24 | // Base case: if the current node is null, return 0 25 | if (!curr) return 0; 26 | 27 | // Recursively calculate the diameter of left and right subtrees 28 | int left = diameter(curr->left, res); 29 | int right = diameter(curr->right, res); 30 | 31 | // Update the maximum diameter encountered so far 32 | res = std::max(res, left + right); 33 | 34 | // Return the depth of the current node 35 | return std::max(left, right) + 1; 36 | } 37 | }; -------------------------------------------------------------------------------- /059-28th_feb-Find_bottom_left_tree_val/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The code aims to find and return the leftmost value in the last level of a binary tree. The use of a deque and a level-order traversal suggests a breadth-first search (BFS) approach to efficiently traverse the tree level by level. 3 | 4 | Approach 5 | Initialize a deque queue with the root node and a variable leftmost_value to None. 6 | Perform a while loop while the queue is not empty: 7 | Dequeue a node from the left of the deque. 8 | Update leftmost_value with the value of the dequeued node. 9 | Enqueue the right child if it exists. 10 | Enqueue the left child if it exists. 11 | Continue the process until all nodes at the last level are processed. 12 | Return the leftmost_value. 13 | Complexity 14 | Time complexity: O(n)O(n)O(n), where nnn is the number of nodes in the binary tree. Each node is processed once during the level-order traversal. 15 | Space complexity: O(m), where mmm is the maximum number of nodes at any level in the binary tree. In the worst case, the queue would store all nodes at the maximum level. -------------------------------------------------------------------------------- /059-28th_feb-Find_bottom_left_tree_val/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class TreeNode 6 | { 7 | public: 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int val) 12 | { 13 | this->val = val; 14 | this->left = this->right = NULL; 15 | } 16 | }; 17 | 18 | class Solution 19 | { 20 | public: 21 | int findBottomLeftValue(TreeNode *root) 22 | { 23 | queue q; 24 | q.push(root); 25 | int leftmost_value; 26 | 27 | while (!q.empty()) 28 | { 29 | TreeNode *node = q.front(); 30 | q.pop(); 31 | 32 | leftmost_value = node->val; 33 | 34 | if (node->right) 35 | { 36 | q.push(node->right); 37 | } 38 | if (node->left) 39 | { 40 | q.push(node->left); 41 | } 42 | } 43 | 44 | return leftmost_value; 45 | } 46 | }; -------------------------------------------------------------------------------- /061-1st_march-Max_binary_odd_number/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Count Number of 1 bits. place (n-1) bits at the start of string and place the remaining 1 bit at the end of string to make the number odd. 3 | 4 | Complexity 5 | Time complexity: O(n) 6 | Space complexity: O(n) -------------------------------------------------------------------------------- /061-1st_march-Max_binary_odd_number/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | string maximumOddBinaryNumber(string s) 9 | { 10 | int ones = count(s.begin(), s.end(), '1'); 11 | int sz = s.size(); 12 | 13 | string res = "1"; 14 | 15 | int nonOnes = sz - ones; 16 | ones--; 17 | 18 | while (nonOnes-- > 0) 19 | { 20 | res += "0"; 21 | } 22 | while (ones-- > 0) 23 | { 24 | res += "1"; 25 | } 26 | reverse(res.begin(), res.end()); 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /062-2nd_march-Squares_of_sorted_array/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approaches: 2 | 3 | Approach 1 (Radix Sort) 4 | Squared and stored the values in same array. 5 | Instead of using sort function, we are using radix sort to reduce complexity. 6 | 7 | Complexity 8 | Time complexity: 9 | O(n) 10 | 11 | Space complexity: 12 | O(n) 13 | 14 | Approach 2 (2 Pointer) 15 | 1. Since the original array is not sorted, it's not guaranteed 16 | that the largest elements (in terms of absolute value) 17 | are at the ends of the array. 18 | 19 | 2. By iterating backwards from the end of the array, we can 20 | start populating the result array from the end, ensuring 21 | that the squares of larger elements occupy the higher 22 | indices of the result array. 23 | 24 | Complexity 25 | Time complexity: 26 | O(n) 27 | 28 | Space complexity: 29 | O(n) -------------------------------------------------------------------------------- /063-3rd_march-Remove_Nth_node_from_last/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The removeNthFromEnd function appears to remove the n-th node from the end of a singly-linked list. 3 | 4 | Approach 5 | Define a helper function length_ll to calculate the length of the linked list. 6 | Calculate the length of the linked list using the helper function. 7 | If the length is 1, return NULL since there is only one node, and removing it would make the list empty. 8 | If the length is equal to n, return head->next to remove the first node. 9 | Iterate through the list to reach the node before the one to be removed. Update the next pointer of this node to skip the n-th node. 10 | Return the modified head of the list. 11 | Complexity 12 | Time complexity: 13 | Time complexity: O(n), where n is the length of the linked list. The function iterates through the list once to calculate its length and then once more to remove the n-th node from the end. 14 | Space complexity: 15 | Space complexity: O(1), The function uses a constant amount of extra space regardless of the size of the input linked list. -------------------------------------------------------------------------------- /064-4th_march-Bag_of_tokens/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int bagOfTokensScore(vector &tokens, int power) 10 | { 11 | int n = tokens.size(); 12 | int count = 0; 13 | sort(tokens.begin(), tokens.end()); 14 | int left = 0, right = n - 1; 15 | int maxScore = 0; 16 | while (left <= right) 17 | { 18 | if (tokens[left] <= power) 19 | { 20 | power -= tokens[left++]; 21 | count++; 22 | maxScore = max(maxScore, count); 23 | } 24 | else if (count > 0) 25 | { 26 | power += tokens[right--]; 27 | count--; 28 | } 29 | else 30 | { 31 | break; 32 | } 33 | } 34 | return maxScore; 35 | } 36 | }; -------------------------------------------------------------------------------- /065-5th_march-Min_length_of_string_after_erase/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int minimumLength(string s) 9 | { 10 | ios_base::sync_with_stdio(0); 11 | int first = 0; 12 | int last = s.length() - 1; 13 | char his = 'd'; 14 | while (first < last) 15 | { 16 | char temp = s[first]; 17 | if (s[first] == s[last]) 18 | { 19 | while ((first != last) && (temp == s[++first])) 20 | { 21 | } 22 | while ((first != last) && (temp == s[--last])) 23 | { 24 | } 25 | his = temp; 26 | } 27 | else 28 | { 29 | break; 30 | } 31 | }; 32 | 33 | if (first < last) 34 | { 35 | return last - first + 1; 36 | } 37 | else if ((first == last) && (s[first] != his)) 38 | { 39 | return 1; 40 | } 41 | else 42 | { 43 | return 0; 44 | } 45 | } 46 | }; -------------------------------------------------------------------------------- /066-6th_march-Loop_in_linkedlist/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Use 2 pointers slow & fast to detect the cycle. Floyd's Algorithm 3 | (Tortoise and Hare Algorithm) 4 | 5 | Approach 6 | If once fast==slow then there is a cycle, otherwise til null. 7 | In usual, the stride for slow is taken 1, and the stride for fast is taken 2. 8 | In 2nd approach, the stride for slow is taken 2, and the stride for fast is taken 3. since 2, 3 are coprime, if there is a cycle, fast & slow will meet. 9 | 10 | Complexity 11 | Time complexity: 12 | O(n) 13 | 14 | Space complexity: 15 | O(1) -------------------------------------------------------------------------------- /066-6th_march-Loop_in_linkedlist/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | bool hasCycle(ListNode *head) { 13 | ListNode *slow_pointer = head, *fast_pointer = head; 14 | while (fast_pointer != nullptr && fast_pointer->next != nullptr) { 15 | slow_pointer = slow_pointer->next; 16 | fast_pointer = fast_pointer->next->next; 17 | if (slow_pointer == fast_pointer) { 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | }; -------------------------------------------------------------------------------- /067-7th_march-Middle_of_linkedlist/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | The given C++ code defines a class Solution that contains a method middleNode for finding the middle node of a singly-linked list. The linked list is represented using the ListNode structure, where each node has an integer value (val) and a pointer to the next node (next). 3 | 4 | Here's an explanation of the approach used in the middleNode method: 5 | 6 | 1- Two pointers, slow and fast, are initialized to the head of the linked list. 7 | 8 | 2- A while loop is used to traverse the list with the fast pointer moving two steps at a time and the slow pointer moving one step at a time. 9 | 10 | 3- The loop continues until the fast pointer reaches the end of the list (i.e., becomes nullptr). 11 | 12 | 4- Inside the loop, both fast and slow pointers are moved accordingly. 13 | 14 | 5- The slow pointer will end up pointing to the middle node when the fast pointer reaches the end because it moves at half the speed of the fast pointer. 15 | 16 | 6- Finally, the slow pointer is returned, which now points to the middle node of the linked list. 17 | 18 | Complexity 19 | Time complexity:0(n) 20 | Space complexity:0(1) -------------------------------------------------------------------------------- /067-7th_march-Middle_of_linkedlist/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class ListNode 5 | { 6 | public: 7 | int val; 8 | ListNode *next; 9 | ListNode(int x) : val(x), next(NULL) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | ListNode* middleNode(ListNode* head) { 15 | ListNode *slow=head; 16 | ListNode *fast=head; 17 | 18 | while(fast){ 19 | fast=fast->next; 20 | if(fast){ 21 | fast=fast->next; 22 | slow=slow->next; 23 | } 24 | } 25 | return slow; 26 | } 27 | }; -------------------------------------------------------------------------------- /068-8th_march-Count_max_freq_elements/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | It needs a container for storing the counting results 3 | 4 | 2nd Approach is a 1 pass solution implemented in C++ which runs in 0ms & beats 100%. 5 | 6 | Approach: 7 | Since the constraints 1 <= nums[i] <= 100, an array of size 101 is suitable for solving problem, no need for a hash table(C++ unordered_map). 8 | 9 | Use a loop to count the frequencies storing in freq & max frequency maxF 10 | Use a loop to find the number f in freq with f==maxF & add it to ans 11 | return ans 12 | 2nd approach is just to combine the 2 loops into one loop which is more compact written. 13 | 14 | Complexity: 15 | 16 | Time complexity: 17 | O(n+m) where m = ∣freq∣ ≤ max(nums) ≤ 100 18 | 19 | Space complexity: 20 | O(m) -------------------------------------------------------------------------------- /068-8th_march-Count_max_freq_elements/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #pragma GCC optimize("O3", "unroll-loops") 7 | class Solution { 8 | public: 9 | int maxFrequencyElements(vector& nums) { 10 | int freq[101]={0}, maxF=0; 11 | for (int x: nums){ 12 | freq[x]++; 13 | maxF=max(maxF, freq[x]); 14 | } 15 | int ans=0; 16 | for (int f: freq){ 17 | if (f==maxF) 18 | ans+=f; 19 | } 20 | return ans; 21 | } 22 | }; 23 | 24 | auto init = []() 25 | { 26 | ios::sync_with_stdio(0); 27 | cin.tie(0); 28 | cout.tie(0); 29 | return 'c'; 30 | }(); -------------------------------------------------------------------------------- /069-9th_march-Minimum_common_value/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int getCommon(vector& nums1, vector& nums2) { 9 | unordered_mapmp1; 10 | for(auto it : nums1) 11 | { 12 | mp1[it]=true; 13 | } 14 | for(auto it : nums2) 15 | { 16 | if(mp1[it]==true) 17 | { 18 | return it; 19 | } 20 | } 21 | return -1; 22 | } 23 | }; -------------------------------------------------------------------------------- /070-10th_march-Intersection_of_two_arrays/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Don't want to use set or unorderd_set, just lookat the constraints 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 1000, container bitset<1001> is very suitable 3 | 4 | Approach 5 | Find A,BA, BA,B which are implemented by bitset or boolean arrays 6 | Push back the elements in the intersection A∩BA\cap BA∩B to ans. 7 | Return ans. 8 | Complexity 9 | Time complexity: 10 | O(∣nums1∣+∣nums2∣) 11 | 12 | Space complexity: 13 | O(1) -------------------------------------------------------------------------------- /070-10th_march-Intersection_of_two_arrays/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #pragma GCC optimize("O3", "unroll-loops") 7 | class Solution { 8 | public: 9 | vector intersection(vector& nums1, vector& nums2) { 10 | int n1=nums1.size(), n2=nums2.size(); 11 | bitset<1001> A=0, B=0; 12 | for (int x: nums1) A[x]=1; 13 | for (int x: nums2) B[x]=1; 14 | vector ans; 15 | ans.reserve(1001); 16 | for (int x=0; x<=1000; x++) 17 | if (A[x] && B[x]) ans.push_back(x); 18 | return ans; 19 | } 20 | }; 21 | 22 | auto init = []() { 23 | ios::sync_with_stdio(0); 24 | cin.tie(0); 25 | cout.tie(0); 26 | return 'c'; 27 | }(); -------------------------------------------------------------------------------- /071-11th_march-Custom_sort_string/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | string customSortString(string order, string s) 10 | { 11 | string result = ""; 12 | unordered_map mp; 13 | for (auto &it : s) 14 | { 15 | mp[it]++; 16 | } 17 | for (auto &it : order) 18 | { 19 | if (mp.find(it) != mp.end()) 20 | result.append(mp[it], it); 21 | mp.erase(it); 22 | } 23 | for (auto &it : mp) 24 | { 25 | result.append(it.second, it.first); 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /073-13th_march-Find_pivot/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | This question is quite intuitive, if we take an example, 3 | 4 | Input: n = 8, Output: 6 5 | Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. 6 | Observation: Let a be the original array, and S be the Prefix Sum array. Then nth prefix sum is S[n]. 7 | 8 | S = [0, 1, 3, 6, 10, 15, 21, 28, 36] 9 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8] 10 | If we want to find an pivot integer x in the array, then it should meet the needs that S[x] == S[n] - S[x] + x 11 | 12 | Approach 13 | Step 1: We can get the total sum, through the formula n * (1 + n) / 2 14 | Step 2: Through the process of building the prefix sum array, we check the condition S[x] == S[n] - S[x] + x, when it is true, we can return the current index. 15 | Complexity 16 | Time complexity: O(n) 17 | Space complexity: O(1) -------------------------------------------------------------------------------- /073-13th_march-Find_pivot/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | int pivotInteger(int n) 8 | { 9 | int total_sum = n * (1 + n) / 2, cur_sum = 0; 10 | for (int i = 1; i <= n; i++) 11 | { 12 | cur_sum += i; 13 | if ((total_sum - cur_sum + i) == cur_sum) 14 | return i; 15 | } 16 | return -1; 17 | } 18 | }; -------------------------------------------------------------------------------- /074-14th_march-Binary_subarrays_with_sum/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | To count the number of non-empty subarrays with a sum equal to the given goal, we iterate through the array while maintaining two pointers, i and j, representing the start and end of the subarray respectively. We update the goal variable based on the elements encountered and count the number of valid subarrays along the way. 3 | 4 | Approach 5 | Initialize variables i, count, and res to 0. i represents the start of the subarray, count keeps track of the number of subarrays with the sum equal to the goal, and res stores the total count. 6 | Iterate through the array using pointer j. 7 | If the current element nums[j] is 1, decrement the goal variable and reset count to 0. 8 | While goal is 0 and i is less than or equal to j, update goal by adding nums[i], increment i, increment count, and check if i exceeds j - goal + 1. If so, break the loop. 9 | While goal is less than 0, update goal by adding nums[i] and increment i. 10 | Add count to res. 11 | Return res as the result. 12 | Complexity 13 | Time complexity:O(n) 14 | Space complexity:O(1) -------------------------------------------------------------------------------- /074-14th_march-Binary_subarrays_with_sum/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int numSubarraysWithSum(vector &nums, int goal) 9 | { 10 | int i = 0, count = 0, res = 0; 11 | for (int j = 0; j < nums.size(); ++j) 12 | { 13 | if (nums[j] == 1) 14 | { 15 | goal--; 16 | count = 0; 17 | } 18 | 19 | while (goal == 0 && i <= j) 20 | { 21 | goal += nums[i]; 22 | i++; 23 | count++; 24 | if (i > j - goal + 1) 25 | break; 26 | } 27 | 28 | while (goal < 0) 29 | { 30 | goal += nums[i]; 31 | i++; 32 | } 33 | 34 | res += count; 35 | } 36 | return res; 37 | } 38 | }; -------------------------------------------------------------------------------- /075-15th_march-Prioduct_of_array/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Multiply all elements and divide it by respective element 3 | 4 | Approach 5 | Initialize a result array answers of the same size as the input array nums. 6 | Initialize two variables product and zeros to 1 and 0 respectively. 7 | Iterate through the nums array: 8 | If the current element is 0, increment the zeros count. 9 | Otherwise, multiply product by the current element. 10 | Iterate through the nums array again: 11 | If the current element is not 0: 12 | If zeros is greater than 1, push 0 into the answers array. 13 | Otherwise, push product divided by the current element into the answers array. 14 | If the current element is 0: 15 | If zeros is 1, push product into the answers array. 16 | Otherwise, push 0 into the answers array. 17 | Return the answers array. 18 | 19 | Complexity 20 | 21 | Time complexity:O(n) 22 | Space complexity:O(n) -------------------------------------------------------------------------------- /075-15th_march-Prioduct_of_array/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | vector productExceptSelf(vector &nums) 9 | { 10 | vector answers; 11 | int product = 1; 12 | int flag = 0; 13 | for (int i = 0; i < nums.size(); i++) 14 | { 15 | if (nums[i] == 0) 16 | flag++; 17 | else 18 | product *= nums[i]; 19 | } 20 | for (int i = 0; i < nums.size(); i++) 21 | { 22 | if (nums[i] == 0 && flag - 1 == 0) 23 | answers.push_back(product); 24 | else if (flag >= 1) 25 | answers.push_back(0); 26 | else 27 | answers.push_back(product / nums[i]); 28 | } 29 | return answers; 30 | } 31 | }; -------------------------------------------------------------------------------- /076-16th_march-Contiguous_subarray/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int findMaxLength(vector &nums) 10 | { 11 | int n = nums.size(); 12 | unordered_map mp; 13 | int sum = 0; 14 | int subArray_length = 0; 15 | for (int i = 0; i < n; i++) 16 | { 17 | sum += nums[i] == 0 ? -1 : 1; 18 | if (sum == 0) 19 | { 20 | subArray_length = i + 1; 21 | } 22 | else if (mp.find(sum) != mp.end()) 23 | { 24 | subArray_length = max(subArray_length, i - mp[sum]); 25 | } 26 | else 27 | { 28 | mp[sum] = i; 29 | } 30 | } 31 | return subArray_length; 32 | } 33 | }; -------------------------------------------------------------------------------- /077-17th_march-Insert_interval/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | vector> insert(vector> &intervals, vector &newInterval) 9 | { 10 | vector> merged; 11 | int i = 0; 12 | 13 | while (i < intervals.size() && intervals[i][1] < newInterval[0]) 14 | { 15 | merged.push_back(intervals[i]); 16 | i++; 17 | } 18 | 19 | while (i < intervals.size() && intervals[i][0] <= newInterval[1]) 20 | { 21 | newInterval = {min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])}; 22 | i++; 23 | } 24 | merged.push_back(newInterval); 25 | 26 | while (i < intervals.size()) 27 | { 28 | merged.push_back(intervals[i]); 29 | i++; 30 | } 31 | 32 | return merged; 33 | } 34 | }; -------------------------------------------------------------------------------- /078-18th_march-Min_no_of_arrows/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The problem asks for the minimum number of arrows needed to burst all balloons. Since the arrows can only be shot vertically, we need to find non-overlapping intervals of balloons and shoot arrows to cover each interval. 3 | 4 | Approach 5 | First, we sort the balloons based on their end coordinates. This allows us to iterate through the balloons in ascending order of their end coordinates. 6 | We initialize the variable arrows to 1, assuming that at least one arrow is needed. 7 | We iterate through the sorted balloons and compare the start coordinate of the current balloon with the end coordinate of the previous balloon. 8 | If the start coordinate of the current balloon is greater than the end coordinate of the previous balloon, it means these two balloons do not overlap, so we need to shoot another arrow. We increment the arrows count and update the prevEnd variable to the end coordinate of the current balloon. 9 | After iterating through all balloons, arrows will contain the minimum number of arrows needed. 10 | Complexity 11 | Time complexity: O(n*log(n)) 12 | Space complexity: O(1) -------------------------------------------------------------------------------- /078-18th_march-Min_no_of_arrows/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int findMinArrowShots(vector>& points) { 9 | 10 | // Sort the balloons based on their end coordinates 11 | sort(points.begin(), points.end(), [](const vector& a, const vector& b) { 12 | return a[1] < b[1]; 13 | }); 14 | 15 | int arrows = 1; 16 | int prevEnd = points[0][1]; 17 | 18 | // Count the number of non-overlapping intervals 19 | for (int i = 1; i < points.size(); ++i) { 20 | if (points[i][0] > prevEnd) { 21 | arrows++; 22 | prevEnd = points[i][1]; 23 | } 24 | } 25 | 26 | return arrows; 27 | } 28 | }; -------------------------------------------------------------------------------- /079-19th_march-Task_scheduler/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | To solve this problem efficiently, we aim to prioritize tasks with higher frequencies while respecting the cooling time constraint. By identifying the tasks' frequencies and organizing them accordingly, we can optimize the scheduling process. 3 | 4 | Approach 5 | Count the frequency of each task using an array. 6 | Sort the frequencies in descending order to prioritize tasks with higher frequency. 7 | Calculate the number of intervals needed based on the task 4. with the maximum frequency, considering the cooling time constraint. 8 | Return the total number of intervals required. 9 | Complexity 10 | Time complexity:Sorting the frequency array: O(26 log 26) ≈ O(1) 11 | Loop to calculate intervals: O(26) ≈ O(1) 12 | Overall: O(1) 13 | Space complexity:Array for frequency: O(26) ≈ O(1) -------------------------------------------------------------------------------- /079-19th_march-Task_scheduler/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int leastInterval(vector& tasks, int n) { 9 | int freq[26] = {0}; 10 | for(char task : tasks){ 11 | freq[task - 'A']++; 12 | } 13 | sort(begin(freq) , end(freq)); 14 | int chunk = freq[25] - 1; 15 | int idel = chunk * n; 16 | 17 | for(int i=24; i>=0; i--){ 18 | idel -= min(chunk,freq[i]); 19 | } 20 | 21 | return idel < 0 ? tasks.size() : tasks.size() + idel; 22 | } 23 | }; -------------------------------------------------------------------------------- /080-20th_march-Merge_in-between_LL/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition: 2 | 3 | To solve this problem, we need to traverse list1 to find the nodes at positions a and b. Once we locate these nodes, we can splice list2 between them. We'll connect the node before position a to the head of list2, and the last node of list2 to the node after position b. 4 | 5 | Approach: 6 | 7 | Traverse list1 to find the node at position a-1, a, and b+1. 8 | Attach the last node of list2 to the node after position b. 9 | Attach the node before position a to the head of list2. 10 | Return the head of list1. 11 | Complexity: 12 | 13 | Time complexity: O(n), where n is the size of list1 since we traverse it once to find the positions. 14 | Space complexity: O(1), as we use a constant amount of extra space. -------------------------------------------------------------------------------- /081-21st_march-Reverse_linked-list/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition: 2 | Exercise for reverse Linked List. 3 | 4 | Approach 5 | Transverse the ListNode with pointer cur. 6 | Use 2 extra pointers prev & Next to reverse the Linked List. 7 | 8 | Complexity 9 | Time complexity: 10 | O(n) 11 | 12 | Space complexity: 13 | O(1) -------------------------------------------------------------------------------- /081-21st_march-Reverse_linked-list/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class ListNode 5 | { 6 | public: 7 | int val; 8 | ListNode *next; 9 | ListNode(int val) 10 | { 11 | this->val = val; 12 | this->next = NULL; 13 | } 14 | }; 15 | 16 | class Solution 17 | { 18 | public: 19 | ListNode *reverseList(ListNode *head) 20 | { 21 | ListNode *nextNode, *prevNode = NULL; 22 | while (head) 23 | { 24 | nextNode = head->next; 25 | head->next = prevNode; 26 | prevNode = head; 27 | head = nextNode; 28 | } 29 | return prevNode; 30 | } 31 | }; -------------------------------------------------------------------------------- /084-24th_march-Find_duplicate/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: Slow and fast pointer 2 | The key intuition behind this method is that if there's a cycle in the linked list, the fast and slow pointers will eventually meet. 3 | We treat the array as a linked list, where the index represents the node and the value at that index represents the next node. 4 | Using the fast-slow pointers technique, we traverse the linked list. 5 | The slow pointer moves one step at a time while the fast pointer moves two steps at a time. 6 | If there's a cycle in the linked list (indicating a duplicate number), the fast and slow pointers will eventually meet. 7 | After identifying the meeting point, we reset the slow pointer to the start and move both pointers at the same pace until they meet again. The meeting point will be the duplicate number. 8 | Complexity 9 | Time complexity: O(N) 10 | Space complexity: O(1) -------------------------------------------------------------------------------- /084-24th_march-Find_duplicate/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findDuplicate(std::vector& nums) { 8 | int slow = nums[0]; 9 | int fast = nums[0]; 10 | 11 | // Find the intersection point of the two pointers 12 | do { 13 | slow = nums[slow]; 14 | fast = nums[nums[fast]]; 15 | } while (slow != fast); 16 | 17 | // Find the entrance of the cycle 18 | slow = nums[0]; 19 | while (slow != fast) { 20 | slow = nums[slow]; 21 | fast = nums[fast]; 22 | } 23 | 24 | return slow; 25 | } 26 | }; -------------------------------------------------------------------------------- /085-25th_march-Find_all_duplicates/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | To solve this problem in O(n) time and constant extra space, we can utilize the fact that all integers in the array are in the range [1, n] and each integer appears once or twice. We can iterate through the array and use each element as an index to mark the corresponding element as negative. If we encounter an element that is already negative, it means we have seen it before and it's a duplicate. 3 | 4 | Approach 5 | Initialize an empty vector ans to store the duplicates. 6 | Iterate through the array nums. 7 | For each element nums[i], take its absolute value x. 8 | Check if nums[x-1] is negative. 9 | If it is, then x is a duplicate, so add it to ans. 10 | Otherwise, mark nums[x-1] as negative. 11 | Return ans. 12 | Complexity 13 | Time complexity:O(n) 14 | Space complexity:O(k) 15 | max value of k = n/2 -------------------------------------------------------------------------------- /085-25th_march-Find_all_duplicates/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | vector findDuplicates(vector &nums) 9 | { 10 | vector ans; 11 | int n = size(nums); 12 | for (int i = 0; i < n; i++) 13 | { 14 | int x = abs(nums[i]); 15 | if (nums[x - 1] < 0) 16 | { 17 | 18 | ans.push_back(x); 19 | } 20 | nums[x - 1] *= -1; 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /086-26th_march-First_missing_positive/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int firstMissingPositive(vector& nums) { 9 | int n= size(nums); 10 | 11 | for(int i=0;i=1 && x<=n : to check if x is in range[1, n] 15 | // x != i+1 : skip if at index i correct element is present. 16 | // nums[x-1]!=x: skip if at index x-1 correct element is present 17 | while(x>=1 && x<=n && x!=i+1 && nums[x-1]!=x){ 18 | swap(nums[x-1],nums[i]); 19 | x=nums[i]; 20 | } 21 | } 22 | 23 | 24 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numSubarrayProductLessThanK(vector& nums, int k) { 8 | int left = 0, right = 0, product = 1, count = 0; 9 | int n = nums.size(); 10 | if(k <= 1) return 0; 11 | while (right < n) { 12 | product *= nums[right]; 13 | while (product >= k) product /= nums[left++]; 14 | count += 1 + (right - left); 15 | right++; 16 | } 17 | return count; 18 | } 19 | }; -------------------------------------------------------------------------------- /088-28th_march-Longest_subarray_with_freq_K/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | My first thought when approaching this problem is to use a sliding window technique because we are dealing with finding the longest subarray with a given condition. Since we are required to find the longest subarray with each element's frequency less than or equal to k, we can use a sliding window to efficiently keep track of the frequency of elements within a subarray. 3 | 4 | Approach 5 | Initialize two pointers, l and r, to mark the left and right boundaries of the current subarray. 6 | Initialize an unordered_map to store the frequency of elements within the current subarray. 7 | Iterate through the array from left to right using the right pointer r. 8 | Increment the frequency of nums[r] in the map. 9 | If the frequency of nums[r] exceeds k, we need to shrink the window from the left until the frequency new inserted element decrease by one. 10 | Update the maximum length of the good subarray if necessary. 11 | Return the maximum length found. 12 | Complexity 13 | Time complexity:O(n) 14 | Space complexity:O(n) -------------------------------------------------------------------------------- /088-28th_march-Longest_subarray_with_freq_K/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int maxSubarrayLength(vector &nums, int k) 10 | { 11 | int ans = 0; 12 | unordered_map mp; 13 | int n = nums.size(); 14 | 15 | for (int l = 0, r = 0; r < n; r++) 16 | { 17 | mp[nums[r]]++; // inserting value in window from right 18 | // if newly inserted element exceed frequencey poped it out from left 19 | if (mp[nums[r]] > k) 20 | { 21 | while (nums[l] != nums[r]) 22 | { 23 | mp[nums[l]]--; 24 | l++; 25 | } 26 | mp[nums[l]]--; 27 | l++; 28 | } 29 | ans = max(ans, r - l + 1); 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /089-29th_march-Count_subarrays_largest_appear_K_times/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The problem requires counting the number of subarrays where the maximum element of the array appears at least k times. This can be approached using a sliding window technique. 3 | 4 | Approach 5 | Find max element. 6 | l,r starting and ending point of current window. 7 | Iterate through the array with the r pointer, decrementing k whenever the element at r equals the maximum element. 8 | When k becomes zero, it indicates that the frequency of the maximum element in the current window has reached to k. 9 | Increment the l pointer until the frequency of the maximum element in the window becomes k-1. 10 | During this process, count the number of subarrays that can be formed using the current window. This count is equal to the number of elements to the left of the window with the maximum element included. 11 | Add this count to the answer. 12 | Continue this process until the r pointer reaches the end of the array. 13 | 14 | Complexity:- 15 | 16 | Time complexity:O(n) 17 | Space complexity: 18 | O(1) 19 | O(n) -------------------------------------------------------------------------------- /089-29th_march-Count_subarrays_largest_appear_K_times/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | long long countSubarrays(vector &nums, int k) 10 | { 11 | 12 | int mx = *max_element(begin(nums), end(nums)); 13 | long long ans = 0; 14 | 15 | int l = 0, r = 0, n = size(nums); 16 | while (r < n) 17 | { 18 | k -= (nums[r++] == mx); 19 | while (k == 0) 20 | { 21 | k += (nums[l++] == mx); 22 | } 23 | ans += l; 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /090-30th_march-Subarrays_with_K_different_ints/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int countSubarraysWithAtMostKDistinct(vector &nums, int k) 10 | { 11 | int n = nums.size(); 12 | 13 | unordered_map mp; 14 | 15 | int i = 0, j = 0; 16 | 17 | int c = 0; 18 | 19 | while (j < n) 20 | { 21 | mp[nums[j]]++; 22 | 23 | while (i <= j && mp.size() > k) 24 | { 25 | if (--mp[nums[i]] == 0) 26 | mp.erase(nums[i]); 27 | i++; 28 | } 29 | 30 | c += (j - i + 1); 31 | 32 | j++; 33 | } 34 | 35 | return c; 36 | } 37 | 38 | int subarraysWithKDistinct(vector &nums, int k) 39 | { 40 | return countSubarraysWithAtMostKDistinct(nums, k) - countSubarraysWithAtMostKDistinct(nums, k - 1); 41 | } 42 | }; -------------------------------------------------------------------------------- /091-31st_march-Count_subarrays_fixed_bounds/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | long long countSubarrays(vector& nums, int minK, int maxK) { 9 | long long res = 0; 10 | int bad_idx = -1, left_idx = -1, right_idx = -1; 11 | 12 | for (int i = 0; i < nums.size(); ++i) { 13 | if (!(minK <= nums[i] && nums[i] <= maxK)) { 14 | bad_idx = i; 15 | } 16 | 17 | if (nums[i] == minK) { 18 | left_idx = i; 19 | } 20 | 21 | if (nums[i] == maxK) { 22 | right_idx = i; 23 | } 24 | 25 | res += max(0, min(left_idx, right_idx) - bad_idx); 26 | } 27 | 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /092-1st_april-Length_of_last_word/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | To solve this problem, we need to find the last word in the string and return its length. We can achieve this by splitting the string into words and then returning the length of the last word. 3 | Approach 4 | 1. Strip trailing whitespaces from the input string using the strip() method. 5 | 2. Split the string into words using the split() method. 6 | 3. If there are no words after stripping whitespaces, return 0. 7 | 4. Otherwise, return the length of the last word, which is the last element in the list of words. 8 | Time complexity: 9 | 1. Stripping trailing whitespaces takes linear time, so it's O(n) where nnn is the length of the input string. 10 | 2. Splitting the string into words also takes linear time, so it's also O(n). 11 | 3. The overall time complexity is O(n). 12 | Space complexity: 13 | We store the list of words, which could take up to O(n) space if all characters in the input string are non-whitespace. -------------------------------------------------------------------------------- /092-1st_april-Length_of_last_word/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int lengthOfLastWord(string s) 9 | { 10 | int length = 0; 11 | bool counting = false; 12 | 13 | for (int i = s.length() - 1; i >= 0; i--) 14 | { 15 | if (s[i] != ' ') 16 | { 17 | counting = true; 18 | length++; 19 | } 20 | else if (counting) 21 | { 22 | break; 23 | } 24 | } 25 | 26 | return length; 27 | } 28 | }; -------------------------------------------------------------------------------- /095-4th_april-Depth_of_parentheses/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | To find the nesting depth of the given VPS string s, we can iterate through each character of the string and keep track of the current nesting depth. Whenever we encounter an opening parenthesis '(', we increment the depth, and whenever we encounter a closing parenthesis ')', we decrement the depth. We update the maximum depth encountered so far accordingly. 3 | Approach 4 | 1. Initialize variables count and max_num to keep track of the current depth and maximum depth encountered so far, respectively. Set both to 0. 5 | 2. Iterate through each character i in the input string s. 6 | 3. If i is '(', increment count by 1 and update max_num if count exceeds it. 7 | 4. If i is ')', decrement count by 1. 8 | 5. Finally, return max_num, which represents the maximum nesting depth. 9 | Complexity 10 | Time complexity: 11 | O(n), where n is the length of the input string s. We traverse the entire string once. 12 | Space complexity: 13 | O(1), as we only use a constant amount of extra space for variables count and max_num. -------------------------------------------------------------------------------- /095-4th_april-Depth_of_parentheses/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int maxDepth(string s) 9 | { 10 | int count = 0; 11 | int max_num = 0; 12 | for (char c : s) 13 | { 14 | if (c == '(') 15 | { 16 | count++; 17 | if (max_num < count) 18 | max_num = count; 19 | } 20 | else if (c == ')') 21 | { 22 | count--; 23 | } 24 | } 25 | return max_num; 26 | } 27 | }; -------------------------------------------------------------------------------- /096-5th_april-Make_string_great/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | We know that : 2 | ASCII value of uppercase alphabets – 65 to 90. 3 | ASCII value of lowercase alphabets – 97 to 122. 4 | 5 | so there are certain steps we have to take to grab the essence of it 6 | 7 | step 1: first we have to initialize a pointer flag which will cutoff the loop when there no lower,upper pair found 8 | 9 | step 2: we have to iterate throughout the loop and check whether there is any lower upper pair available,if yes delete it and continue the process. 10 | 11 | step 3:define a func which will check accordingly if a pair exists or not: thus we will have our output string . 12 | 13 | Ex.leEeetcode 14 | first iter: leEeetcode ->first pair found delete it 15 | second iter: leetcode -> no pair found hence return it as flag==1. 16 | 17 | Time complexity = O(N) 18 | space complexity = O(1) -------------------------------------------------------------------------------- /096-5th_april-Make_string_great/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | string makeGood(string s) 9 | { 10 | int i = 1; // Start from index 1 instead of 0 11 | while (i < s.length()) 12 | { 13 | if (abs(s[i] - s[i - 1]) == 32) 14 | { // Compare characters, not their ASCII values 15 | s.erase(i - 1, 2); // Erase the pair of characters 16 | if (i > 1) // Update i based on the previous characters if possible 17 | i--; 18 | } 19 | else 20 | { 21 | i++; // Move to the next character 22 | } 23 | } 24 | return s; 25 | } 26 | }; -------------------------------------------------------------------------------- /097-6th_april-Min_remove_to_make_valid_parenthesis/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string minRemoveToMakeValid(string s) { 7 | int open = 0; 8 | for(int i = s.length()-1; i>=0; i--) { 9 | if(s[i]==')') 10 | open++; 11 | if(s[i]=='(') { 12 | if(open==0) 13 | s.erase(i, 1); 14 | else 15 | open--; 16 | } 17 | } 18 | 19 | // Adjust the index when erasing characters 20 | for(int i = 0; i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool checkValidString(string s) { 7 | int cmin = 0; 8 | int cmax = 0; 9 | for (char c : s) { 10 | if (c == '(') { 11 | cmax++; 12 | cmin++; 13 | } else if (c == ')') { 14 | cmax--; 15 | cmin = max(cmin - 1, 0); 16 | } else if (c == '*') { 17 | cmax++; 18 | cmin = max(cmin - 1, 0); 19 | } 20 | if (cmax < 0) { 21 | return false; 22 | } 23 | } 24 | return cmin == 0; 25 | } 26 | }; -------------------------------------------------------------------------------- /099-8th_april-Students_eating_lunch/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | We will not need to move to the next sandwich until there is a match and we will only keep pushing the next student to the end of the line. 3 | 4 | Approach 5 | Circular queues will be used so as to reduce the space complexity. The condition to exit the loop is incase we do not get any sandwiches that match the students after we have gone through each students once then it is not possible to make any changes and we will exit the loop. The value of the students array is changed once a match is found since we do not want to keep matching the same value again (That particular students has left the queue). We will then check for the number of students remaining in the queue which is all the 1s and 0s. 6 | 7 | Complexity 8 | Time complexity:O(n) 9 | Space complexity:O(1) -------------------------------------------------------------------------------- /099-8th_april-Students_eating_lunch/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int countStudents(vector& students, vector& sandwiches) { 9 | int n=students.size(); 10 | queue q; 11 | for(int i=0;i0 && count!=q.size()){ 17 | if(q.front()==sandwiches[i]){ 18 | q.pop(); 19 | i++; 20 | count=0; 21 | } 22 | else{ 23 | q.push(q.front()); 24 | q.pop(); 25 | count++; 26 | } 27 | } 28 | return q.size(); 29 | } 30 | }; -------------------------------------------------------------------------------- /100-9th_april-Time_needed_to_buy_tickets/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | 1. Initialize a variable time to keep track of the total time taken. 3 | 2. While the person at position k hasn't bought all their tickets: 4 | Iterate through the queue and let each person buy a ticket. 5 | Update the queue by decrementing the number of tickets for the person who bought a ticket. 6 | Increment the time by 1 second for each pass. 7 | 3. Return the total time taken. 8 | Complexity 9 | Time complexity: 10 | The algorithm iterates through each person in the queue once, so the time complexity of the loop is O(n), where n is the number of people in the queue. 11 | Space complexity: 12 | The algorithm uses only a constant amount of extra space for variables such as total, i, and x. 13 | Therefore, the space complexity is O(1). -------------------------------------------------------------------------------- /100-9th_april-Time_needed_to_buy_tickets/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int timeRequiredToBuy(vector& tickets, int k) { 10 | int total = 0; 11 | 12 | for (int i = 0; i < tickets.size(); ++i) { 13 | if (i <= k) { 14 | total += min(tickets[i], tickets[k]); 15 | } else { 16 | total += min(tickets[i], tickets[k] - 1); 17 | } 18 | } 19 | 20 | return total; 21 | } 22 | }; -------------------------------------------------------------------------------- /103-12th_april-Trapping_rain_water/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int trap(std::vector &height) 11 | { 12 | int i = 0, left_max = height[0], sum = 0; 13 | int j = height.size() - 1, right_max = height[j]; 14 | while (i < j) 15 | { 16 | if (left_max <= right_max) 17 | { 18 | sum += (left_max - height[i]); 19 | i++; 20 | left_max = std::max(left_max, height[i]); 21 | } 22 | else 23 | { 24 | sum += (right_max - height[j]); 25 | j--; 26 | right_max = std::max(right_max, height[j]); 27 | } 28 | } 29 | return sum; 30 | } 31 | }; -------------------------------------------------------------------------------- /105-14th_april-Sum_of_left_leaves/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Use recursive preorder to transverse. 2 | If an extra parameter isLeft=0 is set, the code becomes much simpler. The following is written in Python: 3 | 4 | def f(root, isLeft=False): 5 | if not root: return 0 6 | if not root.left and not root.right and isLeft: return root.val 7 | return f(root.left, True)+f(root.right, False) 8 | Iterative DFS C & C++ codes are also provided using an array/vector as a stack; since C++ vector has all members for the stack. C array can implement a stack. 9 | 10 | Complexity 11 | Time complexity: 12 | O(n) 13 | 14 | Space complexity: 15 | O(n) -------------------------------------------------------------------------------- /105-14th_april-Sum_of_left_leaves/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int val) 11 | { 12 | this->val = val; 13 | this->left = nullptr; 14 | this->right = nullptr; 15 | } 16 | }; 17 | 18 | #pragma GCC optimize("O3", "unroll-loops") 19 | class Solution 20 | { 21 | public: 22 | int sumOfLeftLeaves(TreeNode *root) 23 | { 24 | if (!root) 25 | return 0; 26 | int sum = 0; 27 | if (root->left && !root->left->left && !root->left->right) 28 | sum += root->left->val; 29 | sum += sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); 30 | return sum; 31 | } 32 | }; -------------------------------------------------------------------------------- /106-15th_april-Sum_root_to_leaf_numbers/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode 5 | { 6 | int val; 7 | TreeNode *left, *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution 12 | { 13 | public: 14 | int sumNumbers(TreeNode *root) 15 | { 16 | return dfs(root, 0); 17 | } 18 | 19 | int dfs(TreeNode *node, int pathSum) 20 | { 21 | if (!node) 22 | return 0; 23 | 24 | pathSum = pathSum * 10 + node->val; 25 | 26 | if (!node->left && !node->right) 27 | return pathSum; 28 | 29 | return dfs(node->left, pathSum) + dfs(node->right, pathSum); 30 | } 31 | }; -------------------------------------------------------------------------------- /107-16th_april-Add_one_row_to_tree/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | To add a new row of nodes to the binary tree at a specified depth, we can perform a depth-first search (DFS) traversal of the tree. During the traversal, we keep track of the current depth of the node being visited. When we reach the specified depth, we create new nodes with the given value and insert them as children of the current node at the specified position (either left or right). 3 | 4 | Note: We are maintaining two boolean values(left and right) so that we can know in which side we need to add the below subtrees. If depth = 1, we need to keep the tree in the left side of the tree so we are passing left as true and right as false. 5 | 6 | Complexity 7 | Time complexity: O(N) 8 | Space complexity: O(N) {Recursive call stack} 9 | N is the number of nodes in the tree. -------------------------------------------------------------------------------- /108-17th_april-Smallest_string_starting_from_leaf/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Approach is discussed in the comments given besides the code of the problem. 3 | 4 | Complexity 5 | Time complexity: 6 | O(N), 7 | where N is the number of nodes 8 | Space complexity: 9 | O(1) Memory and 10 | O(H) stack space, 11 | where H is the height of the tree -------------------------------------------------------------------------------- /109-18th_april-Island_perimeter/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int islandPerimeter(vector> &grid) 9 | { 10 | int perimeter = 0; 11 | int rows = grid.size(); 12 | int cols = grid[0].size(); 13 | 14 | for (int r = 0; r < rows; r++) 15 | { 16 | for (int c = 0; c < cols; c++) 17 | { 18 | if (grid[r][c] == 1) 19 | { 20 | perimeter += 4; 21 | if (r > 0 && grid[r - 1][c] == 1) 22 | { 23 | perimeter -= 2; 24 | } 25 | if (c > 0 && grid[r][c - 1] == 1) 26 | { 27 | perimeter -= 2; 28 | } 29 | } 30 | } 31 | } 32 | 33 | return perimeter; 34 | } 35 | }; -------------------------------------------------------------------------------- /110-19th_april-Number_of_islands/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numIslands(vector>& grid) { 8 | if (grid.empty() || grid[0].empty()) { 9 | return 0; 10 | } 11 | 12 | int numIslands = 0; 13 | for (int i = 0; i < grid.size(); i++) { 14 | for (int j = 0; j < grid[0].size(); j++) { 15 | if (grid[i][j] == '1') { 16 | numIslands++; 17 | dfs(grid, i, j); 18 | } 19 | } 20 | } 21 | 22 | return numIslands; 23 | } 24 | 25 | private: 26 | void dfs(vector>& grid, int i, int j) { 27 | if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] != '1') { 28 | return; 29 | } 30 | 31 | grid[i][j] = '0'; // mark as visited 32 | dfs(grid, i + 1, j); // down 33 | dfs(grid, i - 1, j); // up 34 | dfs(grid, i, j + 1); // right 35 | dfs(grid, i, j - 1); // left 36 | } 37 | }; -------------------------------------------------------------------------------- /114-23rd_april-Min_height_trees/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Kahn’s Algorithm for Topological Sorting is for the directed graph. 3 | But modify it one can also solve the this undirected graph problem. 4 | 5 | Approach 6 | Instead of indegree in a directed graph, count the degree for every vertex. 7 | 8 | Build the adjacency list adj & compute the deg for each vertex. 9 | Push all vertices with deg=1 to the queue q 10 | Proceed BFS while the q is not empty, removing the edge connecting v, when the adjacent vetex w has deg(w)=1, push it to q. With a care look how many vertices are left. If none, the center are found. 11 | Complexity 12 | Time complexity: 13 | O(n) 14 | 15 | Space complexity: 16 | O(n) 17 | 18 | Code degree+BFS =like topological sort Kahn's algorithm||75ms Beats 99.43% -------------------------------------------------------------------------------- /115-24th_april-Nth_fibonacci_number/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int tribonacci(int n) 9 | { 10 | std::unordered_map memo; 11 | return helper(n, memo); 12 | } 13 | 14 | private: 15 | int helper(int n, std::unordered_map &memo) 16 | { 17 | if (memo.find(n) != memo.end()) 18 | { 19 | return memo[n]; 20 | } 21 | 22 | int result; 23 | if (n == 0) 24 | { 25 | result = 0; 26 | } 27 | else if (n == 1 || n == 2) 28 | { 29 | result = 1; 30 | } 31 | else 32 | { 33 | result = helper(n - 1, memo) + helper(n - 2, memo) + helper(n - 3, memo); 34 | } 35 | 36 | memo[n] = result; 37 | return result; 38 | } 39 | }; -------------------------------------------------------------------------------- /116-25th_april-Longest_ideal_subsequence/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int longestIdealString(string s, int k) 10 | { 11 | int dp[27] = {0}; 12 | int n = s.length(); 13 | 14 | for (int i = n - 1; i >= 0; i--) 15 | { 16 | char cc = s[i]; 17 | int idx = cc - 'a'; 18 | int maxi = INT_MAX; 19 | 20 | int left = max((idx - k), 0); 21 | int right = min((idx + k), 26); 22 | 23 | for (int j = left; j <= right; j++) 24 | { 25 | maxi = max(maxi, dp[j]); 26 | } 27 | 28 | dp[idx] = maxi + 1; 29 | } 30 | 31 | int max = INT_MAX; 32 | for (int i = 0; i < 27; i++) 33 | { 34 | if (dp[i] > max) 35 | max = dp[i]; 36 | } 37 | 38 | return max; 39 | } 40 | }; -------------------------------------------------------------------------------- /118-27th_april-Freedom_trail/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Store all the indices of ring in hashmap. When both ring[i] and key[j] are equal then you require only 1 step which is ofcourse pressing the button. Otherwise when ring[i] and key[j] are different then explore all the possibilities of reaching the index 'k' such that ring[k]=key[j], and there are always 2 options for reaching a particular k, first is clockwise and second is anticlockwise. 3 | Since we require min steps so we always take the minimum of two options available. 4 | 5 | Time complexity: 6 | O(N*M) + extra for loop for traversing the vector of indices. 7 | 8 | Space complexity: 9 | O(N*M) 10 | N = size of ring, M = size of key -------------------------------------------------------------------------------- /120-29th_april-Min_number_of_operations/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | he code calculates the minimum operations needed to make each bit of the binary representation of integers in the array equal to the corresponding bit of the target 'k'. It iterates through each bit, checking if XOR operation is required for matching bits, updating the answer accordingly. 3 | 4 | Complexity 5 | Time complexity: 6 | O(32*N) 7 | Space complexity: 8 | O(1) -------------------------------------------------------------------------------- /120-29th_april-Min_number_of_operations/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minOperations(vector& v, int k) { 9 | int n=v.size(); 10 | int ans=0; 11 | for(int i=0;i<=30;i++) { 12 | int b=0; 13 | for(int j=0;j>i)&1)==1) 15 | b=b^1; 16 | } 17 | if(((k>>i)&1)!=b) 18 | ans++; 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /121-30th_april-Num_of_wonderful_substrings/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition: 2 | The problem can be tackled using a variation of prefix sum, focusing solely on the parity of character counts. We employ bitwise XOR to construct a prefix sum of the string, where each prefix sum represents a bitmask of 10 different characters 'a'-'j'. By considering the ASCII values of these characters and extracting the 4 least significant bits using a bitwise AND operation (0b1111), we obtain values ranging from 1 to 10. We then use bit shifting to adjust the position of each character in the bitmask and update it using XOR operations. 3 | 4 | Approach: 5 | We maintain an array bitmapcount[1024] to count the occurrences of each possible bitmask value, considering that there are 2^10 = 1024 possible bitmask values within the range 0 to 2048 (inclusive), with a step of 2. We iterate through all possible bitmask values and calculate their corresponding count bmcount. For each bitmask value, we modify at most one bit and accumulate the counts, excluding the count of the bitmask itself, as substrings cannot be empty. Finally, we divide the accumulated count by 2, as each substring is counted twice. -------------------------------------------------------------------------------- /122-1st_may-Reverse_prefix_of_word/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | find the first occurence of ch and reverse word from beginning to ch and return the word. 3 | 4 | Complexity 5 | Time complexity: O(n) 6 | Space complexity:O(1) -------------------------------------------------------------------------------- /122-1st_may-Reverse_prefix_of_word/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string reversePrefix(string word, char ch) { 10 | int a=word.find(ch)+1; 11 | reverse(word.begin(),word.begin()+a); 12 | return word; 13 | } 14 | }; -------------------------------------------------------------------------------- /123-2nd_may-Largest_positive_int_that_exists_with_-ve/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | 🎯Problem Explaination: 2 | You are given an array of integers. Your task is to find the largest positive integer in the array such that its negative counterpart also exists in the array. If such a pair exists, return the largest positive integer; otherwise, return -1. 3 | 4 | 📥Input: 5 | An array of integers nums. 6 | Each integer nums[i] represents an element of the array. 7 | 📤Output: 8 | An integer representing the largest positive integer satisfying the given condition. If no such integer exists, return -1. 9 | 🔍 Methods To Solve This Problem: 10 | I'll be covering two different methods to solve this problem: 11 | 12 | Sorting 13 | Two Pointers 14 | 1️⃣ Sorting: 15 | Approach🤓: 16 | Sort the array in ascending order. 17 | Iterate through the sorted array from the end. 18 | Return the first positive integer and its negative counterpart. 19 | Complexity🧑🏻‍🔬: 20 | ⏰ Time complexity: O(n log n) due to sorting. 21 | 🌌 Space Complexity: O(1) -------------------------------------------------------------------------------- /123-2nd_may-Largest_positive_int_that_exists_with_-ve/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int findMaxK(std::vector& nums) { 9 | std::sort(nums.begin(), nums.end()); 10 | int n = nums.size(); 11 | for (int i = n-1; i >= 0; i--) { 12 | if (nums[i] > 0 && std::binary_search(nums.begin(), nums.end(), -nums[i])) { 13 | return nums[i]; 14 | } 15 | } 16 | return -1; // If no such pair found 17 | } 18 | }; -------------------------------------------------------------------------------- /124-3rd_may-Compare_version_numbers/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Convert the chars to int & compare the numbers x1 & x2 3 | Use a nested loop to solve. 4 | 5 | Approach 6 | Use a nested loop with condition ix2) return 1; 16 | x1=0; 17 | x2=0; 18 | Complexity 19 | Time complexity: 20 | O(n1+n2) 21 | 22 | Space complexity: 23 | O(1) -------------------------------------------------------------------------------- /124-3rd_may-Compare_version_numbers/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | static int compareVersion(string& v1, string& v2) { 8 | const int n1=v1.size(), n2=v2.size(); 9 | int x1=0, x2=0; 10 | for(int i=0, j=0; ix2) return 1; 19 | x1=0; 20 | x2=0; 21 | } 22 | return 0; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /125-4th_may-Boats_to_save_people/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | 3 methods Greedy. At best 1 light+1 heavy can be in a boat. 3 | 1 is using sorting, then 2-pointer 4 | 2nd using counting sort to replace std::sort 5 | Later consider furthermore optimization. 6 | 7 | Since every one is <= limit. Each boat can transport at least 1, but at most 2. 8 | After sorting, use 2-pointer, in form of a loop with control variable r=people.size()-1...with the condition l<=r, for the Greedy process needs to check 9 | people[l]+people[r]<=limit 10 | if yes, the people[l] can go with people[r], so l++; otherwise this boat can carry only people[r]. 11 | 12 | Let's consider the testcase=[1,2,3,4,5,8,9] 9. 13 | The Greedy process with 2-pointer is as follows: 14 | 15 | boat 1:9, 16 | boat 2:8,1 17 | boat 3:5,2 18 | boat 4:4,3 19 | Complexity 20 | Time complexity: 21 | sort+2-pointer: O(nlogn) 22 | Counting sort+2-pointer O(n+m) 23 | Space complexity: 24 | O(sort) -------------------------------------------------------------------------------- /125-4th_may-Boats_to_save_people/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #pragma GCC optimize("O3", "unroll-loops") 7 | class Solution { 8 | public: 9 | int numRescueBoats(vector& people, int limit) { 10 | unsigned freq[30001]={0}; 11 | int maxW=0, minW=30001; 12 | for(int x: people){ 13 | freq[x]++; 14 | maxW=max(maxW, x); 15 | minW=min(minW, x); 16 | } 17 | for (int i=minW, j=0; i<=maxW; i++){ 18 | int f=freq[i]; 19 | fill(people.begin()+j, people.begin()+j+f, i); 20 | j+=f; 21 | } 22 | int x=0; 23 | for(int l=0, r=people.size()-1;l<=r; r--){ 24 | x++; 25 | if (people[l]+people[r]<=limit) 26 | l++; 27 | } 28 | return x; 29 | } 30 | }; 31 | 32 | 33 | auto init = []() { 34 | ios::sync_with_stdio(0); 35 | cin.tie(0); 36 | cout.tie(0); 37 | return 'c'; 38 | }(); -------------------------------------------------------------------------------- /126-5th_may-Delete_linkedlist_node/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | 🎯Problem Explaination: 2 | We have to delete the given node from a singly-linked list without knowing its head or previous node. Given node is not tail node, so it will always have next node. 3 | 4 | Only question is hard to understand. 5 | This is the easiest "Leetcode-Medium" I have seen so far. 6 | Why is this Medium, not Easy? 7 | 8 | 🤔 Intuition 9 | We know that previous node pointer to given node. What if we change given node value to next nodes and point next to next.next. It's essentially changing current node to next and deleting next. 10 | 11 | 🧠 Approach 12 | To delete the given node, we copy the value of the next node to the current node and adjust the next pointer to skip the next node. 13 | 14 | Copy the value of the next node to the current node. 15 | Adjust the next pointer to skip the next node. 16 | 📒 Complexity 17 | ⏰ Time complexity: O(1), as we're only modifying the current node 18 | 🧺Space complexity: O(1), no extra space is used. -------------------------------------------------------------------------------- /126-5th_may-Delete_linkedlist_node/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class ListNode 5 | { 6 | public: 7 | int val; 8 | ListNode *next; 9 | ListNode(int x) : val(x), next(NULL) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | void deleteNode(ListNode* node) { 15 | node->val = node->next->val; 16 | node->next = node->next->next; 17 | } 18 | }; -------------------------------------------------------------------------------- /127-6th_may-Remove_nodes_from_list/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class ListNode 6 | { 7 | public: 8 | int val; 9 | ListNode *next; 10 | ListNode(int val) 11 | { 12 | this->val = val; 13 | this->next = nullptr; 14 | } 15 | }; 16 | 17 | class Solution { 18 | public: 19 | ListNode* removeNodes(ListNode* head) { 20 | ListNode* cur = head; 21 | stack stack; 22 | 23 | while (cur != nullptr) { 24 | while (!stack.empty() && stack.top()->val < cur->val) { 25 | ListNode* a = stack.top(); 26 | stack.pop(); 27 | } 28 | stack.push(cur); 29 | cur = cur->next; 30 | } 31 | 32 | ListNode* nxt = nullptr; 33 | while (!stack.empty()) { 34 | cur = stack.top(); 35 | stack.pop(); 36 | cur->next = nxt; 37 | nxt = cur; 38 | } 39 | 40 | return cur; 41 | } 42 | }; -------------------------------------------------------------------------------- /129-8th_may-Relative_ranks/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector findRelativeRanks(vector& score) { 12 | vector sortedScore = score; 13 | sort(sortedScore.begin(), sortedScore.end(), greater()); 14 | vector medals = {"Gold Medal", "Silver Medal", "Bronze Medal"}; 15 | unordered_map rankMapping; 16 | for (int i = 0; i < sortedScore.size(); i++) { 17 | if (i < 3) { 18 | rankMapping[sortedScore[i]] = medals[i]; 19 | } else { 20 | rankMapping[sortedScore[i]] = to_string(i + 1); 21 | } 22 | } 23 | vector result; 24 | for (int s : score) { 25 | result.push_back(rankMapping[s]); 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /130-9th_may-Max_happiness_of_selected_children/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | long long maximumHappinessSum(vector& happiness, int k) { 10 | ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); 11 | sort(begin(happiness), end(happiness), greater()); 12 | int i = 0; 13 | long long res = 0; 14 | 15 | while(k--) { 16 | happiness[i] = max(happiness[i] - i, 0); 17 | res += happiness[i++]; 18 | } 19 | 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /133-12th_may-Largest_local_value_in_matrix/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> largestLocal(vector>& grid) { 10 | int n = grid.size(); 11 | vector> res(n - 2, vector(n - 2)); 12 | 13 | for(int i = 1; i < n - 1; ++i) { 14 | for(int j = 1; j < n - 1; ++j) { 15 | int temp = 0; 16 | 17 | for(int k = i - 1; k <= i + 1; ++k) { 18 | for(int l = j - 1; l <= j + 1; ++l) { 19 | temp = max(temp, grid[k][l]); 20 | } 21 | } 22 | 23 | res[i - 1][j - 1] = temp; 24 | } 25 | } 26 | 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /134-13th_may-Score_after_flipping_matrix/code.cpp: -------------------------------------------------------------------------------- 1 | #pragma GCC optimize ("Ofast") 2 | #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx") 3 | #pragma GCC optimize ("-ffloat-store") 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int matrixScore(vector>& grid) { 12 | ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); 13 | int n = grid.size(), m = grid[0].size(); 14 | int res = (1 << (m - 1)) * n; 15 | 16 | for(int j = 1; j < m; ++j) { 17 | int val = 1 << (m - 1 - j); 18 | int set = 0; 19 | 20 | for(int i = 0; i < n; ++i) { 21 | if(grid[i][j] == grid[i][0]) { 22 | set++; 23 | } 24 | } 25 | 26 | res += max(set, n - set) * val; 27 | } 28 | 29 | return res; 30 | } 31 | }; -------------------------------------------------------------------------------- /137-16th_may-Evaluate_boolean_binary_tree/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | bool helper(TreeNode *root) 19 | { 20 | if (root->val == 0 || root->val == 1) 21 | { 22 | return root->val == 1; 23 | } 24 | else if (root->val == 2) 25 | { 26 | return helper(root->left) || helper(root->right); 27 | } 28 | else if (root->val == 3) 29 | { 30 | return helper(root->left) && helper(root->right); 31 | } 32 | 33 | return false; 34 | } 35 | 36 | bool evaluateTree(TreeNode *root) 37 | { 38 | return helper(root); 39 | } 40 | }; -------------------------------------------------------------------------------- /138-17th_may-Delete_leaves_with_given_value/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Search for the required element and return NULL if you find the required leaf node. 3 | 4 | Approach 5 | Call for left element and store it. 6 | Recursively call for right element and store it. 7 | If left and right are NULL and the current element is equal to target element so it means we have found the element to remove, so simply return NULL. Now we have NULL as our left element. 8 | Now assign the value of left and right to root->left and root->right. 9 | Now, since we have to return the root element so return it. 10 | Complexity 11 | Time complexity: O(n) 12 | Space complexity:O(log n) 13 | (Because of recursive call) -------------------------------------------------------------------------------- /138-17th_may-Delete_leaves_with_given_value/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | TreeNode *removeLeafNodes(TreeNode *root, int target) 19 | { 20 | if (root == NULL) 21 | return NULL; 22 | TreeNode *left = removeLeafNodes(root->left, target); 23 | TreeNode *right = removeLeafNodes(root->right, target); 24 | if (left == NULL && right == NULL && root->val == target) 25 | return NULL; 26 | root->left = left; 27 | root->right = right; 28 | return root; 29 | } 30 | }; -------------------------------------------------------------------------------- /139-18th_may-Distribute_coins_in_BT/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Use DFS (post-order) to distribute coins. 3 | 4 | The coding is easy, but thinking is not. 5 | 6 | Later try other approaches; an iterative post-order version is made. 7 | 8 | Approach 9 | 10 | The idea is that the child give x=(y-1) coins to parent, if he has y coins. (if y=0=> x=-1 then parent should give the child 1 coin) 11 | Add an extra parameter TreeNode* parent= NULL instead of a helper function. 12 | The number of moves comes from its left & right subtrees & 13 | When x>0 is to give, when x<0 is to obtain. So moves+=abs(x) 14 | Why not Pre-Order? Why Post-order? 15 | As the root of a subtree, it's unkown how many decendants it has before performing any kind of transversal. The thinking of parent-gives-coins-to-children will not work. 16 | 17 | Use post-order transverals, because every node has a parent except for the root. It works that children give coins to parents. 18 | 19 | Complexity 20 | Time complexity: 21 | O(n) 22 | 23 | Space complexity: 24 | O(n) -------------------------------------------------------------------------------- /139-18th_may-Distribute_coins_in_BT/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class TreeNode 5 | { 6 | public: 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | }; 14 | 15 | class Solution { 16 | public: 17 | static int distributeCoins(TreeNode* root, TreeNode* parent= NULL) { 18 | if (!root) return 0; 19 | int moves=distributeCoins(root->left, root)+distributeCoins(root->right, root); 20 | int x=root->val-1;// give x coins to parent node 21 | if (parent) parent->val += x; // now parent's coins 22 | moves+=abs(x); 23 | return moves; 24 | } 25 | }; 26 | 27 | auto init = []() { 28 | ios::sync_with_stdio(0); 29 | cin.tie(0); 30 | cout.tie(0); 31 | return 'c'; 32 | }(); -------------------------------------------------------------------------------- /140-19th_may-Find_max_sum_of_node_values/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Question is hard. Use DP to solve. edges is ignored! 3 | DP recurion+memo->tabular->optimized space 4 | 5 | Approach 6 | Let 0 be the root. 7 | Let f(i, c)=dp[i][c] denote the max sum from the root to i where c is the number (modulo 2) of XORing operations applied. 8 | 9 | The hardest part is to find the recursive relation between vertices i & i+1. Since LC says that this undirected graph is a tree, there exists always an path between i & i+1. An operation is applied, then 2 operations for XORing with k are done. 10 | 11 | # Let x=nums[i], consider not taking x^k , taking x^k 12 | f(i, c)= max(x+f(i+1, c),(x^k)+f(i+1,1-c)) 13 | Xoring is performing in pair, for base case, let n=len(nums), 14 | 15 | if i==n: 16 | # invalid path, any negative integer with large enough absolute value 17 | if c==1: return -(1<<31) 18 | return 0 # base case 19 | Complexity 20 | Time complexity: 21 | O(n) 22 | 23 | Space complexity: 24 | O(n)→O(1) -------------------------------------------------------------------------------- /140-19th_may-Find_max_sum_of_node_values/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int n, k; 10 | long long dp[20000][2]; 11 | long long f(int i, bool c, vector& nums ){ 12 | if (i==n) return (c)?INT_MIN:0; 13 | if (dp[i][c]!=-1) return dp[i][c]; 14 | long long x=nums[i]; 15 | return dp[i][c]=max(x+f(i+1,c, nums), (x^k)+f(i+1,!c, nums)); 16 | } 17 | 18 | long long maximumValueSum(vector& nums, int k, vector>& edges) { 19 | n=nums.size(); 20 | this->k=k; 21 | fill(&dp[0][0], &dp[0][0]+20000*2, -1); 22 | return f(0, 0, nums); 23 | } 24 | }; -------------------------------------------------------------------------------- /141-20th_may-Sum_of_all_subset_XOR_trials/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int subsetXORSum(vector& nums) { 8 | return helper(nums, 0, 0); 9 | } 10 | 11 | private: 12 | int helper(vector& nums, int index, int currValue) { 13 | if (index == nums.size()) return currValue; 14 | return helper(nums, index + 1, currValue ^ nums[index]) + helper(nums, index + 1, currValue); 15 | } 16 | }; -------------------------------------------------------------------------------- /142-21st_may-Subsets/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector> subsets(vector& nums) { 8 | vector> result; 9 | vector path; 10 | backtrack(nums, 0, path, result); 11 | return result; 12 | } 13 | 14 | void backtrack(vector& nums, int start, vector& path, vector>& result) { 15 | result.push_back(path); 16 | for (int i = start; i < nums.size(); i++) { 17 | path.push_back(nums[i]); 18 | backtrack(nums, i + 1, path, result); 19 | path.pop_back(); 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /143-22nd_may-Palindrome_partitioning/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Simply generate all the substrings using recursion and check if they are palindrome or not.If not Backtrack form there.Recursively traverse over the string like in dfs. 3 | 4 | Approach 5 | The idea is to keep track of the last partition index and to iterate from that index to the end of the array to check whether we can form a palindrome substring or not. If we are able to find such a substring we use recursion to continue exploring . If we reach the end whole string it means we were able to partition the string into x number of palindromes. Save the result and backtrack to continue exploring. 6 | 7 | Complexity 8 | Time complexity:(O(n∗2n) 9 | Space complexity:O(n) -------------------------------------------------------------------------------- /143-22nd_may-Palindrome_partitioning/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector>ans; 8 | bool isPalindrome(string& s,int i,int j){ 9 | 10 | while(i&temp){ 18 | if(s.size()==start){ 19 | ans.push_back(temp); 20 | return; 21 | } 22 | 23 | for(int i=start;i> partition(string s) { 33 | vectortemp; 34 | generate(s,0,temp); 35 | 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /144-23rd_may-Number_of_beautiful_subsets/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | In previous approaches, we were calculating in reverse direction (right to left) of sss. Due to this, we needed to convert sorted map to array first. It can be avoided if we traverse left to right. 2 | 3 | Time Complexity: O(nlogn) 4 | Space Complexity: O(n+k) 5 | -------------------------------------------------------------------------------- /144-23rd_may-Number_of_beautiful_subsets/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int beautifulSubsets(vector& nums, int k) { 9 | int result = 1; 10 | map> freq; 11 | for (int& x: nums) { 12 | freq[x % k][x]++; 13 | } 14 | for (auto& fr: freq) { 15 | int prevNum = -k, prev2, prev1 = 1, curr; 16 | for (auto& [num, f]: fr.second) { 17 | int skip = prev1; 18 | int take = ((1 << f) - 1) * (num - prevNum == k ? prev2 : prev1); 19 | curr = skip + take; 20 | prev2 = prev1; prev1 = curr; 21 | prevNum = num; 22 | } 23 | result *= curr; 24 | } 25 | return result - 1; 26 | } 27 | }; -------------------------------------------------------------------------------- /145-24th_may-Max_score_words_formed_by_letter/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxScoreWords(vector& w, vector& l, vector& s) { 8 | vector cnt(26, 0); 9 | for (char c : l) cnt[c - 'a']++; 10 | return dfs(w, s, cnt, 0); 11 | } 12 | 13 | private: 14 | int dfs(vector& w, vector& s, vector& cnt, int i) { 15 | if (i == w.size()) return 0; 16 | int skip = dfs(w, s, cnt, i + 1), score = 0; 17 | bool valid = true; 18 | for (char c : w[i]) { 19 | if (--cnt[c - 'a'] < 0) valid = false; 20 | score += s[c - 'a']; 21 | } 22 | int take = valid ? score + dfs(w, s, cnt, i + 1) : 0; 23 | for (char c : w[i]) cnt[c - 'a']++; 24 | return max(skip, take); 25 | } 26 | }; -------------------------------------------------------------------------------- /146-25th_may-Word_break-II/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | This problem is similar to rod cutting problem in which we have to make optimal cuts but in this we will be finding all the possible ways of cuts. 3 | 4 | Approach 5 | Step 1: Convert the given dictionary list into unordered_map so that we can optimally check whether the word exist in the dictionary or not. 6 | 7 | Step 2: Cut words from the given string and check whether it exist in the map or not. 8 | If it exist then call the solve function for remaining string 9 | else continue because if a word does not exist in the 10 | dictionary then its of no use. 11 | 12 | Step 3: Keep track of the current sentence by pushing and popping word from it. 13 | 14 | Step 4: If we reach at the end of givenString then we got 1 of our possible answers add it to the list of answers. 15 | 16 | Step 5: Return the answers. -------------------------------------------------------------------------------- /147-26th_may-Student_attendance_record-II/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Use DP to solve! 3D DP question. 3 | 4 | Approach 5 | For a fast code implementation, C-array is in use. 6 | 7 | recursion+ memo , top-down design 8 | Convert it into iteration, bottom-up design 9 | Use &1 trick to reduce the space & obtain a fast code 10 | Complexity 11 | Time complexity: 12 | O(6n) 13 | 14 | Space complexity: 15 | O(105)→O(6) -------------------------------------------------------------------------------- /147-26th_may-Student_attendance_record-II/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | const long long mod=1e9+7; 9 | long long dp[100001][2][3]; 10 | long long f(int i, int absent, int late){ 11 | if (absent>=2 || late>=3) return 0; 12 | if (i==0) return 1; 13 | if (dp[i][absent][late]!=-1) return dp[i][absent][late]; 14 | 15 | long long ans=f(i-1, absent, 0);// P 16 | ans+=(late<2?f(i-1, absent, late+1):0);// L 17 | ans+=(absent==0?f(i-1, absent+1, 0):0);// A 18 | 19 | return dp[i][absent][late]=ans%mod; 20 | } 21 | int checkRecord(int n) { 22 | fill(&dp[0][0][0], &dp[0][0][0]+(n+1)*6, -1); 23 | return f(n, 0, 0); 24 | } 25 | }; -------------------------------------------------------------------------------- /148-27th_may-Special_array_with_X_elements/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int specialArray(vector& nums) { 4 | int n = nums.size(), l = 0, r = n; 5 | sort(nums.begin(), nums.end()); 6 | while (l <= r){ 7 | int mid = (l + r) / 2; 8 | int size = lower_bound(nums.begin(), nums.end(), mid) - nums.begin(); 9 | int count = n - size; 10 | if (count == mid) 11 | return mid; 12 | else if (count > mid) 13 | l = mid + 1; 14 | else 15 | r = mid - 1; 16 | } 17 | return -1; 18 | } 19 | }; -------------------------------------------------------------------------------- /148-27th_may-Special_array_with_X_elements/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int specialArray(vector& nums) { 9 | int n = nums.size(), l = 0, r = n; 10 | sort(nums.begin(), nums.end()); 11 | while (l <= r){ 12 | int mid = (l + r) / 2; 13 | int size = lower_bound(nums.begin(), nums.end(), mid) - nums.begin(); 14 | int count = n - size; 15 | if (count == mid) 16 | return mid; 17 | else if (count > mid) 18 | l = mid + 1; 19 | else 20 | r = mid - 1; 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /149-28th_may-Equal_substrings_within_budget/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int equalSubstring(string s, string t, int maxCost) { 10 | int n = s.size(); 11 | int start = 0; 12 | int current_cost = 0; 13 | int max_length = 0; 14 | 15 | for (int end = 0; end < n; ++end) { 16 | current_cost += abs(s[end] - t[end]); 17 | 18 | while (current_cost > maxCost) { 19 | current_cost -= abs(s[start] - t[start]); 20 | ++start; 21 | } 22 | 23 | max_length = max(max_length, end - start + 1); 24 | } 25 | 26 | return max_length; 27 | } 28 | }; -------------------------------------------------------------------------------- /150-29th_may-Num_of_steps_to_reduce_num_in_binary_rep/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Initialize Variables: 3 | 4 | n: The length of the binary string. 5 | ans: The number of steps required, initialized to n - 1 (since each bit contributes at least one step). 6 | carry: To handle the carry during the addition operation, initialized to 0. 7 | Iterate through the Binary String from Right to Left: 8 | 9 | For each bit in the string (from the least significant bit to the second most significant bit), check if the bit plus the current carry is 1. 10 | If it is 1, it means we have an odd number, and we need to add 1, which introduces a carry for the next bit. Increment the ans by 1 and set carry to 1. 11 | If it is 0, continue to the next bit. 12 | Return the Result: 13 | 14 | After the loop, return ans + carry to account for any remaining carry. 15 | Cases 16 | Even Case: 17 | If bit + carry == 0, the number is even. We divide by 2, no additional steps needed. 18 | Odd Case: 19 | If bit + carry == 1, the number is odd. We add 1 to make it even, increment steps, and set carry for the next bit. -------------------------------------------------------------------------------- /150-29th_may-Num_of_steps_to_reduce_num_in_binary_rep/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int numSteps(string s) { 9 | int n = s.length(); 10 | int ans = n - 1, carry = 0; 11 | 12 | for (int i = n - 1; i > 0; i--) { 13 | if (s[i] - '0' + carry == 1) { 14 | ans++; 15 | carry = 1; 16 | } 17 | } 18 | 19 | return ans + carry; 20 | } 21 | }; -------------------------------------------------------------------------------- /151-30th_may-Count_triplets_that_can_form_two_arrays/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int countTriplets(std::vector& arr) { 8 | int n = arr.size(); 9 | std::vector prefix(n + 1, 0); 10 | 11 | for (int i = 0; i < n; ++i) { 12 | prefix[i + 1] = prefix[i] ^ arr[i]; 13 | } 14 | 15 | int count = 0; 16 | for (int i = 0; i < n; ++i) { 17 | for (int k = i + 1; k < n; ++k) { 18 | if (prefix[i] == prefix[k + 1]) { 19 | count += (k - i); 20 | } 21 | } 22 | } 23 | 24 | return count; 25 | } 26 | }; -------------------------------------------------------------------------------- /152-31st_may-Single_number-III/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class Solution 12 | { 13 | public: 14 | static vector singleNumber(vector &nums) 15 | { 16 | int XOR = accumulate(nums.begin(), nums.end(), 0, bit_xor<>()); 17 | // XOR=a^b 18 | 19 | // Find least bit=1 for XOR 20 | // same as 21 | // int i=__builtin_ffs(XOR)-1; 22 | int i = 0; 23 | while (((XOR >> i) & 1) == 0) 24 | i++; 25 | // i-th bit=1 26 | 27 | int A = 0, B = 0; 28 | for (int x : nums) 29 | { 30 | if (((x >> i) & 1) == 0) 31 | A ^= x; 32 | else 33 | B ^= x; 34 | } 35 | // A^=XOR, B^=XOR; 36 | return {A, B}; 37 | } 38 | }; 39 | 40 | auto init = []() 41 | { 42 | ios::sync_with_stdio(0); 43 | cin.tie(0); 44 | cout.tie(0); 45 | return 'c'; 46 | }(); -------------------------------------------------------------------------------- /153-1st_June-Score_of_a_string/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int scoreOfString(string s) { 7 | int score = 0; 8 | for (size_t i = 0; i < s.length() - 1; i++) { 9 | score += abs(s[i] - s[i + 1]); 10 | } 11 | return score; 12 | } 13 | }; -------------------------------------------------------------------------------- /154-2nd_June-Reverse_string/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | using two pointer 3 | 4 | Complexity 5 | Time complexity:O(n) 6 | Space complexity: 7 | 0(1) -------------------------------------------------------------------------------- /154-2nd_June-Reverse_string/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void reverseString(vector& str) { 7 | int s2=0; 8 | int e=str.size()-1; 9 | while(s2 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector commonChars(vector& words) { 9 | vector min_freq(26, INT_MAX); 10 | for (auto& word : words) { 11 | vector freq(26, 0); 12 | for (char c : word) { 13 | freq[c - 'a']++; 14 | } 15 | for (int i = 0; i < 26; ++i) { 16 | min_freq[i] = min(min_freq[i], freq[i]); 17 | } 18 | } 19 | 20 | vector result; 21 | for (int i = 0; i < 26; ++i) { 22 | while (min_freq[i]-- > 0) { 23 | result.push_back(string(1, i + 'a')); 24 | } 25 | } 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /158-6th_June-Hand_of_straights/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool isNStraightHand(vector& hand, int groupSize) { 8 | int n=hand.size(); 9 | if(nm; 11 | for(auto i:hand)m[i]++; 12 | sort(hand.begin(),hand.end()); 13 | for(auto i:hand){ 14 | if(m[i]==0)continue; 15 | bool flag=1; 16 | for(int k=0;k 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string replaceWords(vector& dictionary, string sentence) { 10 | unordered_set rootSet(dictionary.begin(), dictionary.end()); 11 | 12 | istringstream iss(sentence); 13 | string word; 14 | string result; 15 | 16 | while (iss >> word) { 17 | string prefix; 18 | for (int i = 1; i <= word.size(); ++i) { 19 | prefix = word.substr(0, i); 20 | if (rootSet.find(prefix) != rootSet.end()) { 21 | break; 22 | } 23 | } 24 | result += prefix + " "; 25 | } 26 | 27 | if (!result.empty()) { 28 | result.pop_back(); 29 | } 30 | 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /161-9th_June-Subaaray_sums_divisible_by_K/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int subarraysDivByK(vector& nums, int k) { 12 | unordered_map prefix_map = {{0, 1}}; 13 | int sum = 0, ans = 0; 14 | for(int i = 0; i < nums.size(); i++) { 15 | sum = (sum + nums[i]) % k; 16 | if(sum < 0) sum += k; 17 | if(prefix_map.find(sum) != prefix_map.end()) { 18 | ans += prefix_map[sum]; 19 | prefix_map[sum]++; 20 | } else { 21 | prefix_map[sum] = 1; 22 | } 23 | } 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /162-10th_June-Height_checker/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | For the constraints, char (int8_t) is sufficient. 2 | Use std::sort 3 | Use Counting sort 4 | Python 1-liner 5 | A variant for Counting sort which uses counting sort & reuse the array heights to hold the difference of original & sorted ones; then use |heights|-count(heights, 0) to give the answer. Both C++ & python codes are made. 6 | Other counting sort's variant without using function count. 7 | The last one solution is intended to not use other containers( counting sort is of course impossible), just reuse the array heights. In short, use bitwise operations to pack heights[i] & i into int; then sort. Finally, the sorted data is decompressed to count the distinct values. 8 | 9 | Complexity 10 | Time complexity: 11 | sort:O(nlogn) 12 | counting sort: O(n+M)O(n+M)O(n+M) where M=max(heights) 13 | 14 | Space complexity: 15 | O(∣sort∣+n)→extra:O(1) -------------------------------------------------------------------------------- /162-10th_June-Height_checker/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | class Solution { 9 | public: 10 | int heightChecker(vector& heights) { 11 | vector sorted(heights.begin(), heights.end()); 12 | sort(heights.begin(), heights.end()); 13 | int n=heights.size(), ans=0; 14 | for(int i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | vector relativeSortArray(vector &arr1, vector &arr2) 10 | { 11 | int n1 = arr1.size(), n2 = arr2.size(); 12 | int a2i[1001]; 13 | 14 | // Initialize a2i with n2 (indicating elements not in arr2) 15 | fill(a2i, end(a2i), n2); 16 | for (int i = 0; i < n2; i++) 17 | a2i[arr2[i]] = i; // a2i is an array & the map: x=arr2[i]->i 18 | 19 | sort(arr1.begin(), arr1.end(), [&](int x, int y) 20 | { 21 | // ordered by {a2i[x], x} 22 | if (a2i[x]==a2i[y]) 23 | return x < y; 24 | return a2i[x] 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | void sortColors(vector& nums) { 9 | int freq[3]={0}; 10 | for(int x: nums) 11 | freq[x]++; 12 | int n=nums.size(), count=0; 13 | for(int x=0; x<3; x++){ 14 | fill(nums.begin()+count, nums.begin()+count+freq[x], x); 15 | count+=freq[x]; 16 | } 17 | 18 | } 19 | }; -------------------------------------------------------------------------------- /165-13th_June-Move_to_seat_everyone/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minMovesToSeat(vector& seats, vector& students) { 9 | sort(seats.begin(), seats.end()); 10 | sort(students.begin(), students.end()); 11 | int moves = 0; 12 | for( int i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minIncrementForUnique(vector& nums) { 9 | sort(nums.begin(),nums.end()); 10 | int ans = 0; 11 | for(int i=1;i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int minPatches(vector& nums, int n) { 10 | long long miss = 1; 11 | int result = 0; 12 | size_t i = 0; 13 | 14 | while (miss <= n) { 15 | if (i < nums.size() && nums[i] <= miss) { 16 | miss += nums[i]; 17 | i++; 18 | } else { 19 | miss += miss; 20 | result++; 21 | } 22 | } 23 | 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /169-17th_June-Sum_of_square_nums/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool judgeSquareSum(int c) { 8 | for (int divisor = 2; divisor * divisor <= c; divisor++) { 9 | if (c % divisor == 0) { 10 | int exponentCount = 0; 11 | while (c % divisor == 0) { 12 | exponentCount++; 13 | c /= divisor; 14 | } 15 | if (divisor % 4 == 3 && exponentCount % 2 != 0) { 16 | return false; 17 | } 18 | } 19 | } 20 | return c % 4 != 3; 21 | } 22 | }; -------------------------------------------------------------------------------- /170-18th_June-Assigning_work/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { 7 | int maxDifficulty = *max_element(difficulty.begin(), difficulty.end()); 8 | vector maxProfitUpToDifficulty(maxDifficulty + 1, 0); 9 | 10 | for (int i = 0; i < difficulty.size(); ++i) { 11 | maxProfitUpToDifficulty[difficulty[i]] = max(maxProfitUpToDifficulty[difficulty[i]], profit[i]); 12 | } 13 | 14 | for (int i = 1; i <= maxDifficulty; ++i) { 15 | maxProfitUpToDifficulty[i] = max(maxProfitUpToDifficulty[i], maxProfitUpToDifficulty[i - 1]); 16 | } 17 | 18 | int totalProfit = 0; 19 | for (int ability : worker) { 20 | if (ability > maxDifficulty) { 21 | totalProfit += maxProfitUpToDifficulty[maxDifficulty]; 22 | } else { 23 | totalProfit += maxProfitUpToDifficulty[ability]; 24 | } 25 | } 26 | 27 | return totalProfit; 28 | } 29 | }; -------------------------------------------------------------------------------- /172-20th_June-Magnetic_force_between_balls/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The problem is to find the maximum distance between two points in a list of points such that there are at least m points between them. This problem can be solved by using binary search to find the maximum distance. 3 | 4 | Approach 5 | Binary Search: The idea is to use binary search to find the maximum distance. The binary search is performed on the range from 1 to the maximum distance between any two points in the list. For each mid value, check if there are at least m points between two points with a distance of mid. If there are, then update the lower bound of the search range. If not, then update the upper bound of the search range. 6 | 7 | Function fn: The function fn checks if there are at least m points between two points with a distance of mid. It iterates over the list of points, counting the number of points that are at least mid apart from the previous point. If this count is at least m, it returns True; otherwise, it returns False. 8 | 9 | Complexity 10 | Time complexity: O(n log n) 11 | Space complexity: O(1) -------------------------------------------------------------------------------- /172-20th_June-Magnetic_force_between_balls/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool fn(std::vector& arr, int m, int mid) { 9 | int cnt = 1, prev = arr[0]; 10 | for(int i = 1; i < arr.size(); i++) { 11 | if(arr[i] - prev >= mid) { 12 | cnt++; 13 | prev = arr[i]; 14 | } 15 | } 16 | return cnt >= m; 17 | } 18 | 19 | int maxDistance(std::vector& p, int m) { 20 | std::sort(p.begin(), p.end()); 21 | int lo = 1, hi = p.back() - p.front(); 22 | while(hi - lo > 1) { 23 | int mid = (lo + hi) / 2; 24 | if(fn(p, m, mid)) lo = mid; 25 | else hi = mid - 1; 26 | } 27 | if(fn(p, m, hi)) return hi; 28 | return lo; 29 | } 30 | }; -------------------------------------------------------------------------------- /174-22nd_June-Count_num_of_nice_subarrays/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numberOfSubarrays(vector& nums, int k) { 8 | int n = nums.size(); 9 | vector cnt(n + 1, 0); 10 | cnt[0] = 1; 11 | int ans = 0, t = 0; 12 | for (int v : nums) { 13 | t += v & 1; 14 | if (t - k >= 0) { 15 | ans += cnt[t - k]; 16 | } 17 | cnt[t]++; 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /176-24th_June-Min_num_of_K_consecutive_bit_slips/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | There is only one way to filp A[0], 3 | and A[0] will tell us if we need to filp the range A[0] ~ A[K -1]. 4 | So we start from the leftmost one by one using a greedy idea to solve this problem. 5 | 6 | Approach 7 | Create a new array isFlipped[n]. 8 | isFlipped[i] = 1 iff we flip K consecutive bits starting at A[i]. 9 | 10 | We maintain a variable flipped and flipped = 1 iff the current bit is flipped. 11 | 12 | If flipped = 0 and A[i] = 0, we need to flip at A[i]. 13 | If flipped = 1 and A[i] = 1, we need to flip at A[i]. -------------------------------------------------------------------------------- /176-24th_June-Min_num_of_K_consecutive_bit_slips/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int minKBitFlips(std::vector& A, int K) { 9 | int n = A.size(), flipped = 0, res = 0; 10 | std::vector isFlipped(n, 0); 11 | 12 | for (int i = 0; i < n; ++i) { 13 | if (i >= K) 14 | flipped ^= isFlipped[i - K]; 15 | if (flipped == A[i]) { 16 | if (i + K > n) 17 | return -1; 18 | isFlipped[i] = 1; 19 | flipped ^= 1; 20 | res++; 21 | } 22 | } 23 | 24 | return res; 25 | } 26 | }; -------------------------------------------------------------------------------- /178-26th_June-Balance_BST/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Travel the original BST in the inorder to get the nodes in the sorted order 3 | Use Divide and Conquer to build the balanced BST 4 | Complexity 5 | Time complexity: O(n) 6 | Space complexity: O(n) -------------------------------------------------------------------------------- /179-27th_June-Center_of_star_graph/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The intuition behind this solution is that in a star graph, all the edges are connected to a single central node. Therefore, if we look at the first two edges, the central node will be present in both of them. We can use this property to find the center of the star graph. 3 | 4 | Approach 5 | The approach used in the given code is to check if the first element of the first edge is present in the second edge. If it is, then the first element of the first edge is the center of the star graph. If not, then the second element of the first edge is the center of the star graph. 6 | 7 | Complexity 8 | Time complexity:O(1) 9 | Space complexity:O(1) -------------------------------------------------------------------------------- /179-27th_June-Center_of_star_graph/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int findCenter(vector>& e) { 9 | return e[0][0] == e[1][0] || e[0][0] == e[1][1] ? e[0][0] : e[0][1]; 10 | } 11 | }; -------------------------------------------------------------------------------- /180-28th_June-Max_imp_of_roads/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | sort vector> and assign values 3 | 4 | Approach 5 | Create graph i.e. vector which has an hash table for each node to keep its children 6 | make a vector> 7 | fill up and sort this vector 8 | Now value of each node is = i+1 of its position in this sorted vector 9 | Create a Hashmap for quick value finding of each node 10 | Traverse given roads vector and add up values of each road given 11 | Complexity 12 | Time complexity: 13 | let road.size()=m 14 | TC : O(2m+2n+nlogn) 15 | Space complexity: O(n^2+n+n) -------------------------------------------------------------------------------- /180-28th_June-Max_imp_of_roads/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | 11 | long long maximumImportance(int n, vector>& roads) { 12 | vector> graph(n); 13 | for(int i=0;i> imp(n); 23 | 24 | for(int i=0;i mp; 30 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector> getAncestors(int n, vector>& edges) { 9 | vector> ans(n), directChild(n); 10 | for (auto& e : edges) { 11 | directChild[e[0]].push_back(e[1]); 12 | } 13 | for (int i = 0; i < n; i++) { 14 | dfs(i, i, ans, directChild); 15 | } 16 | return ans; 17 | } 18 | 19 | private: 20 | void dfs(int x, int curr, vector>& ans, vector>& directChild) { 21 | for (int ch : directChild[curr]) { 22 | if (ans[ch].empty() || ans[ch].back() != x) { 23 | ans[ch].push_back(x); 24 | dfs(x, ch, ans, directChild); 25 | } 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /183-1st_July-Three_consecutive_odds/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach 2 | Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. 3 | 4 | Use len to count the the length for consecutive odd numbers 5 | If x in nums is even reset len=0, otherwise len++ 6 | if len==3 return true 7 | When the loop is through, there are no three consecutive odds, return false 8 | 2nd C++ uses std::find_if with lambda which return the index if the first odd from index=i on is found in arr 9 | i=find_if(arr.begin()+i, arr.end(), 10 | [](int x){return (x&1);})-arr.begin(); 11 | Complexity 12 | Time complexity: 13 | O(n) 14 | 15 | Space complexity: 16 | O(1) -------------------------------------------------------------------------------- /183-1st_July-Three_consecutive_odds/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | static bool threeConsecutiveOdds(vector &arr) 9 | { 10 | int len = 0; 11 | for (int x : arr) 12 | { 13 | len = (x & 1) ? len + 1 : 0; 14 | if (len == 3) 15 | return 1; 16 | } 17 | return 0; 18 | } 19 | }; 20 | 21 | auto init = []() 22 | { 23 | ios::sync_with_stdio(0); 24 | cin.tie(0); 25 | cout.tie(0); 26 | return 'c'; 27 | }(); -------------------------------------------------------------------------------- /184-2nd_July-Intersection_of_arrays-II/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | We have to check whether the current element in the current array is also present in the other array that has been given to us, What data structure can we use here? 3 | 4 | Approach 5 | We simply store one array in a map with all its frequencies, and while iterating the other given array if we encounter the current element of the current array in the map with suitable frequency we will add that element to our answer vector. Also remember that we have to delete any element that has 0 frequncy to avoid adding extra elements to our answer vector. 6 | 7 | Complexity 8 | Time complexity: 9 | O(n+m) Iterating over the vectors and finding the element in tree map. 10 | 11 | Space complexity: 12 | O(n) An answer vector to return and a map to store elements. -------------------------------------------------------------------------------- /185-3rd_July-Min_diff_bw_values/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The key insights behind this intution is: 3 | 4 | If the array has less than 5 elements, the minimum difference will be 0, as we can't form two groups of 4 elements. 5 | Sorting the array in ascending order allows us to easily identify the 4 smallest and 4 largest elements. 6 | By calculating the difference between the sum of the 4 largest elements and the sum of the 4 smallest elements, we can find the minimum difference. 7 | Approach 8 | The approach used in the provided code is to find the minimum difference between the sum of the largest 4 elements and the sum of the smallest 4 elements in the given array A. 9 | The intuition behind this approach is that the minimum difference will be achieved by either: 10 | 11 | Removing the 4 smallest elements and keeping the 4 largest elements. 12 | Removing the 4 largest elements and keeping the 4 smallest elements. 13 | Complexity 14 | Time complexity:O(n log n) 15 | Space complexity:O(1) -------------------------------------------------------------------------------- /185-3rd_July-Min_diff_bw_values/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int minDifference(vector &A) 10 | { 11 | int n = A.size(); 12 | if (n < 5) 13 | return 0; 14 | sort(A.begin(), A.end()); 15 | return min({A[n - 1] - A[3], A[n - 2] - A[2], A[n - 3] - A[1], A[n - 4] - A[0]}); 16 | } 17 | }; -------------------------------------------------------------------------------- /186-4th_July-Merge_nodes_in_bw_zeroes/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct ListNode 7 | { 8 | int val; 9 | ListNode *next; 10 | ListNode() : val(0), next(nullptr){} 11 | ListNode(int x) : val(x), next(nullptr){} 12 | ListNode(int x, ListNode *next) : val(x), next(next){} 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | ListNode *mergeNodes(ListNode *head) 19 | { 20 | ListNode *temp = head->next; 21 | ListNode *ans = new ListNode(-1); 22 | ListNode *tempAns = ans; 23 | int c = 0; 24 | while (temp) 25 | { 26 | if (temp and temp->val != 0) 27 | { 28 | c += temp->val; 29 | } 30 | else if (temp and temp->val == 0) 31 | { 32 | ListNode *t = new ListNode(c); 33 | tempAns->next = t; 34 | tempAns = tempAns->next; 35 | c = 0; 36 | } 37 | temp = temp->next; 38 | } 39 | return ans->next; 40 | } 41 | }; -------------------------------------------------------------------------------- /187-5th_July-Find_min_max_num_of_nodes/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | The task is to find critical points in a linked list and calculate the minimum and maximum distances between these points. Critical points are nodes that are either local maxima or local minima. A node is a local maxima if its value is greater than both its previous and next nodes. Similarly, a node is a local minima if its value is less than both its previous and next nodes. 3 | 4 | Approach 5 | Identify Critical Points: Traverse the linked list and identify nodes that are either local maxima or local minima by comparing each node's value with its previous and next nodes. Store the indices of these critical points. 6 | Calculate Distances: 7 | If there are fewer than two critical points, return [-1, -1]. 8 | Otherwise, calculate the minimum distance between any two consecutive critical points and the maximum distance between the first and last critical points in the list. 9 | Complexity 10 | Time complexity:O(n) 11 | Space complexity:O(1) -------------------------------------------------------------------------------- /188-6th_July-Pass_the_pillow/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | similiar to solve 3178. Find the Child Who Has the Ball After K Seconds 3 | 4 | Approach 5 | Modular arithmetic with period N=2*(n-1) 6 | 7 | Modular arithmetic x=time%N 8 | The answer is 1+((x=n, x=time mod N one has to do N-x. Don't forget plus 1. 15 | 16 | Complexity 17 | Time complexity: 18 | O(1) 19 | 20 | Space complexity: 21 | O(1) -------------------------------------------------------------------------------- /188-6th_July-Pass_the_pillow/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int passThePillow(int n, int time) 5 | { 6 | int N = 2 * n - 2, x = time % N; 7 | return 1 + ((x < n) ? x : N - x); 8 | } 9 | }; -------------------------------------------------------------------------------- /189-7th_July-Water_bottles/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | We have to maximimse the bottles that we drink here so we clearly have to also maximise the empty bottles in every turn. 3 | 4 | Approach 5 | To maximise the empty bottles in every turn we simply just have to drink in multiples of numExchange as much as we can and then we get the refills, We will continue this till we run out of sufficient bottles that can get us another refill, in the last we will add the remaining bottles that we did not drink in order to maximise our answer 6 | 7 | Complexity 8 | Time complexity: 9 | O(n) We have to simulate our answer for different numbottles 10 | Is there a way to solve this in O(1) somehow? Let me knwo if there is! 11 | 12 | Space complexity: 13 | O(1) We dont need any extra space for our solution -------------------------------------------------------------------------------- /189-7th_July-Water_bottles/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numWaterBottles(int numBottles, int numExchange) 5 | { 6 | int ans = numBottles, curBottles = 0; 7 | while (true) 8 | { 9 | if (numBottles - numExchange < 0) 10 | { 11 | ans += curBottles; 12 | numBottles += curBottles; 13 | curBottles = 0; 14 | } 15 | curBottles++; 16 | numBottles -= numExchange; 17 | if (numBottles < 0) 18 | break; 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /190-8th_July-Find_winner/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | static int findTheWinner(int n, int k) 5 | { 6 | if (n == 1) 7 | return 1; 8 | return (findTheWinner(n - 1, k) + (k - 1)) % n + 1; 9 | } 10 | }; 11 | 12 | auto init = []() 13 | { 14 | ios::sync_with_stdio(0); 15 | cin.tie(0); 16 | cout.tie(0); 17 | return 'c'; 18 | }(); -------------------------------------------------------------------------------- /191-9th_July-Average_waiting_time/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double averageWaitingTime(vector> &customers) 5 | { 6 | int N = customers.size(); 7 | double serviceTime = customers[0][0] + customers[0][1]; 8 | double totalWait = serviceTime - customers[0][0]; 9 | 10 | for (int i = 1; i < N; i++) 11 | { 12 | if (serviceTime < customers[i][0]) 13 | serviceTime = customers[i][0]; 14 | serviceTime += customers[i][1]; 15 | totalWait += (serviceTime - customers[i][0]); 16 | } 17 | return totalWait / N; 18 | } 19 | }; -------------------------------------------------------------------------------- /192-10th_July-Crawler_log_folder/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | change folder problem, go deeper or go backward in a tree structure. 3 | 4 | 2nd approach uses the recursion, C & C++ codes are implemented in different ways. 5 | 6 | 3rd approach is to try a branchless loop suggested by @Sergei. 7 | 8 | Approach 9 | Set level=0 for the root. 10 | Use a loop to transverse. If dir=="../" level-=(level>0) , else if dir!="./" level++ 11 | level is the answer 12 | Complexity 13 | Time complexity: 14 | O(n) 15 | 16 | Space complexity: 17 | O(1) -------------------------------------------------------------------------------- /192-10th_July-Crawler_log_folder/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | static int minOperations(vector &logs) 5 | { 6 | int level = 0; 7 | for (auto &dir : logs) 8 | { 9 | if (dir == "../") 10 | level -= (level > 0); 11 | else if (dir != "./") 12 | level++; 13 | // cout< luckyNumbers(vector> &matrix) 5 | { 6 | const int m = matrix.size(), n = matrix[0].size(); 7 | vector minPos(m, -1); 8 | for (int i = 0; i < m; i++) 9 | { 10 | int p = min_element(matrix[i].begin(), matrix[i].end()) - matrix[i].begin(); 11 | minPos[i] = p; 12 | } 13 | vector ans; 14 | for (int i = 0; i < m; i++) 15 | { 16 | int p = minPos[i], x = matrix[i][p]; 17 | bool lucky = 1; 18 | for (int j = 0; j < m; j++) 19 | { 20 | if (matrix[j][p] > x) 21 | { 22 | lucky = 0; 23 | break; 24 | } 25 | } 26 | if (lucky) 27 | ans.push_back(x); 28 | } 29 | return ans; 30 | } 31 | }; 32 | 33 | auto init = []() 34 | { 35 | ios::sync_with_stdio(false); 36 | cin.tie(nullptr); 37 | cout.tie(nullptr); 38 | return 'c'; 39 | }(); -------------------------------------------------------------------------------- /202-20th_July-Find_valid_matrix/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach and Intuition 2 | Matrix Construction: We iterate through each cell of the matrix using two nested loops. For each cell (i, j): 3 | 4 | If either rowSum[i] or colSum[j] is 0, we set ans[i][j] to 0, as there is no available sum to allocate to this cell. 5 | Otherwise, we set ans[i][j] to the minimum of rowSum[i] and colSum[j]. This ensures that we do not exceed the required sum for either the current row or the current column. 6 | We then subtract the allocated value from both rowSum[i] and colSum[j] to reflect the remaining sums needed for the rest of the cells in the current row and column. 7 | Return Result: After filling in the entire matrix, we return the ans matrix, which now has the desired row and column sums. 8 | 9 | Complexity 10 | Time complexity: 11 | O(N^2) 12 | 13 | Space complexity: 14 | O(N^2) -------------------------------------------------------------------------------- /202-20th_July-Find_valid_matrix/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> restoreMatrix(vector &rowSum, vector &colSum) 5 | { 6 | int m = rowSum.size(); 7 | int n = colSum.size(); 8 | vector> ans(m, vector(n, 0)); 9 | 10 | for (int i = 0; i < m; i++) 11 | { 12 | for (int j = 0; j < n; j++) 13 | { 14 | if (rowSum[i] == 0 || colSum[j] == 0) 15 | { 16 | ans[i][j] = 0; 17 | } 18 | else 19 | { 20 | ans[i][j] = min(rowSum[i], colSum[j]); 21 | rowSum[i] -= ans[i][j]; 22 | colSum[j] -= ans[i][j]; 23 | } 24 | } 25 | } 26 | 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /204-22nd_July-Sort_the_people/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Since we need to sort the names based on decreasing number of their respective heights, we need to sort the heights. 3 | 4 | Approach 5 | Push the pair of heights and names on to the heap. 6 | Get the names from the heap which will be in the decreasing order of the heights and store them in names vector 7 | Complexity 8 | Time complexity: 9 | O(nlog(n)) 10 | Space complexity: 11 | O(n) -------------------------------------------------------------------------------- /204-22nd_July-Sort_the_people/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector sortPeople(vector &names, vector &heights) 5 | { 6 | const int m = names.size(); 7 | priority_queue> pq; 8 | for (int i = 0; i < m; ++i) 9 | { 10 | pq.push({heights[i], names[i]}); 11 | } 12 | int i = 0; 13 | while (!pq.empty()) 14 | { 15 | names[i++] = pq.top().second; 16 | pq.pop(); 17 | } 18 | return names; 19 | } 20 | }; -------------------------------------------------------------------------------- /205-23rd_July-Sort_array_by_freq/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Given the constraints -100 <= nums[i] <= 100, you can count the frequency of elements using an array where the index represents the value shifted by 100 (i.e., freq[x + 100] for x in nums). Then, sort it using a lambda function, which is efficient in both C++ and Python. 3 | 4 | A similar concept can be applied using the Counter class in Python for a one-liner solution, which is slower but acceptable. 5 | 6 | Another approach involves using counting sort, which reduces the time complexity to O(n + m). 7 | 8 | Approach 9 | Count the frequency of elements using freq[x + 100] for x in nums. Sort nums with respect to the lambda function [&](int x, int y){ return (freq[x + 100] == freq[y + 100]) ? x > y : freq[x + 100] < freq[y + 100]; }. 10 | 11 | The second approach uses counting sort, which is more complex compared to the simpler methods. While it has a linear time complexity, it doesn't provide significant benefits for small test cases. The best performance recorded is 2ms. 12 | 13 | Complexity 14 | Time complexity: 15 | O(nlogn) 16 | Counting sort: O(n+m) 17 | 18 | Space complexity: 19 | O(m) where m=max(nums) -------------------------------------------------------------------------------- /205-23rd_July-Sort_array_by_freq/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | using int2 = array; 5 | vector frequencySort(vector &nums) 6 | { 7 | int n = nums.size(), freq[201] = {0}; 8 | for (int x : nums) 9 | { 10 | freq[x + 100]++; 11 | } 12 | 13 | sort(nums.begin(), nums.end(), [&](int x, int y) 14 | { return (freq[x + 100] == freq[y + 100]) ? x > y : freq[x + 100] < freq[y + 100]; }); 15 | return nums; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /206-24th_July-Sort_jumbled_numbers/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | private: 4 | long long mapStringToInt(string num, vector &mapping) 5 | { 6 | long long res = 0; 7 | 8 | for (int i = 0; i < num.size(); i++) 9 | { 10 | int idx = num[i] - '0'; 11 | res = (res + mapping[idx]) * 10; 12 | } 13 | 14 | res = res / 10; 15 | 16 | return res; 17 | } 18 | 19 | public: 20 | vector sortJumbled(vector &mapping, vector &nums) 21 | { 22 | 23 | auto lambda = [&](auto first, auto second) 24 | { 25 | return mapStringToInt(to_string(first), mapping) < mapStringToInt(to_string(second), mapping); 26 | }; 27 | 28 | sort(nums.begin(), nums.end(), lambda); 29 | 30 | return nums; 31 | } 32 | }; -------------------------------------------------------------------------------- /207-25th_July-Sort_array/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Approach: 2 | Base Case Handling: 3 | 4 | If the array is null or has only one element, it's already sorted. Return the array as is. 5 | Merge Sort Function: 6 | 7 | Recursively divide the array into two halves until each subarray has one element. 8 | Merge the subarrays back together in sorted order. 9 | Merge Function: 10 | 11 | Merge two sorted subarrays into a single sorted array. 12 | Use temporary arrays to hold the elements of the subarrays during merging. -------------------------------------------------------------------------------- /209-27th_July-Min_cost_to_convert/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | step 1: make graph 3 | step 2: Floyd-Warshall algorithm to find the minimum transformation costs between all pairs of characters 4 | 5 | Approach 6 | The goal is to transform the string source into the string target using the minimal cost specified in the cost array. The transformation rules are defined by the original and changed arrays, where original[i] can be changed to changed[i] at a cost of cost[i]. 7 | 8 | Complexity 9 | Time complexity: 10 | O(m+n^3) 11 | 12 | Space complexity: 13 | O(n^2) -------------------------------------------------------------------------------- /211-29th_July-Count_number_of_teams/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Since we can use the same soldier for multiple teams, we just need to find number of ratings less than index i , mumber of ratings greater than index i which are on the left side of the index i and similarly umber of ratings less than index i , mumber of ratings greater than index i which are on the right side of the index i, multiply and add it to the answer. 3 | 4 | Approach 5 | Iterate over the array. 6 | For every index i calculate the following: 7 | lowerThanLeft 8 | higherThanLeft 9 | lowerThanRight 10 | higherThanRight 11 | Multiply lowerThanLeft and higherThanRight, similarly multiply higherThanLeft and lowerThanRight and add it to answer. 12 | Complexity 13 | Time complexity: 14 | O(n^2) 15 | Space complexity: 16 | O(1) -------------------------------------------------------------------------------- /212-30th_July-Min_deletions/approach-explanation.txt: -------------------------------------------------------------------------------- 1 | Intuition 2 | Basically, the problem asks you to have all a before b in string s by deleting minimum number of characters from string s. 3 | The intuition is simple enough. We just need to store how many b come before a at a specific position i in string s. 4 | This will tell us how many a we have to delete which come after b or how many b we have to delete which come before a. 5 | In the end, we will count the minimum number of deletions we have to make in order to achieve the string with all a before b. 6 | Approach 7 | Create a prefix_b array to store all b from left to right and create a suffix_a array to store all a from right to left. 8 | Now, at every index i check how many prefix b and suffix a we have to delete by adding prefix_b[i] and suffix_a[i]. 9 | Keep the track of minimum deletions using a variable mini which will be our final answer to return. 10 | Complexity 11 | Time complexity: O(n) 12 | Space complexity: O(n) -------------------------------------------------------------------------------- /212-30th_July-Min_deletions/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minimumDeletions(string s) 5 | { 6 | vector prefix_b(s.size() + 2, 0), suffix_a(s.size() + 2, 0); 7 | prefix_b[0] = 0; 8 | suffix_a[suffix_a.size() - 1] = 0; 9 | 10 | for (int i = 1; i < prefix_b.size() - 1; i++) 11 | { 12 | if (s[i - 1] == 'b') 13 | { 14 | prefix_b[i + 1] = prefix_b[i] + 1; 15 | } 16 | else 17 | { 18 | prefix_b[i + 1] = prefix_b[i] + 0; 19 | } 20 | } 21 | 22 | for (int i = s.size(); i >= 1; i--) 23 | { 24 | if (s[i - 1] == 'a') 25 | { 26 | suffix_a[i - 1] = suffix_a[i] + 1; 27 | } 28 | else 29 | { 30 | suffix_a[i - 1] = suffix_a[i] + 0; 31 | } 32 | } 33 | 34 | int mini = INT_MAX; 35 | 36 | for (int i = 0; i < s.size() + 2; i++) 37 | { 38 | mini = min(prefix_b[i] + suffix_a[i], mini); 39 | } 40 | 41 | return mini; 42 | } 43 | }; -------------------------------------------------------------------------------- /213-31st_July-Filling_bookcase_shelves/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minHeightShelves(vector> &books, int shelfWidth) 5 | { 6 | int n = books.size(); 7 | int f[n + 1]; 8 | f[0] = 0; 9 | for (int i = 1; i <= n; ++i) 10 | { 11 | int w = books[i - 1][0], h = books[i - 1][1]; 12 | f[i] = f[i - 1] + h; 13 | for (int j = i - 1; j > 0; --j) 14 | { 15 | w += books[j - 1][0]; 16 | if (w > shelfWidth) 17 | { 18 | break; 19 | } 20 | h = max(h, books[j - 1][1]); 21 | f[i] = min(f[i], f[j - 1] + h); 22 | } 23 | } 24 | return f[n]; 25 | } 26 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Sarthak Sachdev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 365 day code challenge 2 | 3 | This repository features solutions to daily LeetCode problems. Each day, an optimized solution with an explanation is added, showcasing problem-solving skills and coding proficiency. This ongoing project demonstrates commitment to continuous learning and improvement in algorithmic thinking and coding expertise. 4 | 5 | Such a repository has been created to ensure consistency in practice and to aid in mastering data structures and algorithms. It serves as a personal learning tool and a resource for others looking to enhance their coding skills. 6 | --------------------------------------------------------------------------------